DeepSeekService.php 771 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. private $gemini_text_models;
  29. protected $aiImageGenerationService;
  30. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  33. $this->api_key = env('DEEPSEEK_API_KEY');
  34. $this->headers = [
  35. 'Authorization' => 'Bearer '.$this->api_key,
  36. 'Content-Type' => 'application/json; charset=UTF-8'
  37. ];
  38. // 火山引擎模型列表
  39. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  40. // GPT文本模型列表
  41. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  42. // Gemini文本模型列表
  43. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  44. $this->sys_message = [
  45. 'role' => 'system',
  46. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  47. 强制要求:\n
  48. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  49. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  50. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  51. 普通要求:\n
  52. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  53. 2.<分集剧本>的要求如下:
  54.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  55.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  56.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  57.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  58. \n\n
  59. 示例如下:\n
  60. ###剧本名:西昆仑
  61. ###故事梗概
  62. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  63. ###剧本亮点
  64. 亮点1:绝境奇药,生死一线
  65. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  66. 亮点2:结拜兄妹,化解尴尬
  67. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  68. 亮点3:纤发夺命,情愫暗涌
  69. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  70. ###人物关系
  71. 阿雪与梁萧之间存在兄妹之情。
  72. ###核心矛盾
  73. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  74. ###主体列表
  75. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  76. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  77. 阴阳球:天地异宝,能化生精气,救人于危难。
  78. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  79. ###美术风格
  80. 基础画风风格词:厚涂古风
  81. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  82. ###场景列表
  83. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  84. ###分集剧本
  85. ##分集01
  86. 第1集: 第一集的标题
  87. 场景描述:地点、时间、场景
  88. 运镜:固定近距离
  89. 出场角色:男主、女主
  90. 台词内容:
  91. 女主: 女主对话
  92. 男主:男主对话
  93. 女主: 女主对话
  94. 男主: 男主对话
  95. ##分集02
  96. 第2集: 第二集的标题
  97. 场景描述:地点、时间、场景
  98. 运镜:固定近距离
  99. 出场角色:男主、女主
  100. 台词内容:
  101. 女主: 女主对话
  102. 男主:男主对话
  103. 女主: 女主对话
  104. 男主: 男主对话"
  105. ];
  106. }
  107. /**
  108. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  109. *
  110. * @param array $data 请求参数
  111. * @return \Generator 返回生成器,用于流式输出
  112. */
  113. public function generateText($data) {
  114. // 获取请求参数
  115. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  116. $messages = getProp($data, 'messages', []);
  117. $systemPrompt = getProp($data, 'system_prompt', '');
  118. $prompt = getProp($data, 'prompt', '');
  119. $images = getProp($data, 'images', []); // 支持多张图片
  120. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  121. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  122. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  123. $isGeminiModel = in_array($model, $this->gemini_text_models);
  124. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  125. Utils::throwError('20003:仅Gemini模型支持视频输入');
  126. }
  127. // 如果没有提供messages,则根据system_prompt、content和images构建
  128. if (empty($messages)) {
  129. $messages = [];
  130. // 添加系统提示词
  131. if (!empty($systemPrompt)) {
  132. $messages[] = [
  133. 'role' => 'system',
  134. 'content' => $systemPrompt
  135. ];
  136. }
  137. // 构建用户消息内容(支持文本+图片)
  138. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  139. $userMessage = [
  140. 'role' => 'user',
  141. 'content' => []
  142. ];
  143. // 添加文本内容
  144. if (!empty($prompt)) {
  145. $userMessage['content'][] = [
  146. 'type' => 'text',
  147. 'text' => $prompt
  148. ];
  149. }
  150. // 处理上传的图片文件
  151. if (!empty($images)) {
  152. if (!is_array($images)) {
  153. $images = [$images];
  154. }
  155. foreach ($images as $image) {
  156. $imageBase64 = $this->processImageToBase64($image);
  157. if ($imageBase64) {
  158. $userMessage['content'][] = [
  159. 'type' => 'image_url',
  160. 'image_url' => [
  161. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  162. ]
  163. ];
  164. }
  165. }
  166. }
  167. // 处理图片URL
  168. if (!empty($imageUrls)) {
  169. if (!is_array($imageUrls)) {
  170. $imageUrls = [$imageUrls];
  171. }
  172. foreach ($imageUrls as $url) {
  173. if (!empty($url)) {
  174. $userMessage['content'][] = [
  175. 'type' => 'image_url',
  176. 'image_url' => [
  177. 'url' => $url
  178. ]
  179. ];
  180. }
  181. }
  182. }
  183. // 处理上传的视频文件(仅 Gemini)
  184. if (!empty($videos) && $isGeminiModel) {
  185. if (!is_array($videos)) {
  186. $videos = [$videos];
  187. }
  188. foreach ($videos as $video) {
  189. $inlineData = $this->processMediaToInlineData($video);
  190. if ($inlineData) {
  191. $userMessage['content'][] = [
  192. 'type' => 'video',
  193. 'inline_data' => $inlineData
  194. ];
  195. }
  196. }
  197. }
  198. // 处理视频URL(仅 Gemini)
  199. if (!empty($videoUrls) && $isGeminiModel) {
  200. if (!is_array($videoUrls)) {
  201. $videoUrls = [$videoUrls];
  202. }
  203. foreach ($videoUrls as $url) {
  204. if (!empty($url)) {
  205. $userMessage['content'][] = [
  206. 'type' => 'video_url',
  207. 'video_url' => ['url' => $url]
  208. ];
  209. }
  210. }
  211. }
  212. // 如果只有文本内容,简化为字符串格式
  213. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  214. $userMessage['content'] = $userMessage['content'][0]['text'];
  215. }
  216. $messages[] = $userMessage;
  217. }
  218. }
  219. // 验证messages不为空
  220. if (empty($messages)) {
  221. Utils::throwError('20003:请提供有效的对话内容');
  222. }
  223. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  224. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  225. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  226. if ($model === 'deepseek-chat') {
  227. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  228. $model = 'deepseek-v4-flash';
  229. $thinkingMode = 'disabled';
  230. } elseif ($model === 'deepseek-reasoner') {
  231. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  232. $model = 'deepseek-v4-flash';
  233. $thinkingMode = 'enabled';
  234. }
  235. // 构建请求参数
  236. $post_data = [
  237. 'model' => $model,
  238. 'messages' => $messages,
  239. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  240. 'temperature' => getProp($data, 'temperature', 1),
  241. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  242. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  243. 'thinking' => ['type' => $thinkingMode],
  244. 'stream' => true // 启用流式输出
  245. ];
  246. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  247. // 添加可选参数
  248. if (isset($data['top_p'])) {
  249. $post_data['top_p'] = $data['top_p'];
  250. }
  251. if (isset($data['response_format'])) {
  252. $post_data['response_format'] = $data['response_format'];
  253. }
  254. // 根据模型类型选择调用方法
  255. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  256. // DeepSeek 官方模型使用 DeepSeek API
  257. return $this->deepSeekStreamResponse($post_data);
  258. } else if (in_array($model, $this->gpt_text_models)) {
  259. // GPT 模型使用 TokenRouter API
  260. return $this->gpt54StreamResponse($post_data);
  261. } else if (in_array($model, $this->gemini_text_models)) {
  262. // Gemini 模型使用 Gemini API
  263. return $this->geminiStreamResponse($post_data, $model);
  264. } else if (in_array($model, $this->valid_text_models)) {
  265. // 火山引擎支持的模型使用火山引擎 API
  266. return $this->volcEngineChatCompletion($post_data);
  267. } else {
  268. Utils::throwError('20003:不支持的模型: ' . $model);
  269. }
  270. }
  271. public function createGenerateText($data) {
  272. $file = getProp($data, 'file');
  273. $uid = Site::getUid();
  274. $cpid = Site::getCpid();
  275. if (!$file) {
  276. Utils::throwError('20003:请上传文件');
  277. }
  278. // 提取文件内容
  279. $content = $this->extractFileContent($file);
  280. if (!$content) {
  281. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  282. }
  283. // 获取原始文件名(不含扩展名)作为script_name
  284. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  285. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  286. // 字节安全剥离,不依赖服务器locale设置
  287. $originalName = $file->getClientOriginalName();
  288. $extension = $file->getClientOriginalExtension();
  289. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  290. ? substr($originalName, 0, -strlen($extension) - 1)
  291. : $originalName;
  292. if ($script_name === '') {
  293. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  294. }
  295. // 如果同一用户的剧本名存在则提示
  296. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  297. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  298. }
  299. // 插入数据到mp_scripts表
  300. $script_id = DB::table('mp_scripts')->insertGetId([
  301. 'script_name' => $script_name,
  302. 'user_id' => $uid,
  303. 'cpid' => $cpid,
  304. 'content' => $content,
  305. 'created_at' => date('Y-m-d H:i:s'),
  306. 'updated_at' => date('Y-m-d H:i:s')
  307. ]);
  308. return [
  309. 'script_id' => $script_id,
  310. 'script_name' => $script_name
  311. ];
  312. }
  313. /**
  314. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  315. *
  316. * @param array $data 请求参数
  317. * @return array 返回结果数组
  318. */
  319. public function newGenerateText($data) {
  320. // 获取请求参数
  321. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  322. $messages = getProp($data, 'messages', []);
  323. $systemPrompt = getProp($data, 'system_prompt', '');
  324. $prompt = getProp($data, 'prompt', '');
  325. $images = getProp($data, 'images', []); // 支持多张图片
  326. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  327. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  328. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  329. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  330. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  331. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  332. $generateTaskId = 0;
  333. if ($script_id > 0) {
  334. $uid = Site::getUid();
  335. $existingTask = DB::table('mp_script_generate_tasks')
  336. ->where('uid', $uid)
  337. ->where('script_id', $script_id)
  338. ->orderByDesc('id')
  339. ->first();
  340. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  341. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  342. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  343. }
  344. }
  345. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  346. $originalContent = '';
  347. if ($script_id > 0) {
  348. $script = DB::table('mp_scripts')
  349. ->where('id', $script_id)
  350. ->where('is_deleted', 0)
  351. ->first();
  352. if (!$script) {
  353. Utils::throwError('20003:剧本不存在或已删除');
  354. }
  355. $originalContent = $script->content ?? '';
  356. if (empty($originalContent)) {
  357. Utils::throwError('20003:剧本内容为空');
  358. }
  359. // 将剧本内容添加到提示词前面
  360. if (!empty($originalContent)) {
  361. if (!empty($prompt)) {
  362. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  363. } else {
  364. $prompt = "原文内容:\n" . $originalContent;
  365. }
  366. }
  367. }
  368. // 新增: 如果提供了template_id,从数据库获取template_prompt
  369. if ($templateId > 0) {
  370. $template = DB::table('mp_prompt_templates')
  371. ->where('id', $templateId)
  372. ->where('is_deleted', 0)
  373. ->first();
  374. if (!$template) {
  375. Utils::throwError('20003:模板不存在或已删除');
  376. }
  377. $templatePrompt = $template->template_prompt ?? '';
  378. // 将模板提示词和用户输入的prompt组合
  379. // 模板为准,用户输入作为补充要求
  380. if (!empty($templatePrompt)) {
  381. if (!empty($prompt)) {
  382. $prompt = $templatePrompt . "\n\n" . $prompt;
  383. } else {
  384. $prompt = $templatePrompt;
  385. }
  386. }
  387. }
  388. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  389. if (empty($messages)) {
  390. $messages = [];
  391. // 添加系统提示词
  392. if (!empty($systemPrompt)) {
  393. $messages[] = [
  394. 'role' => 'system',
  395. 'content' => $systemPrompt
  396. ];
  397. }
  398. // 构建用户消息内容(支持文本+图片)
  399. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  400. $userMessage = [
  401. 'role' => 'user',
  402. 'content' => []
  403. ];
  404. // 添加文本内容
  405. if (!empty($prompt)) {
  406. $userMessage['content'][] = [
  407. 'type' => 'text',
  408. 'text' => $prompt
  409. ];
  410. }
  411. // 处理上传的图片文件
  412. if (!empty($images)) {
  413. if (!is_array($images)) {
  414. $images = [$images];
  415. }
  416. foreach ($images as $image) {
  417. $imageBase64 = $this->processImageToBase64($image);
  418. if ($imageBase64) {
  419. $userMessage['content'][] = [
  420. 'type' => 'image_url',
  421. 'image_url' => [
  422. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  423. ]
  424. ];
  425. }
  426. }
  427. }
  428. // 处理图片URL
  429. if (!empty($imageUrls)) {
  430. if (!is_array($imageUrls)) {
  431. $imageUrls = [$imageUrls];
  432. }
  433. foreach ($imageUrls as $url) {
  434. if (!empty($url)) {
  435. $userMessage['content'][] = [
  436. 'type' => 'image_url',
  437. 'image_url' => [
  438. 'url' => $url
  439. ]
  440. ];
  441. }
  442. }
  443. }
  444. // 如果只有文本内容,简化为字符串格式
  445. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  446. $userMessage['content'] = $userMessage['content'][0]['text'];
  447. }
  448. $messages[] = $userMessage;
  449. }
  450. }
  451. // 验证messages不为空
  452. if (empty($messages)) {
  453. Utils::throwError('20003:请提供有效的对话内容');
  454. }
  455. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  456. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  457. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  458. if ($model === 'deepseek-chat') {
  459. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  460. $model = 'deepseek-v4-flash';
  461. $thinkingMode = 'disabled';
  462. } elseif ($model === 'deepseek-reasoner') {
  463. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  464. $model = 'deepseek-v4-flash';
  465. $thinkingMode = 'enabled';
  466. }
  467. // 构建请求参数(非流式)
  468. $post_data = [
  469. 'model' => $model,
  470. 'messages' => $messages,
  471. 'temperature' => getProp($data, 'temperature', 1),
  472. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  473. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  474. 'thinking' => ['type' => $thinkingMode],
  475. 'stream' => false // 非流式输出
  476. ];
  477. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  478. // 添加可选参数
  479. if (isset($data['top_p'])) {
  480. $post_data['top_p'] = $data['top_p'];
  481. }
  482. // 新增: 根据response_format设置响应格式
  483. if ($responseFormat === 'json') {
  484. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  485. $hasJsonKeyword = false;
  486. foreach ($post_data['messages'] as $message) {
  487. if (isset($message['content'])) {
  488. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  489. if (stripos($content, 'json') !== false) {
  490. $hasJsonKeyword = true;
  491. break;
  492. }
  493. }
  494. }
  495. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  496. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  497. if (!$hasJsonKeyword) {
  498. $lastMessageIndex = count($post_data['messages']) - 1;
  499. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  500. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  501. // 如果content是字符串,直接追加
  502. if (is_string($lastContent)) {
  503. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  504. }
  505. // 如果content是数组(包含文本和图片),在文本部分追加
  506. else if (is_array($lastContent)) {
  507. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  508. if ($contentPart['type'] === 'text') {
  509. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  510. break;
  511. }
  512. }
  513. }
  514. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  515. }
  516. }
  517. // 设置response_format参数(所有支持的模型)
  518. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  519. // DeepSeek模型
  520. $post_data['response_format'] = ['type' => 'json_object'];
  521. } else if (in_array($model, $this->gpt_text_models)) {
  522. // GPT模型
  523. $post_data['response_format'] = ['type' => 'json_object'];
  524. } else if (in_array($model, $this->valid_text_models)) {
  525. // 火山引擎模型
  526. $post_data['response_format'] = ['type' => 'json_object'];
  527. }
  528. }
  529. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  530. if ($script_id > 0) {
  531. $uid = Site::getUid();
  532. // 创建新的生成任务
  533. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  534. 'uid' => $uid,
  535. 'script_id' => $script_id,
  536. 'sequence' => $sequence,
  537. 'status' => 'processing',
  538. 'prompt' => getProp($data, 'prompt', ''),
  539. 'started_at' => date('Y-m-d H:i:s'),
  540. 'created_at' => date('Y-m-d H:i:s'),
  541. 'updated_at' => date('Y-m-d H:i:s')
  542. ]);
  543. }
  544. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  545. try {
  546. $aiResult = null;
  547. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  548. // DeepSeek 官方模型使用现有的 chatOnly 方法
  549. $result = $this->chatOnly($post_data);
  550. // 记录实际使用的模型
  551. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  552. $aiResult = [
  553. 'content' => $result['fullContent'],
  554. 'reasoning_content' => $result['fullReasoningContent'],
  555. 'usage' => $result['usage'],
  556. 'model' => $model,
  557. 'finish_reason' => 'stop'
  558. ];
  559. } else if (in_array($model, $this->gpt_text_models)) {
  560. // GPT 模型使用现有的 gpt54ChatOnly 方法
  561. $result = $this->gpt54ChatOnly($post_data);
  562. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  563. $aiResult = [
  564. 'content' => $result['fullContent'],
  565. 'reasoning_content' => '',
  566. 'usage' => $result['usage'],
  567. 'model' => $model,
  568. 'finish_reason' => 'stop'
  569. ];
  570. } else if (in_array($model, $this->gemini_text_models)) {
  571. // Gemini 模型使用 Gemini API(非流式)
  572. $result = $this->geminiChatOnly($post_data, $model);
  573. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  574. $aiResult = [
  575. 'content' => $result['fullContent'],
  576. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  577. 'usage' => $result['usage'],
  578. 'model' => $model,
  579. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  580. ];
  581. } else if (in_array($model, $this->valid_text_models)) {
  582. // 火山引擎支持的模型使用火山引擎 API(非流式)
  583. $post_data['stream'] = false;
  584. $result = $this->volcEngineChatCompletion($post_data);
  585. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  586. 'requested_model' => $model,
  587. 'result_keys' => array_keys($result),
  588. 'has_fullContent' => isset($result['fullContent']),
  589. 'has_content' => isset($result['content'])
  590. ]);
  591. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  592. $aiResult = [
  593. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  594. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  595. 'usage' => $result['usage'] ?? [],
  596. 'model' => $model,
  597. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  598. ];
  599. } else {
  600. Utils::throwError('20003:不支持的模型: ' . $model);
  601. }
  602. } catch (\Exception $e) {
  603. // 生成失败,更新任务状态
  604. if ($generateTaskId) {
  605. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  606. 'status' => 'failed',
  607. 'error_message' => $e->getMessage(),
  608. 'completed_at' => date('Y-m-d H:i:s'),
  609. 'updated_at' => date('Y-m-d H:i:s')
  610. ]);
  611. }
  612. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  613. }
  614. // 生成成功,更新任务状态
  615. if ($generateTaskId && $aiResult) {
  616. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  617. 'status' => 'success',
  618. 'result' => getProp($aiResult, 'content', ''),
  619. 'completed_at' => date('Y-m-d H:i:s'),
  620. 'updated_at' => date('Y-m-d H:i:s')
  621. ]);
  622. $aiResult['generate_task_id'] = $generateTaskId;
  623. }
  624. // 新增: 如果提供了script_id,保存对话记录
  625. if ($script_id > 0 && $aiResult) {
  626. try {
  627. $uid = Site::getUid();
  628. $now = now();
  629. // 获取用户原始的prompt(不包含剧本内容)
  630. $originalPrompt = getProp($data, 'prompt', '');
  631. $recordsToInsert = [
  632. [
  633. 'uid' => $uid,
  634. 'script_id' => $script_id,
  635. 'sequence' => $sequence,
  636. 'role' => 'user',
  637. 'content' => $originalPrompt,
  638. 'created_at' => $now,
  639. 'updated_at' => $now,
  640. ],
  641. [
  642. 'uid' => $uid,
  643. 'script_id' => $script_id,
  644. 'sequence' => $sequence,
  645. 'role' => 'assistant',
  646. 'content' => $aiResult['content'],
  647. 'created_at' => $now,
  648. 'updated_at' => $now,
  649. ]
  650. ];
  651. DB::table('mp_script_records')->insert($recordsToInsert);
  652. // 获取刚插入的记录ID(假设按插入顺序返回)
  653. $insertedRecords = DB::table('mp_script_records')
  654. ->where('uid', $uid)
  655. ->where('script_id', $script_id)
  656. ->where('sequence', $sequence)
  657. ->orderBy('id', 'desc')
  658. ->limit(2)
  659. ->get()
  660. ->map(function ($record) {
  661. return [
  662. 'rid' => $record->id,
  663. 'script_id' => $record->script_id,
  664. 'sequence' => $record->sequence,
  665. 'role' => $record->role,
  666. 'content' => $record->content,
  667. 'created_at' => $record->created_at,
  668. ];
  669. })
  670. ->reverse()
  671. ->values()
  672. ->toArray();
  673. // 将记录信息添加到返回结果中
  674. $aiResult['records'] = $insertedRecords;
  675. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  676. } catch (\Exception $e) {
  677. // 记录错误但不影响主流程
  678. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  679. }
  680. }
  681. return $aiResult;
  682. }
  683. /**
  684. * 通用 Gemini 文生文方法(支持流式和非流式)
  685. *
  686. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  687. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  688. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  689. * system_prompt 系统提示词(可选)
  690. * prompt 用户提示词(可选)
  691. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  692. * image_urls 图片/视频URL列表(可选,同上)
  693. * temperature 温度(可选,默认 1)
  694. * top_p 核采样(可选)
  695. * max_tokens 最大输出 token(可选,默认 8192)
  696. * response_format text/json(可选)
  697. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  698. * thinking_budget 思考预算(可选,默认 20)
  699. * stream 是否流式(可选,默认 false)
  700. *
  701. * @param array $data 请求参数
  702. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  703. */
  704. public function geminiGenerateText($data) {
  705. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  706. $isStream = (bool)getProp($data, 'stream', false);
  707. if (!in_array($model, $this->gemini_text_models)) {
  708. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  709. }
  710. $requestData = $this->buildGeminiRequestBody($data, $model);
  711. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  712. if ($isStream) {
  713. // 流式返回生成器
  714. return $this->geminiStreamResponse($requestData, $model);
  715. }
  716. // 非流式
  717. return $this->geminiChatOnly($requestData, $model);
  718. }
  719. /**
  720. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  721. */
  722. private function geminiMediaMaxBytes() {
  723. return 14 * 1024 * 1024;
  724. }
  725. /**
  726. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  727. */
  728. private function buildGeminiRequestBody($data, $model) {
  729. $messages = getProp($data, 'messages', []);
  730. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  731. if (empty($messages)) {
  732. $systemPrompt = getProp($data, 'system_prompt', '');
  733. $prompt = getProp($data, 'prompt', '');
  734. $images = getProp($data, 'images', []);
  735. $imageUrls = getProp($data, 'image_urls', []);
  736. $messages = [];
  737. if (!empty($systemPrompt)) {
  738. $messages[] = [
  739. 'role' => 'system',
  740. 'content' => $systemPrompt
  741. ];
  742. }
  743. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  744. $userMessage = ['role' => 'user', 'content' => []];
  745. if (!empty($prompt)) {
  746. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  747. }
  748. if (!empty($images)) {
  749. if (!is_array($images)) {
  750. $images = [$images];
  751. }
  752. foreach ($images as $image) {
  753. $inlineData = $this->processMediaToInlineData($image);
  754. if ($inlineData) {
  755. $userMessage['content'][] = [
  756. 'type' => 'image',
  757. 'inline_data' => $inlineData
  758. ];
  759. }
  760. }
  761. }
  762. if (!empty($imageUrls)) {
  763. if (!is_array($imageUrls)) {
  764. $imageUrls = [$imageUrls];
  765. }
  766. foreach ($imageUrls as $url) {
  767. if (!empty($url)) {
  768. $inlineData = $this->processMediaToInlineData($url);
  769. if ($inlineData) {
  770. $userMessage['content'][] = [
  771. 'type' => 'image',
  772. 'inline_data' => $inlineData
  773. ];
  774. }
  775. }
  776. }
  777. }
  778. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  779. $userMessage['content'] = $userMessage['content'][0]['text'];
  780. }
  781. $messages[] = $userMessage;
  782. }
  783. }
  784. if (empty($messages)) {
  785. Utils::throwError('20003:请提供有效的对话内容');
  786. }
  787. // 转换为 Gemini contents 格式
  788. $systemInstruction = '';
  789. $contents = [];
  790. foreach ($messages as $message) {
  791. $role = getProp($message, 'role', 'user');
  792. $content = getProp($message, 'content', '');
  793. if ($role === 'system') {
  794. if (is_array($content)) {
  795. $systemInstruction = $this->extractGeminiTextFromParts($content);
  796. } else {
  797. $systemInstruction = (string)$content;
  798. }
  799. continue;
  800. }
  801. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  802. $parts = [];
  803. if (is_array($content)) {
  804. foreach ($content as $part) {
  805. $partType = getProp($part, 'type', 'text');
  806. if ($partType === 'text') {
  807. $text = (string)getProp($part, 'text', '');
  808. if ($text !== '') {
  809. $parts[] = ['text' => $text];
  810. }
  811. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  812. if (in_array($partType, ['image_url', 'video_url'])) {
  813. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  814. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  815. } elseif (isset($part['inline_data'])) {
  816. // 已处理过的 inline_data 直接使用
  817. $parts[] = ['inline_data' => $part['inline_data']];
  818. continue;
  819. } else {
  820. $url = '';
  821. }
  822. $inlineData = $this->processMediaToInlineData($url);
  823. if ($inlineData) {
  824. $parts[] = ['inline_data' => $inlineData];
  825. }
  826. }
  827. }
  828. } else {
  829. $text = (string)$content;
  830. if ($text !== '') {
  831. $parts[] = ['text' => $text];
  832. }
  833. }
  834. if (!empty($parts)) {
  835. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  836. }
  837. }
  838. if (empty($contents)) {
  839. Utils::throwError('20003:请提供有效的对话内容');
  840. }
  841. // 构建生成配置
  842. $generationConfig = [];
  843. if (getProp($data, 'temperature', null) !== null) {
  844. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  845. }
  846. if (getProp($data, 'top_p', null) !== null) {
  847. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  848. }
  849. if (getProp($data, 'frequency_penalty', null) !== null) {
  850. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  851. }
  852. if (getProp($data, 'presence_penalty', null) !== null) {
  853. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  854. }
  855. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  856. if ($maxOutputTokens <= 0) {
  857. $maxOutputTokens = 8192;
  858. }
  859. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  860. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  861. $maxOutputTokens = 32768;
  862. }
  863. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  864. // response_format 映射:text -> text/plain,json -> application/json
  865. $responseFormat = getProp($data, 'response_format', 'text');
  866. if (is_array($responseFormat)) {
  867. $responseFormat = getProp($responseFormat, 'type', 'text');
  868. }
  869. if (in_array($responseFormat, ['json', 'json_object'])) {
  870. $generationConfig['responseMimeType'] = 'application/json';
  871. } else {
  872. $generationConfig['responseMimeType'] = 'text/plain';
  873. }
  874. $requestData = [
  875. 'contents' => $contents,
  876. 'generationConfig' => $generationConfig,
  877. ];
  878. if ($systemInstruction !== '') {
  879. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  880. }
  881. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  882. $thinkingMode = getProp($data, 'thinking', null);
  883. if (is_array($thinkingMode)) {
  884. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  885. }
  886. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  887. if ($thinkingMode === null) {
  888. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  889. }
  890. if ($thinkingMode === 'enabled') {
  891. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  892. if ($thinkingBudget <= 0) {
  893. $thinkingBudget = 20;
  894. }
  895. $requestData['generationConfig']['thinkingConfig'] = [
  896. 'thinkingBudget' => $thinkingBudget
  897. ];
  898. } elseif ($defaultThinking) {
  899. // 该模型仅支持思考模式,传 0 会返回 400
  900. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  901. } else {
  902. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  903. }
  904. return $requestData;
  905. }
  906. /**
  907. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  908. *
  909. * 模型名 -> env 变量名映射:
  910. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  911. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  912. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  913. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  914. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  915. */
  916. private function getGeminiApiKey($model) {
  917. $map = [
  918. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  919. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  920. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  921. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  922. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  923. ];
  924. if (isset($map[$model])) {
  925. $key = env($map[$model]);
  926. if (!empty($key)) {
  927. return $key;
  928. }
  929. }
  930. return env('GEMINI_API_KEY', '');
  931. }
  932. /**
  933. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  934. */
  935. private function geminiChatOnly($requestData, $model) {
  936. $apiKey = $this->getGeminiApiKey($model);
  937. if (empty($apiKey)) {
  938. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  939. }
  940. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  941. if (isset($requestData['messages'])) {
  942. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  943. }
  944. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  945. . '/models/' . $model . ':generateContent';
  946. $client = new Client(['timeout' => 1800, 'verify' => false]);
  947. $headers = [
  948. 'Authorization' => 'Bearer ' . $apiKey,
  949. 'Content-Type' => 'application/json'
  950. ];
  951. $maxRetries = $this->gptRetryTimes();
  952. $interval = $this->gptRetryInterval();
  953. $attempt = 0;
  954. while (true) {
  955. try {
  956. $response = $client->post($url, [
  957. 'json' => $requestData,
  958. 'headers' => $headers
  959. ]);
  960. $responseArr = json_decode($response->getBody()->getContents(), true);
  961. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  962. $fullContent = $this->extractGeminiContent($responseArr);
  963. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  964. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  965. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  966. ? $responseArr['candidates'][0]['finishReason']
  967. : '';
  968. return [
  969. 'fullContent' => $fullContent,
  970. 'fullReasoningContent' => $fullReasoningContent,
  971. 'usage' => $usage,
  972. 'finish_reason' => $finishReason
  973. ];
  974. } catch (\Exception $e) {
  975. $retryable = true;
  976. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  977. $status = $e->getResponse()->getStatusCode();
  978. $retryable = $status >= 500 || $status == 429;
  979. }
  980. if (!$retryable || $attempt >= $maxRetries) {
  981. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  982. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  983. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  984. }
  985. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  986. 'retry' => $attempt + 1,
  987. 'max_retries' => $maxRetries,
  988. 'error' => $e->getMessage()
  989. ]);
  990. sleep($interval);
  991. $attempt++;
  992. }
  993. }
  994. }
  995. /**
  996. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  997. */
  998. private function geminiStreamResponse($requestData, $model) {
  999. $apiKey = $this->getGeminiApiKey($model);
  1000. if (empty($apiKey)) {
  1001. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1002. }
  1003. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1004. if (isset($requestData['messages'])) {
  1005. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1006. }
  1007. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1008. . '/models/' . $model . ':generateContent?alt=sse';
  1009. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1010. $headers = [
  1011. 'Authorization' => 'Bearer ' . $apiKey,
  1012. 'Content-Type' => 'application/json'
  1013. ];
  1014. try {
  1015. $response = $client->post($url, [
  1016. 'json' => $requestData,
  1017. 'headers' => $headers,
  1018. 'stream' => true
  1019. ]);
  1020. $body = $response->getBody();
  1021. $fullContent = '';
  1022. $fullReasoningContent = '';
  1023. $usage = [];
  1024. $buffer = '';
  1025. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1026. while (!$body->eof()) {
  1027. $chunk = $body->read(1024);
  1028. $buffer .= $chunk;
  1029. $lines = explode("\n", $buffer);
  1030. $buffer = array_pop($lines);
  1031. foreach ($lines as $line) {
  1032. $line = trim($line);
  1033. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1034. continue;
  1035. }
  1036. $data = substr($line, 6);
  1037. if ($data === '[DONE]') {
  1038. break 2;
  1039. }
  1040. try {
  1041. $json = json_decode($data, true);
  1042. if (json_last_error() !== JSON_ERROR_NONE) {
  1043. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1044. continue;
  1045. }
  1046. // 思考内容(thoughts)
  1047. $thoughts = $this->extractGeminiThoughts($json);
  1048. if ($thoughts !== '') {
  1049. $fullReasoningContent .= $thoughts;
  1050. yield [
  1051. 'type' => 'reasoning',
  1052. 'content' => $thoughts,
  1053. 'full_reasoning' => $fullReasoningContent
  1054. ];
  1055. }
  1056. // 回答内容
  1057. $partText = $this->extractGeminiContent($json);
  1058. if ($partText !== '') {
  1059. $fullContent .= $partText;
  1060. yield [
  1061. 'type' => 'content',
  1062. 'content' => $partText,
  1063. ];
  1064. }
  1065. // 使用统计
  1066. if (isset($json['usageMetadata'])) {
  1067. $usage = $json['usageMetadata'];
  1068. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1069. }
  1070. } catch (\Exception $e) {
  1071. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1072. continue;
  1073. }
  1074. }
  1075. }
  1076. dLog('deepseek')->info('Gemini流式读取完成', [
  1077. 'content_length' => strlen($fullContent),
  1078. 'reasoning_length' => strlen($fullReasoningContent)
  1079. ]);
  1080. yield [
  1081. 'type' => 'done',
  1082. 'full_content' => $fullContent,
  1083. 'full_reasoning' => $fullReasoningContent,
  1084. 'usage' => $usage
  1085. ];
  1086. } catch (\Exception $e) {
  1087. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1088. yield [
  1089. 'type' => 'error',
  1090. 'msg' => $e->getMessage(),
  1091. 'code' => $e->getCode()
  1092. ];
  1093. }
  1094. }
  1095. /**
  1096. * 从 Gemini 响应中提取回答文本
  1097. */
  1098. private function extractGeminiContent($responseArr) {
  1099. $text = '';
  1100. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1101. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1102. if (isset($part['text'])) {
  1103. $text .= $part['text'];
  1104. }
  1105. }
  1106. }
  1107. return $text;
  1108. }
  1109. /**
  1110. * 从 Gemini 响应中提取思考内容
  1111. */
  1112. private function extractGeminiReasoningContent($responseArr) {
  1113. $reasoning = '';
  1114. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1115. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1116. if (isset($thought['text'])) {
  1117. $reasoning .= $thought['text'];
  1118. }
  1119. }
  1120. }
  1121. return $reasoning;
  1122. }
  1123. /**
  1124. * 从 Gemini 流式响应中提取本次增量思考内容
  1125. */
  1126. private function extractGeminiThoughts($responseArr) {
  1127. $thoughts = '';
  1128. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1129. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1130. if (isset($thought['text'])) {
  1131. $thoughts .= $thought['text'];
  1132. }
  1133. }
  1134. }
  1135. return $thoughts;
  1136. }
  1137. /**
  1138. * 提取消息数组中的纯文本
  1139. */
  1140. private function extractGeminiTextFromParts($parts) {
  1141. $text = '';
  1142. if (is_array($parts)) {
  1143. foreach ($parts as $part) {
  1144. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1145. $text .= (string)getProp($part, 'text', '');
  1146. }
  1147. }
  1148. }
  1149. return $text;
  1150. }
  1151. /**
  1152. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1153. *
  1154. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1155. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1156. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1157. *
  1158. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1159. * @return array|null ['mime_type' => string, 'data' => string]
  1160. */
  1161. private function processMediaToInlineData($media) {
  1162. if (empty($media)) {
  1163. return null;
  1164. }
  1165. $localPath = null;
  1166. $isTempFile = false;
  1167. try {
  1168. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1169. if (is_string($media) && strpos($media, 'data:') === 0) {
  1170. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1171. return [
  1172. 'mime_type' => $matches[1],
  1173. 'data' => $matches[2]
  1174. ];
  1175. }
  1176. return null;
  1177. }
  1178. // 2. 获取本地文件路径
  1179. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1180. $localPath = $this->downloadMediaToTemp($media);
  1181. $isTempFile = true;
  1182. } elseif (is_string($media)) {
  1183. $localPath = $media;
  1184. } else {
  1185. // Laravel UploadedFile 对象
  1186. $localPath = $media->getRealPath();
  1187. }
  1188. if (!$localPath || !file_exists($localPath)) {
  1189. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1190. return null;
  1191. }
  1192. $fileSize = filesize($localPath);
  1193. $maxBytes = $this->geminiMediaMaxBytes();
  1194. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1195. $mimeType = $this->detectMediaMime($localPath);
  1196. $isVideo = strpos($mimeType, 'video/') === 0;
  1197. $needCompress = $fileSize > $maxBytes;
  1198. $duration = 0;
  1199. if ($isVideo) {
  1200. $duration = $this->getMediaDuration($localPath);
  1201. if ($duration > 300) {
  1202. $needCompress = true;
  1203. }
  1204. }
  1205. $finalPath = $localPath;
  1206. $compressedPath = null;
  1207. if ($needCompress && $this->ffmpegAvailable()) {
  1208. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1209. if ($compressed && file_exists($compressed)) {
  1210. $compressedPath = $compressed;
  1211. if (filesize($compressed) < $fileSize || $isVideo) {
  1212. $finalPath = $compressed;
  1213. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1214. } else {
  1215. @unlink($compressed);
  1216. $compressedPath = null;
  1217. }
  1218. }
  1219. }
  1220. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1221. $finalSize = filesize($finalPath);
  1222. if ($finalSize > $maxBytes) {
  1223. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1224. 'path' => $localPath,
  1225. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1226. 'limit_mb' => 14
  1227. ]);
  1228. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1229. }
  1230. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1231. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1232. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1233. }
  1234. $data = base64_encode(file_get_contents($finalPath));
  1235. return [
  1236. 'mime_type' => $mimeType,
  1237. 'data' => $data
  1238. ];
  1239. } catch (\App\Exceptions\ApiException $e) {
  1240. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1241. throw $e;
  1242. } catch (\Exception $e) {
  1243. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1244. return null;
  1245. } finally {
  1246. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1247. @unlink($compressedPath);
  1248. }
  1249. if ($isTempFile && $localPath && file_exists($localPath)) {
  1250. @unlink($localPath);
  1251. }
  1252. }
  1253. }
  1254. /**
  1255. * 下载远程多媒体到临时目录
  1256. *
  1257. * @return string|null 本地临时文件路径
  1258. */
  1259. private function downloadMediaToTemp($url) {
  1260. try {
  1261. $tempDir = storage_path('app/temp/gemini');
  1262. if (!is_dir($tempDir)) {
  1263. mkdir($tempDir, 0775, true);
  1264. }
  1265. $extension = 'tmp';
  1266. $pathInfo = parse_url($url, PHP_URL_PATH);
  1267. if ($pathInfo) {
  1268. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1269. if ($ext && strlen($ext) <= 10) {
  1270. $extension = strtolower($ext);
  1271. }
  1272. }
  1273. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1274. $client = new Client(['timeout' => 300, 'verify' => false]);
  1275. $response = $client->get($url, ['sink' => $tmpFile]);
  1276. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1277. @unlink($tmpFile);
  1278. return null;
  1279. }
  1280. return $tmpFile;
  1281. } catch (\Exception $e) {
  1282. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1283. return null;
  1284. }
  1285. }
  1286. /**
  1287. * 检测多媒体文件 MIME 类型
  1288. */
  1289. private function detectMediaMime($filePath) {
  1290. $imageInfo = @getimagesize($filePath);
  1291. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1292. return $imageInfo['mime'];
  1293. }
  1294. // 视频按扩展名粗略判断
  1295. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1296. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1297. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1298. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1299. if (isset($videoExts[$ext])) {
  1300. return $videoExts[$ext];
  1301. }
  1302. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1303. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1304. if (isset($imageExts[$ext])) {
  1305. return $imageExts[$ext];
  1306. }
  1307. return 'application/octet-stream';
  1308. }
  1309. /**
  1310. * 获取多媒体时长(秒),非视频或失败返回 0
  1311. */
  1312. private function getMediaDuration($filePath) {
  1313. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1314. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1315. $output = trim((string)shell_exec($cmd));
  1316. $duration = (float)$output;
  1317. return $duration > 0 ? $duration : 0;
  1318. }
  1319. /**
  1320. * 检查 ffmpeg 是否可用
  1321. */
  1322. private function ffmpegAvailable() {
  1323. static $available = null;
  1324. if ($available !== null) {
  1325. return $available;
  1326. }
  1327. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1328. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1329. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1330. $available = false;
  1331. return $available;
  1332. }
  1333. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1334. $output = shell_exec($cmd);
  1335. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1336. return $available;
  1337. }
  1338. /**
  1339. * 使用 ffmpeg 压缩多媒体文件
  1340. *
  1341. * @param string $inputFile 输入文件路径
  1342. * @param bool $isVideo 是否为视频
  1343. * @param float $duration 视频时长(秒),非视频传 0
  1344. * @return string|null 压缩后的文件路径,失败返回 null
  1345. */
  1346. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1347. try {
  1348. $tempDir = storage_path('app/temp/gemini');
  1349. if (!is_dir($tempDir)) {
  1350. mkdir($tempDir, 0775, true);
  1351. }
  1352. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1353. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1354. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1355. if ($isVideo) {
  1356. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1357. $speedFactor = 1.0;
  1358. if ($duration > 300) {
  1359. $speedFactor = $duration / 300;
  1360. }
  1361. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1362. $finalDuration = $duration / max(1.0, $speedFactor);
  1363. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1364. $targetBitrate = max(300, min(6000, $targetBitrate));
  1365. $filters = [];
  1366. $filters[] = 'scale=min(1280,iw):-2';
  1367. $filters[] = 'fps=24';
  1368. if ($speedFactor > 1.0) {
  1369. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1370. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1371. $fullCount = (int)ceil($speedFactor / 2.0);
  1372. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1373. if ($lastTempo < 0.5) {
  1374. $fullCount++;
  1375. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1376. }
  1377. for ($i = 0; $i < $fullCount; $i++) {
  1378. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1379. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1380. }
  1381. }
  1382. $filterStr = implode(',', $filters);
  1383. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1384. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1385. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1386. } else {
  1387. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1388. $imageInfo = @getimagesize($inputFile);
  1389. $scaleW = 2048;
  1390. $scaleH = 2048;
  1391. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1392. if ($imageInfo[0] >= $imageInfo[1]) {
  1393. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1394. $scaleW = 2048;
  1395. } else {
  1396. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1397. $scaleH = 2048;
  1398. }
  1399. }
  1400. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1401. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1402. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1403. }
  1404. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1405. $output = shell_exec($cmd);
  1406. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1407. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1408. 'input' => $inputFile,
  1409. 'output' => $output
  1410. ]);
  1411. @unlink($outputFile);
  1412. return null;
  1413. }
  1414. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1415. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1416. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1417. ]);
  1418. return $outputFile;
  1419. } catch (\Exception $e) {
  1420. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1421. return null;
  1422. }
  1423. }
  1424. /**
  1425. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1426. *
  1427. * @param array $data
  1428. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1429. */
  1430. public function getScriptGenerateTasks($data) {
  1431. $uid = Site::getUid();
  1432. return DB::table('mp_script_generate_tasks as t')
  1433. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1434. ->where('t.uid', $uid)
  1435. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1436. ->orderByDesc('t.id')
  1437. ->paginate(15);
  1438. }
  1439. public function saveScriptChatHistory($data) {
  1440. $uid = Site::getUid();
  1441. $rid = getProp($data, 'rid');
  1442. $script_id = getProp($data, 'script_id');
  1443. $sequence = getProp($data, 'sequence', 0);
  1444. $content = getProp($data, 'content');
  1445. if (!$rid) {
  1446. Utils::throwError('20003:请选择对话记录ID');
  1447. }
  1448. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1449. if (!$record) {
  1450. Utils::throwError('20003:对话记录不存在');
  1451. }
  1452. if (!$script_id) {
  1453. Utils::throwError('20003:请选择剧本');
  1454. }
  1455. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1456. if (!$script) {
  1457. Utils::throwError('20003:剧本不存在');
  1458. }
  1459. // 批量插入数据
  1460. return DB::table('mp_script_records')->where('id', $rid)->update([
  1461. 'content' => $content,
  1462. 'updated_at' => date('Y-m-d H:i:s')
  1463. ]);
  1464. }
  1465. /**
  1466. * 获取剧本的历史对话记录
  1467. *
  1468. * @param array $data 请求参数
  1469. * @return array 返回历史记录数组
  1470. */
  1471. public function getScriptChatHistory($data) {
  1472. $uid = Site::getUid();
  1473. $script_id = getProp($data, 'script_id');
  1474. $rid = getProp($data, 'rid');
  1475. $sequence = getProp($data, 'sequence', null);
  1476. if (!$script_id) {
  1477. Utils::throwError('20003:请提供剧本ID');
  1478. }
  1479. // 验证剧本是否存在
  1480. $script = DB::table('mp_scripts')
  1481. ->where('id', $script_id)
  1482. ->where('is_deleted', 0)
  1483. ->first();
  1484. if (!$script) {
  1485. Utils::throwError('20003:剧本不存在');
  1486. }
  1487. // 构建查询
  1488. $query = DB::table('mp_script_records')
  1489. ->where('script_id', $script_id);
  1490. // ->where('uid', $uid);
  1491. // 如果提供了 sequence,则过滤指定剧集
  1492. if ($sequence !== null) {
  1493. $query->where('sequence', $sequence);
  1494. }
  1495. // 记录ID筛选
  1496. if ($rid) {
  1497. $query->where('id', $rid);
  1498. }
  1499. // 查询记录并按 id 正序排序
  1500. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1501. ->orderBy('created_at', 'asc')
  1502. ->orderBy('id', 'asc')
  1503. ->get()
  1504. ->map(function ($record) {
  1505. return [
  1506. 'rid' => $record->id,
  1507. 'script_id' => $record->script_id,
  1508. 'sequence' => $record->sequence,
  1509. 'role' => $record->role,
  1510. 'content' => $record->content,
  1511. 'products' => $record->products ? json_decode($record->products) : [],
  1512. 'created_at' => $record->created_at,
  1513. ];
  1514. })
  1515. ->toArray();
  1516. return $records;
  1517. }
  1518. /**
  1519. * 处理图片转换为base64
  1520. *
  1521. * @param mixed $image 图片文件对象或文件路径
  1522. * @return string|null base64编码的图片数据
  1523. */
  1524. private function processImageToBase64($image) {
  1525. try {
  1526. // 获取文件路径
  1527. if (is_string($image)) {
  1528. $filePath = $image;
  1529. } else {
  1530. // Laravel UploadedFile 对象
  1531. $filePath = $image->getRealPath();
  1532. }
  1533. if (!file_exists($filePath)) {
  1534. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1535. return null;
  1536. }
  1537. // 验证是否为图片文件
  1538. $imageInfo = @getimagesize($filePath);
  1539. if ($imageInfo === false) {
  1540. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1541. return null;
  1542. }
  1543. // 读取图片并转换为base64
  1544. $imageData = file_get_contents($filePath);
  1545. $base64Image = base64_encode($imageData);
  1546. dLog('deepseek')->info('图片转换成功', [
  1547. 'size' => strlen($imageData),
  1548. 'type' => $imageInfo['mime']
  1549. ]);
  1550. return $base64Image;
  1551. } catch (\Exception $e) {
  1552. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1553. return null;
  1554. }
  1555. }
  1556. private function getArtStylePromptMappings($art_style='')
  1557. {
  1558. $arr = [
  1559. '唯美真人风格' => [
  1560. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1561. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1562. ],
  1563. '真人古风风格' => [
  1564. 'aliases' => ['真人古风风格', '真人古风'],
  1565. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1566. ],
  1567. '日系动漫风格' => [
  1568. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1569. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1570. ],
  1571. '国漫风格' => [
  1572. 'aliases' => ['国漫风格', '国漫'],
  1573. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1574. ],
  1575. 'Q版卡通风格' => [
  1576. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1577. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1578. ],
  1579. '简约扁平风格' => [
  1580. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1581. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1582. ],
  1583. '武侠风格' => [
  1584. 'aliases' => ['武侠风格', '武侠'],
  1585. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1586. ],
  1587. '古风仙侠风格' => [
  1588. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1589. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1590. ],
  1591. '新中式水墨风格' => [
  1592. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1593. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1594. ],
  1595. '写实插画风格' => [
  1596. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1597. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1598. ],
  1599. '3D卡通风格' => [
  1600. 'aliases' => ['3D卡通风格', '3D卡通'],
  1601. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1602. ],
  1603. '条漫风格' => [
  1604. 'aliases' => ['条漫风格', '条漫'],
  1605. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1606. ],
  1607. '赛博朋克风格' => [
  1608. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1609. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  1610. ],
  1611. '暗黑悬疑风格' => [
  1612. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1613. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  1614. ],
  1615. '治愈清新风格' => [
  1616. 'aliases' => ['治愈清新风格', '治愈清新'],
  1617. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  1618. ],
  1619. '3D真人风格' => [
  1620. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  1621. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  1622. ],
  1623. ];
  1624. if($art_style) {
  1625. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  1626. }
  1627. return $arr;
  1628. $arr = [
  1629. '唯美真人风格' => [
  1630. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1631. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  1632. 2. 色彩色调
  1633. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  1634. 3. 画质精度
  1635. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  1636. 4. 画面观感
  1637. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  1638. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  1639. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  1640. ],
  1641. '真人古风风格' => [
  1642. 'aliases' => ['真人古风风格', '真人古风'],
  1643. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  1644. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  1645. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  1646. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  1647. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  1648. ],
  1649. '日系动漫风格' => [
  1650. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1651. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  1652. 正向提示词(中文)
  1653. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  1654. 必须遵守规则
  1655. • 全程保持日系动漫风格,不混入其他画风
  1656. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  1657. • 画面适配所选画面比例,构图居中,主体突出
  1658. • 线条干净、色彩统一,不杂乱、不突兀
  1659. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  1660. ],
  1661. '国漫风格' => [
  1662. 'aliases' => ['国漫风格', '国漫'],
  1663. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  1664. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  1665. 必须遵守规则
  1666. • 严格保持国漫画风,不串风格、不混画风
  1667. • 角色形象统一,不随意改变五官、身材、服饰
  1668. • 画面构图稳定,适合漫剧叙事展示
  1669. • 色调统一,不出现脏色、杂色
  1670. 禁止/避免词汇
  1671. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  1672. ],
  1673. 'Q版卡通风格' => [
  1674. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1675. 'prompt' => "风格说明
  1676. 头大身小,造型可爱圆润,简约干净
  1677. 正向提示词(中文)
  1678. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  1679. 必须遵守规则
  1680. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  1681. • 角色造型统一,表情可爱,不诡异
  1682. • 画面简洁清爽,无多余复杂元素
  1683. • 色彩明亮柔和,不刺眼
  1684. 禁止/避免词汇
  1685. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  1686. ],
  1687. '简约扁平风格' => [
  1688. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1689. 'prompt' => "风格说明
  1690. 色块简洁、无复杂渐变,现代极简风
  1691. 正向提示词(中文)
  1692. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  1693. 必须遵守规则
  1694. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  1695. • 构图简洁,主体突出,无多余装饰
  1696. • 色彩统一、干净,不杂乱
  1697. 禁止/避免词汇
  1698. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  1699. ],
  1700. '武侠风格' => [
  1701. 'aliases' => ['武侠风格', '武侠'],
  1702. 'prompt' => "风格说明
  1703. 江湖气息,线条硬朗,动作感强
  1704. 正向提示词(中文)
  1705. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  1706. 必须遵守规则
  1707. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  1708. • 角色形象、服饰、身材比例统一
  1709. • 画面动作自然,不扭曲、不畸形
  1710. 禁止/避免词汇
  1711. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  1712. ],
  1713. '古风仙侠风格' => [
  1714. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1715. 'prompt' => "风格说明
  1716. 飘逸汉服、云雾仙气、唯美空灵
  1717. 正向提示词(中文)
  1718. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  1719. 必须遵守规则
  1720. • 保持古风仙侠统一画风,不混入现代、科幻元素
  1721. • 角色服饰、发型、形象前后一致
  1722. • 场景仙气飘逸,色调清雅统一
  1723. • 画面唯美柔和,不阴暗、不诡异
  1724. 禁止/避免词汇
  1725. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  1726. ],
  1727. '新中式水墨风格' => [
  1728. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1729. 'prompt' => "风格说明
  1730. 淡墨渲染,毛笔笔触,留白意境
  1731. 正向提示词(中文)
  1732. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  1733. 必须遵守规则
  1734. • 严格保持水墨质感,不混入厚涂、写实、卡通
  1735. • 色调淡雅统一,不浓艳杂乱
  1736. • 画面干净有意境,不堆砌元素
  1737. 禁止/避免词汇
  1738. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  1739. ],
  1740. '写实插画风格' => [
  1741. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1742. 'prompt' => "风格说明
  1743. 接近真人比例,光影真实,质感细腻
  1744. 正向提示词(中文)
  1745. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  1746. 必须遵守规则
  1747. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  1748. • 角色五官、身材、服饰高度统一
  1749. • 画面清晰、光影自然、不扭曲
  1750. 禁止/避免词汇
  1751. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  1752. ],
  1753. '3D卡通风格' => [
  1754. 'aliases' => ['3D卡通风格', '3D卡通'],
  1755. 'prompt' => "风格说明
  1756. 3D建模质感,柔和渲染,圆润可爱
  1757. 正向提示词(中文)
  1758. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1759. 必须遵守规则
  1760. • 保持3D卡通统一质感,不出现2D杂乱线条
  1761. • 角色模型、比例、形象前后一致
  1762. • 画面干净,不模糊、不穿模
  1763. 禁止/避免词汇
  1764. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1765. ],
  1766. '条漫风格' => [
  1767. 'aliases' => ['条漫风格', '条漫'],
  1768. 'prompt' => "风格说明
  1769. 纵向分镜,上下滑动阅读,轻量化
  1770. 正向提示词(中文)
  1771. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1772. 必须遵守规则
  1773. • 保持条漫纵向阅读逻辑,构图简洁
  1774. • 画风统一,不混写实、3D、水墨
  1775. • 画面干净,不杂乱
  1776. 禁止/避免词汇
  1777. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1778. ],
  1779. '赛博朋克风格' => [
  1780. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1781. 'prompt' => "风格说明
  1782. 霓虹灯光、未来都市、暗色调、科技机械
  1783. 正向提示词(中文)
  1784. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1785. 必须遵守规则
  1786. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1787. • 色调以暗调+霓虹为主,色彩统一
  1788. • 画面科技感强,不杂乱
  1789. 禁止/避免词汇
  1790. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1791. ],
  1792. '暗黑悬疑风格' => [
  1793. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1794. 'prompt' => "风格说明
  1795. 低饱和、冷色调、阴影重、神秘压抑
  1796. 正向提示词(中文)
  1797. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1798. 必须遵守规则
  1799. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1800. • 画面氛围压抑神秘,但不低俗、不血腥
  1801. • 角色形象统一,不崩坏
  1802. 禁止/避免词汇
  1803. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1804. ],
  1805. '治愈清新风格' => [
  1806. 'aliases' => ['治愈清新风格', '治愈清新'],
  1807. 'prompt' => "风格说明
  1808. 马卡龙色系、柔光、温暖干净
  1809. 正向提示词(中文)
  1810. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1811. 必须遵守规则
  1812. • 保持治愈清新统一色调,不阴暗、不诡异
  1813. • 画面柔和干净,无杂乱元素
  1814. • 角色形象柔和可爱,不狰狞
  1815. 禁止/避免词汇
  1816. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1817. ],
  1818. ];
  1819. return $arr;
  1820. }
  1821. public function getArtStylePromptByInput($inputArtStyle): string
  1822. {
  1823. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1824. if ($normalizedInput === '') {
  1825. return '';
  1826. }
  1827. return $this->getArtStylePromptMappings($normalizedInput);
  1828. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1829. // foreach ($mapping['aliases'] as $alias) {
  1830. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1831. // if ($normalizedAlias === '') {
  1832. // continue;
  1833. // }
  1834. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1835. // return $mapping['prompt'];
  1836. // }
  1837. // }
  1838. // }
  1839. return '';
  1840. }
  1841. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1842. $stylePrefixes = [
  1843. '唯美真人风格' => [
  1844. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1845. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1846. ],
  1847. '真人古风风格' => [
  1848. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1849. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1850. ],
  1851. '日系动漫风格' => [
  1852. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1853. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1854. ],
  1855. '国漫风格' => [
  1856. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1857. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1858. ],
  1859. 'Q版卡通风格' => [
  1860. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1861. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1862. ],
  1863. '简约扁平风格' => [
  1864. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1865. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1866. ],
  1867. '武侠风格' => [
  1868. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1869. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1870. ],
  1871. '古风仙侠风格' => [
  1872. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1873. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1874. ],
  1875. '新中式水墨风格' => [
  1876. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1877. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1878. ],
  1879. '写实插画风格' => [
  1880. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1881. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1882. ],
  1883. '3D卡通风格' => [
  1884. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1885. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1886. ],
  1887. '条漫风格' => [
  1888. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1889. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1890. ],
  1891. '赛博朋克风格' => [
  1892. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1893. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1894. ],
  1895. '暗黑悬疑风格' => [
  1896. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1897. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1898. ],
  1899. '治愈清新风格' => [
  1900. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1901. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1902. ]
  1903. ];
  1904. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1905. }
  1906. private function normalizeArtStyleInput($value): string
  1907. {
  1908. $value = trim((string)$value);
  1909. if ($value === '') {
  1910. return '';
  1911. }
  1912. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1913. return mb_strtolower($value, 'UTF-8');
  1914. }
  1915. private function replaceArtStyleSection(string $content, string $artStyle): string
  1916. {
  1917. if ($content === '' || $artStyle === '') {
  1918. return $content;
  1919. }
  1920. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1921. if (!preg_match($pattern, $content)) {
  1922. return $content;
  1923. }
  1924. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1925. }
  1926. /**
  1927. * DeepSeek流式输出处理方法
  1928. *
  1929. * @param array $post_data DeepSeek API请求参数
  1930. * @return \Generator 返回生成器,用于流式输出
  1931. */
  1932. private function deepSeekStreamResponse($post_data) {
  1933. // 设置最大输出tokens
  1934. $post_data['max_tokens'] = 300000;
  1935. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1936. $response = $client->post($this->url, [
  1937. 'json' => $post_data,
  1938. 'headers' => $this->headers,
  1939. 'stream' => true // 启用流式响应
  1940. ]);
  1941. $body = $response->getBody();
  1942. $fullContent = '';
  1943. $fullReasoningContent = '';
  1944. $usage = [];
  1945. $buffer = '';
  1946. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1947. // 逐行读取流式响应
  1948. while (!$body->eof()) {
  1949. $chunk = $body->read(1024); // 每次读取 1KB
  1950. $buffer .= $chunk;
  1951. // 按行分割
  1952. $lines = explode("\n", $buffer);
  1953. // 保留最后一个不完整的行
  1954. $buffer = array_pop($lines);
  1955. foreach ($lines as $line) {
  1956. $line = trim($line);
  1957. // 跳过空行
  1958. if (empty($line)) {
  1959. continue;
  1960. }
  1961. // 检查是否是 SSE 数据行
  1962. if (strpos($line, 'data: ') !== 0) {
  1963. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1964. continue;
  1965. }
  1966. $data = substr($line, 6); // 移除 "data: " 前缀
  1967. if ($data === '[DONE]') {
  1968. dLog('deepseek')->info('收到结束标记');
  1969. break 2; // 跳出两层循环
  1970. }
  1971. try {
  1972. $json = json_decode($data, true);
  1973. if (json_last_error() !== JSON_ERROR_NONE) {
  1974. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1975. continue;
  1976. }
  1977. if (isset($json['choices'][0]['delta'])) {
  1978. $delta = $json['choices'][0]['delta'];
  1979. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1980. if (isset($delta['reasoning_content'])) {
  1981. $fullReasoningContent .= $delta['reasoning_content'];
  1982. yield [
  1983. 'type' => 'reasoning',
  1984. 'content' => $delta['reasoning_content'],
  1985. 'full_reasoning' => $fullReasoningContent
  1986. ];
  1987. }
  1988. // 处理最终回答内容
  1989. if (isset($delta['content'])) {
  1990. $fullContent .= $delta['content'];
  1991. yield [
  1992. 'type' => 'content',
  1993. 'content' => $delta['content'],
  1994. ];
  1995. }
  1996. }
  1997. // 获取使用统计信息
  1998. if (isset($json['usage'])) {
  1999. $usage = $json['usage'];
  2000. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2001. }
  2002. } catch (\Exception $e) {
  2003. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2004. continue;
  2005. }
  2006. }
  2007. }
  2008. dLog('deepseek')->info('流式读取完成', [
  2009. 'content_length' => strlen($fullContent),
  2010. 'reasoning_length' => strlen($fullReasoningContent)
  2011. ]);
  2012. yield [
  2013. 'type' => 'done',
  2014. 'full_content' => $fullContent,
  2015. 'full_reasoning' => $fullReasoningContent,
  2016. 'usage' => $usage
  2017. ];
  2018. }
  2019. /**
  2020. * GPT 重试次数(env 可配置,默认 5 次)
  2021. */
  2022. private function gptRetryTimes()
  2023. {
  2024. return (int)env('GPT_RETRY_TIMES', 5);
  2025. }
  2026. /**
  2027. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2028. */
  2029. private function gptRetryInterval()
  2030. {
  2031. return (int)env('GPT_RETRY_INTERVAL', 10);
  2032. }
  2033. /**
  2034. * 判断 GPT 请求异常是否可重试
  2035. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2036. */
  2037. private function isGptRetryableException(\Exception $e)
  2038. {
  2039. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2040. return false;
  2041. }
  2042. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2043. $status = $e->getResponse()->getStatusCode();
  2044. return $status >= 500 || $status == 429;
  2045. }
  2046. return true;
  2047. }
  2048. /**
  2049. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2050. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2051. */
  2052. private function checkGptServiceAvailable()
  2053. {
  2054. $apiKey = env('GPT_54_API_KEY');
  2055. if (empty($apiKey)) {
  2056. return false;
  2057. }
  2058. try {
  2059. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2060. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2061. 'headers' => [
  2062. 'Authorization' => 'Bearer ' . $apiKey,
  2063. 'Content-Type' => 'application/json'
  2064. ]
  2065. ]);
  2066. $status = $response->getStatusCode();
  2067. return $status < 500 && $status != 429;
  2068. } catch (\Exception $e) {
  2069. return false;
  2070. }
  2071. }
  2072. /**
  2073. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2074. * 全部失败抛出友好错误
  2075. */
  2076. private function ensureGptServiceAvailable()
  2077. {
  2078. $maxRetries = $this->gptRetryTimes();
  2079. $interval = $this->gptRetryInterval();
  2080. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2081. if ($this->checkGptServiceAvailable()) {
  2082. return;
  2083. }
  2084. if ($attempt < $maxRetries) {
  2085. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2086. 'retry' => $attempt + 1,
  2087. 'max_retries' => $maxRetries
  2088. ]);
  2089. sleep($interval);
  2090. }
  2091. }
  2092. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2093. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2094. 'max_retries' => $maxRetries,
  2095. 'interval' => $interval
  2096. ]);
  2097. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2098. }
  2099. /**
  2100. * GPT 流式输出处理方法
  2101. *
  2102. * @param array $post_data GPT API请求参数
  2103. * @return \Generator 返回生成器,用于流式输出
  2104. */
  2105. private function gpt54StreamResponse($post_data) {
  2106. $apiKey = env('GPT_54_API_KEY');
  2107. if (empty($apiKey)) {
  2108. Utils::throwError('20003:GPT API Key未配置');
  2109. }
  2110. // 先探活,服务不可用时自动重试
  2111. $this->ensureGptServiceAvailable();
  2112. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2113. $headers = [
  2114. 'Authorization' => 'Bearer ' . $apiKey,
  2115. 'Content-Type' => 'application/json'
  2116. ];
  2117. // 移除 thinking 参数,GPT-5.4 不支持
  2118. if (isset($post_data['thinking'])) {
  2119. unset($post_data['thinking']);
  2120. }
  2121. if (isset($post_data['reasoning_effort'])) {
  2122. unset($post_data['reasoning_effort']);
  2123. }
  2124. $post_data['max_completion_tokens'] = 100000;
  2125. $maxRetries = $this->gptRetryTimes();
  2126. $interval = $this->gptRetryInterval();
  2127. $attempt = 0;
  2128. while (true) {
  2129. $fullContent = '';
  2130. $usage = [];
  2131. $buffer = '';
  2132. try {
  2133. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2134. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2135. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2136. 'json' => $post_data,
  2137. 'headers' => $headers,
  2138. 'stream' => true // 启用流式响应
  2139. ]);
  2140. $body = $response->getBody();
  2141. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2142. // 逐行读取流式响应
  2143. while (!$body->eof()) {
  2144. $chunk = $body->read(1024); // 每次读取 1KB
  2145. $buffer .= $chunk;
  2146. // 按行分割
  2147. $lines = explode("\n", $buffer);
  2148. // 保留最后一个不完整的行
  2149. $buffer = array_pop($lines);
  2150. foreach ($lines as $line) {
  2151. $line = trim($line);
  2152. // 跳过空行
  2153. if (empty($line)) {
  2154. continue;
  2155. }
  2156. // 检查是否是 SSE 数据行
  2157. if (strpos($line, 'data: ') !== 0) {
  2158. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2159. continue;
  2160. }
  2161. $data = substr($line, 6); // 移除 "data: " 前缀
  2162. if ($data === '[DONE]') {
  2163. dLog('deepseek')->info('收到结束标记');
  2164. break 2; // 跳出 foreach 和流读取循环
  2165. }
  2166. try {
  2167. $json = json_decode($data, true);
  2168. if (json_last_error() !== JSON_ERROR_NONE) {
  2169. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2170. continue;
  2171. }
  2172. if (isset($json['choices'][0]['delta'])) {
  2173. $delta = $json['choices'][0]['delta'];
  2174. // 处理回答内容
  2175. if (isset($delta['content'])) {
  2176. $fullContent .= $delta['content'];
  2177. yield [
  2178. 'type' => 'content',
  2179. 'content' => $delta['content'],
  2180. ];
  2181. }
  2182. }
  2183. // 获取使用统计信息
  2184. if (isset($json['usage'])) {
  2185. $usage = $json['usage'];
  2186. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2187. }
  2188. } catch (\Exception $e) {
  2189. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2190. continue;
  2191. }
  2192. }
  2193. }
  2194. dLog('deepseek')->info('流式读取完成', [
  2195. 'content_length' => strlen($fullContent)
  2196. ]);
  2197. yield [
  2198. 'type' => 'done',
  2199. 'full_content' => $fullContent,
  2200. 'full_reasoning' => '',
  2201. 'usage' => $usage
  2202. ];
  2203. return;
  2204. } catch (\Exception $e) {
  2205. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2206. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2207. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2208. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2209. throw $e;
  2210. }
  2211. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2212. 'retry' => $attempt + 1,
  2213. 'max_retries' => $maxRetries,
  2214. 'error' => $e->getMessage()
  2215. ]);
  2216. sleep($interval);
  2217. $attempt++;
  2218. }
  2219. }
  2220. }
  2221. // 与推理模型对话
  2222. public function chatWithReasoner($data) {
  2223. $content = getProp($data, 'content');
  2224. $model = getProp($data, 'model', 'r1');
  2225. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2226. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2227. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2228. if ($model == 'r1') {
  2229. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2230. $thinkingMode = 'disabled';
  2231. } else {
  2232. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2233. $thinkingMode = 'disabled';
  2234. }
  2235. // 获取可选情感(根据音色可支持情感选)
  2236. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2237. $emotion_list = [];
  2238. foreach ($timbre_emotion as $emotion) {
  2239. $tmp = explode(',', $emotion);
  2240. $emotion_list = array_merge($emotion_list, $tmp);
  2241. }
  2242. $emotion_list = array_unique($emotion_list);
  2243. $emotion_str = implode('、', $emotion_list);
  2244. // // 获取可选情感
  2245. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2246. // $emotion_str = implode('、', $emotion_list);
  2247. // 是否启用情感
  2248. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2249. if ($enable_emotion) {
  2250. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2251. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2252. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2253. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2254. }else {
  2255. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2256. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2257. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2258. }
  2259. $messages = [
  2260. [
  2261. 'role' => 'system',
  2262. 'content' => $sys_content
  2263. ],
  2264. [
  2265. 'role' => 'user',
  2266. 'content' => $content
  2267. ]
  2268. ];
  2269. $post_data = [
  2270. 'model' => $model,
  2271. 'messages' => $messages,
  2272. // 'max_tokens' => 8192,
  2273. 'temperature' => 1,
  2274. 'frequency_penalty' => 0,
  2275. 'presence_penalty' => 0,
  2276. 'thinking' => ['type' => $thinkingMode],
  2277. 'response_format' => [
  2278. 'type' => 'text'
  2279. ],
  2280. 'stream' => false
  2281. ];
  2282. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2283. // 根据模型类型选择调用方法
  2284. $fullContent = '';
  2285. $usage = [];
  2286. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2287. // DeepSeek 官方模型使用 DeepSeek API
  2288. $chatResult = $this->chatOnly($post_data);
  2289. } else if (in_array($model, $this->gpt_text_models)) {
  2290. // GPT-5.4 模型使用 TokenRouter API
  2291. $chatResult = $this->gpt54ChatOnly($post_data);
  2292. } else {
  2293. // 其他模型使用火山引擎API
  2294. $chatResult = $this->volcEngineChatCompletion($post_data);
  2295. }
  2296. if (is_array($chatResult)) {
  2297. $fullContent = $chatResult['fullContent'];
  2298. $usage = $chatResult['usage'];
  2299. }
  2300. // 处理获取到的剧本数据
  2301. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2302. $result = [
  2303. 'origin_content' => $fullContent,
  2304. 'roles' => getProp($script_content, 'roles'),
  2305. 'words' => getProp($script_content, 'words'),
  2306. ];
  2307. return $result;
  2308. }
  2309. public function resetParagraphAudio($data) {
  2310. $bid = getProp($data, 'bid');
  2311. $cid = getProp($data, 'cid');
  2312. $version_id = getProp($data, 'version_id');
  2313. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2314. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2315. 'generate_status' => '待制作',
  2316. 'updated_at' => date('Y-m-d H:i:s')
  2317. ]);
  2318. }
  2319. public function saveParagraphAudio($data) {
  2320. $bid = getProp($data, 'bid');
  2321. $cid = getProp($data, 'cid');
  2322. $version_id = getProp($data, 'version_id');
  2323. $sequence = getProp($data, 'sequence');
  2324. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2325. // 获取所有情感
  2326. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2327. $emotion_list = array_flip($emotion_list);
  2328. // 获取音色支持情感
  2329. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2330. $timbre_emotion = explode(',', $timbre_emotion);
  2331. $emotion = getProp($data, 'emotion');
  2332. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2333. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2334. $list = [
  2335. 'bid' => $bid,
  2336. 'cid' => $cid,
  2337. 'version_id' => $version_id,
  2338. 'sequence' => $sequence,
  2339. 'role' => getProp($data, 'role'),
  2340. 'gender' => getProp($data, 'gender'),
  2341. 'text' => trim(getProp($data, 'text')),
  2342. 'emotion' => $emotion,
  2343. 'emotion_type' => $emotion_type,
  2344. 'voice_type' => getProp($data, 'voice_type'),
  2345. 'voice_name' => getProp($data, 'voice_name'),
  2346. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2347. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2348. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2349. 'pitch' => getProp($data, 'pitch', 0),
  2350. // 'paragraph_audio_url' => '',
  2351. 'generate_status' => '制作中',
  2352. 'error_msg' => '',
  2353. 'updated_at' => date('Y-m-d H:i:s')
  2354. ];
  2355. $continue = false;
  2356. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2357. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2358. $list['generate_status'] = '制作成功';
  2359. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2360. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2361. $continue = true;
  2362. }
  2363. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2364. if ($id) {
  2365. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2366. }else {
  2367. $list['created_at'] = date('Y-m-d H:i:s');
  2368. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2369. $boolen = $id ? true : false;
  2370. }
  2371. // 如果更新成功则加入查询队列
  2372. if ($boolen) {
  2373. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2374. Redis::sadd($redis_key, $id);
  2375. }
  2376. if ($boolen && !$continue) {
  2377. $boolen = false;
  2378. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2379. // 根据ID通过API通知合成音频
  2380. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2381. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2382. $response = $result->getBody()->getContents();
  2383. $response_arr = json_decode($response, true);
  2384. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2385. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2386. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2387. Utils::throwError('20003:通知火山生成段落音频失败');
  2388. }
  2389. $boolen = true;
  2390. }
  2391. return $boolen;
  2392. }
  2393. public function insertAudioEffect($data) {
  2394. $audio_id = getProp($data, 'audio_id');
  2395. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2396. $bid = getProp($chapter_audio, 'bid');
  2397. $version_id = getProp($chapter_audio, 'version_id');
  2398. $cid = getProp($chapter_audio, 'cid');
  2399. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2400. $audio_effect_json = getProp($data, 'audio_effect_json');
  2401. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2402. try {
  2403. DB::beginTransaction();
  2404. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2405. if (!$count) {
  2406. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2407. }else {
  2408. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2409. }
  2410. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2411. 'audio_effect_status' => '添加中',
  2412. 'audio_effect_json' => $audio_effect_json,
  2413. 'updated_at' => date('Y-m-d H:i:s')
  2414. ]);
  2415. if (!$boolen1) {
  2416. DB::rollBack();
  2417. Utils::throwError('20003:更新生成数据失败');
  2418. }
  2419. $id = DB::table('mp_audio_tasks')->insertGetId([
  2420. 'audio_id' => $audio_id,
  2421. 'generate_status' => '执行中',
  2422. 'generate_json' => json_encode([], 256),
  2423. 'bid' => $bid,
  2424. 'book_name' => getProp($chapter_audio, 'book_name'),
  2425. 'version_id' => $version_id,
  2426. 'version_name' => getProp($chapter_audio, 'version_name'),
  2427. 'cid' => $cid,
  2428. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2429. 'task_name' => $task_name,
  2430. 'created_at' => date('Y-m-d H:i:s'),
  2431. 'updated_at' => date('Y-m-d H:i:s')
  2432. ]);
  2433. if (!$id) {
  2434. DB::rollBack();
  2435. Utils::throwError('20003:创建任务失败');
  2436. }
  2437. }catch (\Exception $e) {
  2438. DB::rollBack();
  2439. Utils::throwError('20003:'.$e->getMessage());
  2440. }
  2441. DB::commit();
  2442. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2443. // 根据ID通过API通知合成音频
  2444. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2445. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2446. $response = $result->getBody()->getContents();
  2447. $response_arr = json_decode($response, true);
  2448. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2449. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2450. Log::info('通知火山插入音效失败: '.$error_msg);
  2451. Utils::throwError('20003:通知火山插入音效失败');
  2452. }
  2453. return true;
  2454. }
  2455. public function insertBgm($data) {
  2456. $audio_id = getProp($data, 'audio_id');
  2457. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2458. $bid = getProp($chapter_audio, 'bid');
  2459. $version_id = getProp($chapter_audio, 'version_id');
  2460. $cid = getProp($chapter_audio, 'cid');
  2461. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2462. $bgm_json = getProp($data, 'bgm_json');
  2463. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2464. if (!$bgm_json) {
  2465. $bgm_json = getProp($data, 'audio_effect_json');
  2466. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2467. }
  2468. try {
  2469. DB::beginTransaction();
  2470. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2471. if (!$count) {
  2472. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2473. }else {
  2474. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2475. }
  2476. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2477. 'bgm_status' => '添加中',
  2478. 'bgm_json' => $bgm_json,
  2479. 'updated_at' => date('Y-m-d H:i:s')
  2480. ]);
  2481. if (!$boolen1) {
  2482. DB::rollBack();
  2483. Utils::throwError('20003:更新生成数据失败');
  2484. }
  2485. $id = DB::table('mp_audio_tasks')->insertGetId([
  2486. 'audio_id' => $audio_id,
  2487. 'generate_status' => '执行中',
  2488. 'generate_json' => json_encode([], 256),
  2489. 'bid' => $bid,
  2490. 'book_name' => getProp($chapter_audio, 'book_name'),
  2491. 'version_id' => $version_id,
  2492. 'version_name' => getProp($chapter_audio, 'version_name'),
  2493. 'cid' => $cid,
  2494. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2495. 'task_name' => $task_name,
  2496. 'created_at' => date('Y-m-d H:i:s'),
  2497. 'updated_at' => date('Y-m-d H:i:s')
  2498. ]);
  2499. if (!$id) {
  2500. DB::rollBack();
  2501. Utils::throwError('20003:创建任务失败');
  2502. }
  2503. }catch (\Exception $e) {
  2504. DB::rollBack();
  2505. Utils::throwError('20003:'.$e->getMessage());
  2506. }
  2507. DB::commit();
  2508. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2509. // 根据ID通过API通知合成音频
  2510. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2511. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2512. $response = $result->getBody()->getContents();
  2513. $response_arr = json_decode($response, true);
  2514. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2515. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2516. Log::info('通知火山插入bgm失败: '.$error_msg);
  2517. Utils::throwError('20003:通知火山插入bgm失败');
  2518. }
  2519. return true;
  2520. }
  2521. public function getParagraphAudios($data) {
  2522. $bid = getProp($data, 'bid');
  2523. $cid = getProp($data, 'cid');
  2524. $version_id = getProp($data, 'version_id');
  2525. $sequence = getProp($data, 'sequence');
  2526. // 获取已生成的音频
  2527. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2528. if ($sequence) $query->where('sequence', $sequence);
  2529. $paragraph_audios = $query->orderBy('sequence')->get();
  2530. $result = [];
  2531. foreach($paragraph_audios as $item) {
  2532. $result[] = [
  2533. 'sequence' => getProp($item, 'sequence'),
  2534. 'role' => getProp($item, 'role'),
  2535. 'gender' => getProp($item, 'gender'),
  2536. 'text' => trim(getProp($item, 'text')),
  2537. 'emotion' => getProp($item, 'emotion'),
  2538. 'emotion_type' => getProp($item, 'emotion_type'),
  2539. 'voice_type' => getProp($item, 'voice_type'),
  2540. 'voice_name' => getProp($item, 'voice_name'),
  2541. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2542. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2543. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2544. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2545. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  2546. ];
  2547. }
  2548. return $result;
  2549. }
  2550. // 新增合成任务
  2551. public function addGenerateTask($data) {
  2552. $bid = getProp($data, 'bid');
  2553. $cid = getProp($data, 'cid');
  2554. $version_id = getProp($data, 'version_id');
  2555. $generate_json = getProp($data, 'generate_json');
  2556. // 获取已生成的音频
  2557. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  2558. $paragraph_list = [];
  2559. foreach($paragraph_audios as $item) {
  2560. $paragraph_list[getProp($item, 'sequence')] = [
  2561. 'role' => getProp($item, 'role'),
  2562. 'gender' => getProp($item, 'gender'),
  2563. 'text' => trim(getProp($item, 'text')),
  2564. 'emotion' => getProp($item, 'emotion'),
  2565. 'emotion_type' => getProp($item, 'emotion_type'),
  2566. 'voice_type' => getProp($item, 'voice_type'),
  2567. 'voice_name' => getProp($item, 'voice_name'),
  2568. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2569. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2570. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2571. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2572. ];
  2573. }
  2574. // 更新角色-音色信息
  2575. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  2576. $existed_role_info = json_decode($existed_role_info, true);
  2577. if (!$existed_role_info) $existed_role_info = [];
  2578. // 获取情感信息
  2579. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2580. $emotion_list = array_flip($emotion_list);
  2581. // 获取音色对应情感组
  2582. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  2583. $timbre_emotion_list = [];
  2584. foreach($timbre_emotions as $item) {
  2585. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  2586. }
  2587. // 构造生成音频的json
  2588. $words = json_decode($generate_json, true);
  2589. // 最终合成前的参数组
  2590. $mp_chapter_paragraph_audios = [];
  2591. $sequence = 1;
  2592. $complete_paragraph_sequences = [];
  2593. foreach($words as &$word) {
  2594. if (!isset($word['text']) || !isset($word['emotion']) || !isset($word['voice_type']) || !isset($word['voice_name']) || !isset($word['speed_ratio']) || !isset($word['loudness_ratio']) || !isset($word['emotion_scale'])) Utils::throwError('20003:参数格式有误');
  2595. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  2596. $role = getProp($word, 'role');
  2597. $word['gender'] = (int)$word['gender'];
  2598. // 判断音色对应情感是否支持,不支持则调整为中性
  2599. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  2600. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  2601. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  2602. if (isset($emotion_list[getProp($word, 'emotion')])) {
  2603. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  2604. }else {
  2605. $word['emotion'] = '中性';
  2606. $word['emotion_type'] = 'neutral';
  2607. }
  2608. $existed_role_info[$role] = [
  2609. 'timbre_type' => $word['voice_type'],
  2610. 'timbre_name' => $word['voice_name'],
  2611. 'emotion' => $word['emotion'],
  2612. 'emotion_type' => $word['emotion_type'],
  2613. 'speed_ratio' => $word['speed_ratio'],
  2614. 'loudness_ratio'=> $word['loudness_ratio'],
  2615. 'emotion_scale' => $word['emotion_scale'],
  2616. 'pitch' => $word['pitch']
  2617. ];
  2618. $word['paragraph_audio_url'] = '';
  2619. // 判断生成参数是否相同,相同则直接使用已生成的音频
  2620. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  2621. // 如果音频存在并且参数都未改变则使用已生成的音频
  2622. if (getProp($paragraph, 'paragraph_audio_url')) {
  2623. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  2624. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  2625. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  2626. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  2627. // {
  2628. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2629. // }
  2630. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2631. }
  2632. $tmp = $word;
  2633. // 组装章节分句音频数据
  2634. // $tmp['sequence'] = getProp($word, 'sequence');
  2635. // $tmp['text'] = getProp($word, 'text');
  2636. // $tmp['emotion'] = getProp($word, 'emotion');
  2637. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  2638. // $tmp['voice_name'] = getProp($word, 'voice_name');
  2639. // $tmp['voice_type'] = getProp($word, 'voice_type');
  2640. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  2641. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  2642. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  2643. $tmp['bid'] = $bid;
  2644. $tmp['version_id'] = $version_id;
  2645. $tmp['cid'] = $cid;
  2646. $tmp['sequence'] = $sequence;
  2647. $tmp['created_at'] = date('Y-m-d H:i:s');
  2648. $tmp['updated_at'] = date('Y-m-d H:i:s');
  2649. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  2650. $mp_chapter_paragraph_audios[] = $tmp;
  2651. $complete_paragraph_sequences[] = $sequence;
  2652. $sequence++;
  2653. }
  2654. $generate_json = json_encode($words, 256);
  2655. // 判断是否有未生成字幕的段落
  2656. $no_subtitle_sequences = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->whereIn('sequence', $complete_paragraph_sequences)->whereNull('subtitle_info')->pluck('sequence')->toArray();
  2657. if ($no_subtitle_sequences) {
  2658. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  2659. }
  2660. try {
  2661. DB::beginTransaction();
  2662. $role_info = json_encode($existed_role_info, 256);
  2663. $boolen = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->update(['role_info' => $role_info, 'updated_at' => date('Y-m-d H:i:s')]);
  2664. if (!$boolen) {
  2665. DB::rollBack();
  2666. Utils::throwError('20003:更新角色信息失败');
  2667. }
  2668. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  2669. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  2670. if (!$count) {
  2671. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2672. }else {
  2673. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2674. }
  2675. $boolen1 = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->update(['generate_status'=>'制作中', 'generate_json' => $generate_json, 'updated_at' => date('Y-m-d H:i:s')]);
  2676. if (!$boolen1) {
  2677. DB::rollBack();
  2678. Utils::throwError('20003:更新生成数据失败');
  2679. }
  2680. $id = DB::table('mp_audio_tasks')->insertGetId([
  2681. 'audio_id' => getProp($chapter_audio, 'id'),
  2682. 'generate_status' => '执行中',
  2683. 'generate_json' => $generate_json,
  2684. 'bid' => $bid,
  2685. 'book_name' => getProp($chapter_audio, 'book_name'),
  2686. 'version_id' => $version_id,
  2687. 'version_name' => getProp($chapter_audio, 'version_name'),
  2688. 'cid' => $cid,
  2689. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2690. 'task_name' => $task_name,
  2691. 'created_at' => date('Y-m-d H:i:s'),
  2692. 'updated_at' => date('Y-m-d H:i:s')
  2693. ]);
  2694. if (!$id) {
  2695. DB::rollBack();
  2696. Utils::throwError('20003:创建任务失败');
  2697. }
  2698. // 删除不在段落序号范围内的其他数据
  2699. if ($complete_paragraph_sequences) {
  2700. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  2701. }
  2702. // // 删除章节分句音频数据并重新插入
  2703. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  2704. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  2705. // if (!$boolen3) {
  2706. // DB::rollBack();
  2707. // Utils::throwError('20003:更新章节分句音频失败');
  2708. // }
  2709. } catch (\Exception $e) {
  2710. DB::rollBack();
  2711. Utils::throwError('20003:'.$e->getMessage());
  2712. }
  2713. DB::commit();
  2714. // 通知火山生成音频
  2715. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2716. // 根据ID通过API通知合成音频
  2717. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  2718. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  2719. $response = $result->getBody()->getContents();
  2720. $response_arr = json_decode($response, true);
  2721. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2722. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2723. Log::info('通知火山生成音频失败: '.$error_msg);
  2724. Utils::throwError('20003:通知火山生成音频失败');
  2725. }
  2726. return true;
  2727. }
  2728. public function timbreList($data) {
  2729. $gender = getProp($data, 'gender');
  2730. $timbre_name = getProp($data, 'voice_name');
  2731. $category_id = getProp($data, 'category_id');
  2732. $age_stage = getProp($data, 'age_stage');
  2733. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'age_stage', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  2734. if ($gender) {
  2735. $query->where('gender', $gender);
  2736. }
  2737. if ($timbre_name) {
  2738. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  2739. }
  2740. if ($category_id) {
  2741. $query->where(function ($query) use ($category_id) {
  2742. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  2743. });
  2744. }
  2745. if ($age_stage) {
  2746. $query->where('age_stage', $age_stage);
  2747. }
  2748. $list = $query->get()->map(function ($value) {
  2749. $value = (array)$value;
  2750. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2751. return $value;
  2752. })->toArray();
  2753. return $list;
  2754. }
  2755. // 生成火山临时token
  2756. public function setStsToken() {
  2757. // ************* 配置参数 *************
  2758. $method = 'GET';
  2759. $service = 'sts';
  2760. $host = 'open.volcengineapi.com';
  2761. $region = env('VOLC_REGION');
  2762. $endpoint = 'https://open.volcengineapi.com';
  2763. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2764. $access_key = env('VOLC_AK');
  2765. $secret_key = env('VOLC_SK');
  2766. // 获取缓存中的token,如果没有则请求接口
  2767. $token = Redis::get('volc_sts_token');
  2768. if (!$token) {
  2769. // 查询参数
  2770. $query_parameters = [
  2771. 'Action' => 'AssumeRole',
  2772. 'RoleSessionName' => 'user@zw',
  2773. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2774. 'Version' => '2018-01-01'
  2775. ];
  2776. // 生成URL编码的查询字符串
  2777. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2778. // 获取签名头信息
  2779. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2780. // 构建完整URL
  2781. $request_url = $endpoint . '?' . $request_parameters;
  2782. $client = new Client(['verify' => false]);
  2783. $response = $client->get($request_url, ['headers' => $headers]);
  2784. $response_arr = json_decode($response->getBody()->getContents(), true);
  2785. $result = [
  2786. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2787. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2788. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2789. 'Region' => env('VOLC_REGION'),
  2790. 'Endpoint' => env('VOLC_END_POINT'),
  2791. 'Bucket' => env('VOLC_BUCKET'),
  2792. ];
  2793. // 缓存token
  2794. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2795. return $result;
  2796. } else {
  2797. return json_decode($token, true);
  2798. }
  2799. // $response = $response['Response'];
  2800. // $access_key = $response['Credentials']['AccessKeyId'];
  2801. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2802. // $security_token = $response['Credentials']['SecurityToken'];
  2803. // $expiration = $response['Credentials']['Expiration'];
  2804. // dd($response_arr);
  2805. }
  2806. public function emotionGroups($data) {
  2807. $id = getProp($data, 'group_id');
  2808. $group_name = getProp($data, 'group_name');
  2809. $voice_type = getProp($data, 'voice_type');
  2810. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2811. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2812. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2813. if ($group_name) {
  2814. $query->where('group_name', 'like', "%{$group_name}%");
  2815. }
  2816. if ($id) {
  2817. $query->where('id', $id);
  2818. }
  2819. if ($voice_type) {
  2820. $query->where('voice_type', $voice_type);
  2821. }
  2822. return $query->orderBy('id')->get()->map(function ($value) {
  2823. return (array)$value;
  2824. })->toArray();
  2825. }
  2826. private function sign($key, $msg) {
  2827. return hash_hmac('sha256', $msg, $key, true);
  2828. }
  2829. // 生成签名密钥
  2830. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2831. $kDate = $this->sign($key, $dateStamp);
  2832. $kRegion = $this->sign($kDate, $regionName);
  2833. $kService = $this->sign($kRegion, $serviceName);
  2834. $kSigning = $this->sign($kService, 'request');
  2835. return $kSigning;
  2836. }
  2837. // 获取签名头信息
  2838. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2839. $contenttype = 'application/x-www-form-urlencoded';
  2840. $accept = 'application/json';
  2841. // 获取当前UTC时间
  2842. $t = new DateTime('now', new DateTimeZone('UTC'));
  2843. $xdate = $t->format('Ymd\THis\Z');
  2844. $datestamp = $t->format('Ymd');
  2845. // 1. 拼接规范请求串
  2846. $canonical_uri = '/';
  2847. $canonical_querystring = $request_parameters;
  2848. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2849. $signed_headers = 'content-type;host;x-date';
  2850. // 空请求体的SHA256哈希
  2851. $payload_hash = hash('sha256', '');
  2852. $canonical_request = implode("\n", [
  2853. $method,
  2854. $canonical_uri,
  2855. $canonical_querystring,
  2856. $canonical_headers,
  2857. $signed_headers,
  2858. $payload_hash
  2859. ]);
  2860. // 2. 拼接待签名字符串
  2861. $algorithm = 'HMAC-SHA256';
  2862. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2863. $hashed_canonical_request = hash('sha256', $canonical_request);
  2864. $string_to_sign = implode("\n", [
  2865. $algorithm,
  2866. $xdate,
  2867. $credential_scope,
  2868. $hashed_canonical_request
  2869. ]);
  2870. // 3. 计算签名
  2871. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2872. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2873. // 4. 添加签名到请求头
  2874. $authorization_header = sprintf(
  2875. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2876. $algorithm,
  2877. $access_key,
  2878. $credential_scope,
  2879. $signed_headers,
  2880. $signature
  2881. );
  2882. return [
  2883. 'Accept' => $accept,
  2884. 'Content-Type' => $contenttype,
  2885. 'X-Date' => $xdate,
  2886. 'Authorization' => $authorization_header
  2887. ];
  2888. }
  2889. // 文字合成语音(火山引擎)
  2890. public function tts($data) {
  2891. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2892. $headers = [
  2893. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2894. 'Content-Type' => 'application/json; charset=UTF-8'
  2895. ];
  2896. $post_data = [
  2897. 'app' => [
  2898. 'appid' => env('VOLC_APPID'),
  2899. 'token' => env('VOLC_TOKEN'),
  2900. 'cluster' => 'volcano_tts'
  2901. ],
  2902. 'user' => [
  2903. 'uid' => 'mp_audio'
  2904. ],
  2905. // 'audio' => [
  2906. // 'voice_type' =>
  2907. // ],
  2908. ];
  2909. }
  2910. public function scriptList($data) {
  2911. $uid = Site::getUid();
  2912. $script_id = getProp($data, 'script_id');
  2913. $script_name = getProp($data, 'script_name');
  2914. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2915. if ($script_id) {
  2916. $query->where('id', $script_id);
  2917. }
  2918. if ($script_name) {
  2919. $query->where('script_name', 'like', "%{$script_name}%");
  2920. }
  2921. return $query->orderBy('created_at', 'desc')->paginate(12);
  2922. }
  2923. public function scripts($data) {
  2924. $uid = Site::getUid();
  2925. $script_id = getProp($data, 'script_id');
  2926. $script_name = getProp($data, 'script_name');
  2927. $is_products = getProp($data, 'is_products');
  2928. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2929. if ($script_id) {
  2930. $query->where('id', $script_id);
  2931. }
  2932. if ($is_products !== '') {
  2933. $query->where('is_products', $is_products);
  2934. }
  2935. if ($script_name) {
  2936. $query->where('script_name', 'like', "%{$script_name}%");
  2937. }
  2938. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2939. return (array)$value;
  2940. })->toArray();
  2941. }
  2942. public function scriptInfo($data) {
  2943. $uid = Site::getUid();
  2944. $script_id = getProp($data, 'script_id');
  2945. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2946. // ->selectRaw('id as script_id, script_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_sequence, end_episode_sequence, episode_num, remark, created_at')->first();
  2947. ->selectRaw('id as script_id, script_name')->first();
  2948. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2949. $script = (array)$script;
  2950. // 获取分集组信息
  2951. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2952. ->selectRaw('id as group_id, script_id, group_name, start_episode_number, end_episode_number, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, episode_content')
  2953. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2954. $value = (array)$value;
  2955. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2956. return (array)$value;
  2957. })->toArray();
  2958. $script['group'] = $groups;
  2959. return $script;
  2960. }
  2961. public function createScript($data) {
  2962. $script_name = getProp($data, 'script_name');
  2963. $uid = Site::getUid(); // 获取当前用户ID
  2964. $cpid = Site::getCpid(); // 获取当前公司组ID
  2965. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2966. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2967. $script_name .= '_'.date('YmdHis');
  2968. }
  2969. return DB::table('mp_scripts')->insertGetId([
  2970. 'script_name' => $script_name,
  2971. 'user_id' => $uid,
  2972. 'cpid' => $cpid,
  2973. 'created_at' => date('Y-m-d H:i:s'),
  2974. 'updated_at' => date('Y-m-d H:i:s')
  2975. ]);
  2976. }
  2977. public function editScript($data) {
  2978. $script_id = getProp($data, 'script_id');
  2979. $script_name = getProp($data, 'script_name');
  2980. $uid = Site::getUid(); // 获取当前用户ID
  2981. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2982. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2983. if ($id && (int)$id !== (int)$script_id) {
  2984. $script_name .= '_'.date('YmdHis');
  2985. }
  2986. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2987. 'script_name' => $script_name,
  2988. 'updated_at' => date('Y-m-d H:i:s')
  2989. ]);
  2990. }
  2991. public function delScript($data) {
  2992. $script_id = getProp($data, 'script_id');
  2993. $uid = Site::getUid(); // 获取当前用户ID
  2994. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2995. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2996. 'is_deleted' => 1,
  2997. 'updated_at' => date('Y-m-d H:i:s')
  2998. ]);
  2999. }
  3000. public function createEpisode($data) {
  3001. $script_id = getProp($data, 'script_id');
  3002. $group_name = getProp($data, 'group_name');
  3003. $remark = getProp($data, 'remark');
  3004. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3005. $uid = Site::getUid(); // 获取当前用户ID
  3006. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3007. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3008. $group_name .= '_'.date('YmdHis');
  3009. }
  3010. return DB::table('mp_script_episode_group')->insertGetId([
  3011. 'script_id' => $script_id,
  3012. 'group_name' => $group_name,
  3013. 'user_id' => $uid,
  3014. 'remark' => $remark,
  3015. 'created_at' => date('Y-m-d H:i:s'),
  3016. 'updated_at' => date('Y-m-d H:i:s')
  3017. ]);
  3018. }
  3019. public function editEpisode($data) {
  3020. $group_id = getProp($data, 'group_id');
  3021. $start_episode_number = getProp($data, 'start_episode_number');
  3022. $end_episode_number = getProp($data, 'end_episode_number');
  3023. $group_name = getProp($data, 'group_name');
  3024. $uid = Site::getUid(); // 获取当前用户ID
  3025. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3026. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3027. if ($id && (int)$id !== (int)$group_id) {
  3028. $group_name .= '_'.date('YmdHis');
  3029. }
  3030. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3031. 'group_name' => $group_name,
  3032. 'start_episode_number' => $start_episode_number,
  3033. 'end_episode_number' => $end_episode_number,
  3034. 'updated_at' => date('Y-m-d H:i:s')
  3035. ]);
  3036. }
  3037. public function delEpisode($data) {
  3038. $group_id = getProp($data, 'group_id');
  3039. $uid = Site::getUid(); // 获取当前用户ID
  3040. if (!$group_id) Utils::throwError('20003:请选择分集');
  3041. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3042. 'is_deleted' => 1,
  3043. 'updated_at' => date('Y-m-d H:i:s')
  3044. ]);
  3045. }
  3046. /**
  3047. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3048. *
  3049. * @param array $data 包含以下参数:
  3050. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3051. * - question: 用户问题(可选)
  3052. * - model: 使用的模型(r1 或 v3,默认 v3)
  3053. * @return \Generator 返回生成器,用于流式输出
  3054. */
  3055. public function generateEpisodes($data) {
  3056. $script_id = getProp($data, 'script_id');
  3057. $group_id = getProp($data, 'group_id');
  3058. // $file = getProp($data, 'file');
  3059. $file = '';
  3060. $content = getProp($data, 'content', '');
  3061. // $bid = getProp($data, 'bid', 0);
  3062. $bid = 0;
  3063. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3064. if (!$group) {
  3065. Utils::throwError('20003:剧本分集不存在');
  3066. }
  3067. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3068. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3069. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3070. $prompt = getProp($data, 'prompt');
  3071. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3072. $model = getProp($data, 'model');
  3073. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3074. Utils::throwError('20003:该模型不存在!');
  3075. }
  3076. // 检查是否存在重叠的剧集序号范围
  3077. $exists_groups = DB::table('mp_script_episode_group')
  3078. ->where('script_id', $script_id)
  3079. ->where('id', '<>', $group_id) // 排除当前组
  3080. ->where('is_deleted', 0)
  3081. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3082. // 检查新范围是否与现有范围重叠
  3083. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3084. // 新范围的开始在现有范围内
  3085. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3086. ->where('end_episode_number', '>=', $start_episode_sequence);
  3087. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3088. // 新范围的结束在现有范围内
  3089. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3090. ->where('end_episode_number', '>=', $end_episode_sequence);
  3091. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3092. // 新范围完全包含现有范围
  3093. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3094. ->where('end_episode_number', '<=', $end_episode_sequence);
  3095. });
  3096. })
  3097. ->select('start_episode_number', 'end_episode_number')
  3098. ->get();
  3099. if ($exists_groups->isNotEmpty()) {
  3100. $conflict_ranges = [];
  3101. foreach ($exists_groups as $group) {
  3102. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3103. }
  3104. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3105. }
  3106. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3107. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3108. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3109. if ($model === 'deepseek-chat') {
  3110. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3111. $model = 'deepseek-v4-flash';
  3112. $thinkingMode = 'disabled';
  3113. } elseif ($model === 'deepseek-reasoner') {
  3114. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3115. $model = 'deepseek-v4-flash';
  3116. $thinkingMode = 'enabled';
  3117. }
  3118. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3119. if (!$script) {
  3120. Utils::throwError('20003:剧本不存在');
  3121. }
  3122. $content = getProp($group, 'content');
  3123. if (!$file && !$content && !$bid) {
  3124. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3125. }
  3126. // 提取文件内容
  3127. if ($file) {
  3128. $content = $this->extractFileContent($file);
  3129. if (!$content) {
  3130. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3131. }
  3132. } elseif ($bid) {
  3133. $content = $this->getContentByBid($bid);
  3134. if (!$content) {
  3135. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3136. }
  3137. } elseif ($content) {
  3138. $content = filterContent($content);
  3139. } elseif ($prompt) {
  3140. $content = filterContent($prompt);
  3141. } else {
  3142. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3143. }
  3144. // 构建消息
  3145. $messages = [
  3146. $this->sys_message,
  3147. [
  3148. 'role' => 'user',
  3149. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3150. ]
  3151. ];
  3152. $post_data = [
  3153. 'model' => $model,
  3154. 'messages' => $messages,
  3155. // 'max_tokens' => 8192,
  3156. 'temperature' => 0.7,
  3157. 'frequency_penalty' => 0,
  3158. 'presence_penalty' => 0,
  3159. 'thinking' => ['type' => $thinkingMode],
  3160. 'response_format' => ['type' => 'text'],
  3161. 'stream' => true
  3162. ];
  3163. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3164. // 根据模型类型选择调用方法
  3165. $fullContent = '';
  3166. $fullReasoningContent = '';
  3167. $usage = [];
  3168. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3169. // DeepSeek 官方模型使用 DeepSeek API
  3170. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3171. } else if (in_array($model, $this->gpt_text_models)) {
  3172. // GPT-5.4 模型使用 TokenRouter API
  3173. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3174. } else if (in_array($model, $this->gemini_text_models)) {
  3175. // Gemini 模型使用 Gemini API
  3176. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3177. } else {
  3178. // 其他模型使用火山引擎API
  3179. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3180. }
  3181. // 处理流式输出
  3182. foreach ($streamGenerator as $chunk) {
  3183. if (isset($chunk['type'])) {
  3184. if ($chunk['type'] === 'done') {
  3185. // 最终结果
  3186. $fullContent = $chunk['full_content'];
  3187. $fullReasoningContent = $chunk['full_reasoning'];
  3188. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3189. } else {
  3190. // 逐块yield数据
  3191. yield $chunk;
  3192. }
  3193. }
  3194. }
  3195. dLog('deepseek')->info('完整内容: '.$fullContent);
  3196. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3197. // 处理完整内容并返回最终结果
  3198. $script_arr = [];
  3199. if ($fullContent) {
  3200. $script_arr = extractScriptContent($fullContent);
  3201. }
  3202. logDB('deepseek', 'info', '解析内容', $script_arr);
  3203. if (!$script_arr['episodes']) {
  3204. Utils::throwError('20003:未生成剧本相关信息');
  3205. // yield [
  3206. // 'type' => 'done',
  3207. // 'script' => $script_arr,
  3208. // 'msg' => '未生成剧本相关信息',
  3209. // 'answer' => $fullContent,
  3210. // 'reasoning' => $fullReasoningContent,
  3211. // 'usage' => $usage
  3212. // ];
  3213. // return ;
  3214. }
  3215. try {
  3216. DB::beginTransaction();
  3217. // // 返回前保存剧本内容
  3218. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3219. // 'content' => $content,
  3220. // 'updated_at' => date('Y-m-d H:i:s')
  3221. // ]);
  3222. // if (!$boolen) {
  3223. // Utils::throwError('20003:保存剧本内容失败');
  3224. // }
  3225. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3226. // 'start_episode_number' => $start_episode_sequence,
  3227. // 'end_episode_number' => $end_episode_sequence,
  3228. // 'updated_at' => date('Y-m-d H:i:s')
  3229. // ]);
  3230. // if (!$boolen1) {
  3231. // Utils::throwError('20003:保存分集失败');
  3232. // }
  3233. $episode_content = '';
  3234. $episodes = [];
  3235. foreach ($script_arr['episodes'] as $item) {
  3236. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3237. // $episodes[] = [
  3238. // 'script_id' => $script_id,
  3239. // 'episode_number' => $item['episode_number'],
  3240. // 'episode_name' => $item['episode_name'],
  3241. // 'episode_content' => $item['episode_content'],
  3242. // 'created_at' => date('Y-m-d H:i:s'),
  3243. // 'updated_at' => date('Y-m-d H:i:s'),
  3244. // ];
  3245. }
  3246. if ($episode_content) {
  3247. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3248. 'episode_content' => $episode_content,
  3249. 'updated_at' => date('Y-m-d H:i:s')
  3250. ]);
  3251. if (!$boolen2) {
  3252. Utils::throwError('20003:保存分集内容失败');
  3253. }
  3254. }else {
  3255. Utils::throwError('20003:分集剧本解析失败');
  3256. }
  3257. }catch (\Exception $e) {
  3258. DB::rollBack();
  3259. Utils::throwError('20003:'.$e->getMessage());
  3260. }
  3261. DB::commit();
  3262. yield [
  3263. 'type' => 'done',
  3264. 'script' => $script_arr,
  3265. 'episode_content' => $episode_content,
  3266. 'answer' => $fullContent,
  3267. 'reasoning' => $fullReasoningContent,
  3268. 'usage' => $usage
  3269. ];
  3270. }
  3271. public function chatWithFileStream($data) {
  3272. $script_id = getProp($data, 'script_id');
  3273. $group_id = getProp($data, 'group_id');
  3274. $file = getProp($data, 'file');
  3275. $content = getProp($data, 'content', '');
  3276. $bid = getProp($data, 'bid', 0);
  3277. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3278. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3279. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3280. $prompt = getProp($data, 'prompt');
  3281. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3282. if (!empty($prompt)) {
  3283. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3284. }
  3285. $question = getProp($data, 'question', $baseQuestion);
  3286. $model = getProp($data, 'model');
  3287. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3288. Utils::throwError('20003:该模型不存在!');
  3289. }
  3290. // 检查是否存在重叠的剧集序号范围
  3291. $exists_groups = DB::table('mp_script_episode_group')
  3292. ->where('script_id', $script_id)
  3293. ->where('id', '<>', $group_id)
  3294. ->where('is_deleted', 0)
  3295. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3296. // 检查新范围是否与现有范围重叠
  3297. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3298. // 新范围的开始在现有范围内
  3299. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3300. ->where('end_episode_number', '>=', $start_episode_sequence);
  3301. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3302. // 新范围的结束在现有范围内
  3303. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3304. ->where('end_episode_number', '>=', $end_episode_sequence);
  3305. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3306. // 新范围完全包含现有范围
  3307. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3308. ->where('end_episode_number', '<=', $end_episode_sequence);
  3309. });
  3310. })
  3311. ->select('start_episode_number', 'end_episode_number')
  3312. ->get();
  3313. if ($exists_groups->isNotEmpty()) {
  3314. $conflict_ranges = [];
  3315. foreach ($exists_groups as $group) {
  3316. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3317. }
  3318. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3319. }
  3320. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3321. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3322. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3323. if ($model === 'deepseek-chat') {
  3324. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3325. $model = 'deepseek-v4-flash';
  3326. $thinkingMode = 'disabled';
  3327. } elseif ($model === 'deepseek-reasoner') {
  3328. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3329. $model = 'deepseek-v4-flash';
  3330. $thinkingMode = 'enabled';
  3331. }
  3332. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3333. if (!$script) {
  3334. Utils::throwError('20003:剧本不存在');
  3335. }
  3336. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3337. if (!$group) {
  3338. Utils::throwError('20003:剧本分集不存在');
  3339. }
  3340. if (!$file && !$content && !$bid) {
  3341. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3342. }
  3343. // 提取文件内容
  3344. if ($file) {
  3345. $content = $this->extractFileContent($file);
  3346. if (!$content) {
  3347. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3348. }
  3349. } elseif ($bid) {
  3350. $content = $this->getContentByBid($bid);
  3351. if (!$content) {
  3352. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3353. }
  3354. } elseif ($content) {
  3355. $content = filterContent($content);
  3356. } elseif ($prompt) {
  3357. $content = filterContent($prompt);
  3358. } else {
  3359. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3360. }
  3361. // 构建消息
  3362. $messages = [
  3363. [
  3364. 'role' => 'system',
  3365. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3366. 强制要求:\n
  3367. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3368. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3369. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3370. 普通要求:\n
  3371. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3372. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3373. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3374. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3375. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3376. 示例如下:\n
  3377. ###剧本名:西昆仑
  3378. ###故事梗概
  3379. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3380. ###剧本亮点
  3381. 亮点1:绝境奇药,生死一线
  3382. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3383. 亮点2:结拜兄妹,化解尴尬
  3384. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3385. 亮点3:纤发夺命,情愫暗涌
  3386. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3387. ###人物关系
  3388. 阿雪与梁萧之间存在兄妹之情。
  3389. ###核心矛盾
  3390. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3391. ###主体列表
  3392. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3393. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3394. 阴阳球:天地异宝,能化生精气,救人于危难。
  3395. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3396. ###美术风格
  3397. 基础画风风格词:厚涂古风
  3398. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3399. ###场景列表
  3400. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3401. [
  3402. 'role' => 'user',
  3403. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3404. ]
  3405. ];
  3406. $post_data = [
  3407. 'model' => $model,
  3408. 'messages' => $messages,
  3409. // 'max_tokens' => 8192,
  3410. 'temperature' => 0.7,
  3411. 'frequency_penalty' => 0,
  3412. 'presence_penalty' => 0,
  3413. 'thinking' => ['type' => $thinkingMode],
  3414. 'response_format' => ['type' => 'text'],
  3415. 'stream' => true
  3416. ];
  3417. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3418. // 根据模型类型选择调用方法
  3419. $fullContent = '';
  3420. $fullReasoningContent = '';
  3421. $usage = [];
  3422. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3423. // DeepSeek 官方模型使用 DeepSeek API
  3424. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3425. } else if (in_array($model, $this->gpt_text_models)) {
  3426. // GPT-5.4 模型使用 TokenRouter API
  3427. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3428. } else if (in_array($model, $this->gemini_text_models)) {
  3429. // Gemini 模型使用 Gemini API
  3430. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3431. } else {
  3432. // 其他模型使用火山引擎API
  3433. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3434. }
  3435. // 处理流式输出
  3436. foreach ($streamGenerator as $chunk) {
  3437. if (isset($chunk['type'])) {
  3438. if ($chunk['type'] === 'done') {
  3439. // 最终结果
  3440. $fullContent = $chunk['full_content'];
  3441. $fullReasoningContent = $chunk['full_reasoning'];
  3442. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3443. } else {
  3444. // 逐块yield数据
  3445. yield $chunk;
  3446. }
  3447. }
  3448. }
  3449. dLog('deepseek')->info('完整内容: '.$fullContent);
  3450. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3451. // 处理完整内容并返回最终结果
  3452. $script_arr = [];
  3453. if ($fullContent) {
  3454. $script_arr = extractScriptContent($fullContent);
  3455. }
  3456. logDB('deepseek', 'info', '解析内容', $script_arr);
  3457. if (!$script_arr['roles']) {
  3458. Utils::throwError('20003:未生成剧本相关信息');
  3459. // yield [
  3460. // 'type' => 'done',
  3461. // 'script' => $script_arr,
  3462. // 'msg' => '未生成剧本相关信息',
  3463. // 'answer' => $fullContent,
  3464. // 'reasoning' => $fullReasoningContent,
  3465. // 'usage' => $usage
  3466. // ];
  3467. }
  3468. try {
  3469. DB::beginTransaction();
  3470. // // 返回前保存剧本内容
  3471. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3472. // 'content' => $content,
  3473. // 'status' => '解析完成',
  3474. // 'updated_at' => date('Y-m-d H:i:s')
  3475. // ]);
  3476. // if (!$boolen) {
  3477. // Utils::throwError('20003:保存剧本内容失败');
  3478. // }
  3479. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3480. 'start_episode_number' => $start_episode_sequence,
  3481. 'end_episode_number' => $end_episode_sequence,
  3482. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3483. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3484. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3485. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3486. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3487. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3488. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3489. 'status' => '解析完成',
  3490. 'content' => $content,
  3491. 'updated_at' => date('Y-m-d H:i:s')
  3492. ]);
  3493. if (!$boolen1) {
  3494. Utils::throwError('20003:保存分集失败');
  3495. }
  3496. // $episodes = [];
  3497. // foreach ($script_arr['episodes'] as $item) {
  3498. // $episodes[] = [
  3499. // 'script_id' => $script_id,
  3500. // 'episode_number' => $item['episode_number'],
  3501. // 'episode_name' => $item['episode_name'],
  3502. // 'episode_content' => $item['episode_content'],
  3503. // 'created_at' => date('Y-m-d H:i:s'),
  3504. // 'updated_at' => date('Y-m-d H:i:s'),
  3505. // ];
  3506. // }
  3507. // if ($episodes) {
  3508. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3509. // if (!$boolen2) {
  3510. // Utils::throwError('20003:保存分集内容失败');
  3511. // }
  3512. // }else {
  3513. // Utils::throwError('20003:分集剧本解析失败');
  3514. // }
  3515. }catch (\Exception $e) {
  3516. DB::rollBack();
  3517. Utils::throwError('20003:'.$e->getMessage());
  3518. }
  3519. DB::commit();
  3520. yield [
  3521. 'type' => 'done',
  3522. 'script' => $script_arr,
  3523. 'answer' => $fullContent,
  3524. 'reasoning' => $fullReasoningContent,
  3525. 'usage' => $usage
  3526. ];
  3527. }
  3528. /**
  3529. * 上传文件识别文字内容并与 DeepSeek 进行对话
  3530. *
  3531. * @param array $data 包含以下参数:
  3532. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3533. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  3534. * - model: 使用的模型(r1 或 v3,默认 v3)
  3535. * @return array
  3536. */
  3537. public function chatWithFile($data) {
  3538. $script_id = getProp($data, 'script_id');
  3539. $file = getProp($data, 'file');
  3540. $content = getProp($data, 'content', '');
  3541. $bid = getProp($data, 'bid', 0);
  3542. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3543. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3544. $prompt = getProp($data, 'prompt');
  3545. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3546. if (!empty($prompt)) {
  3547. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3548. }
  3549. $question = getProp($data, 'question', $baseQuestion);
  3550. // 处理文本模型
  3551. $model = getProp($data, 'model');
  3552. if (!$model) {
  3553. // 用户没有输入,使用默认值
  3554. $model = 'doubao-seed-2-0-mini-260215';
  3555. }
  3556. // 验证模型是否在可用模型表中
  3557. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3558. $model = 'doubao-seed-2-0-mini-260215';
  3559. }
  3560. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3561. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3562. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3563. if ($model === 'deepseek-chat') {
  3564. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3565. $model = 'deepseek-v4-flash';
  3566. $thinkingMode = 'disabled';
  3567. } elseif ($model === 'deepseek-reasoner') {
  3568. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3569. $model = 'deepseek-v4-flash';
  3570. $thinkingMode = 'enabled';
  3571. }
  3572. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3573. if (!$script) {
  3574. Utils::throwError('20003:剧本不存在');
  3575. }
  3576. if (!$file && !$content && !$bid) {
  3577. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3578. }
  3579. // 提取文件内容
  3580. if ($file) {
  3581. $content = $this->extractFileContent($file);
  3582. if (!$content) {
  3583. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3584. }
  3585. } elseif ($bid) {
  3586. $content = $this->getContentByBid($bid);
  3587. if (!$content) {
  3588. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3589. }
  3590. } elseif ($content) {
  3591. $content = filterContent($content);
  3592. } elseif ($prompt) {
  3593. $content = filterContent($prompt);
  3594. } else {
  3595. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3596. }
  3597. // 构建消息
  3598. $messages = [
  3599. $this->sys_message,
  3600. [
  3601. 'role' => 'user',
  3602. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3603. ]
  3604. ];
  3605. $post_data = [
  3606. 'model' => $model,
  3607. 'messages' => $messages,
  3608. // 'max_tokens' => 8192,
  3609. 'temperature' => 0.7,
  3610. 'frequency_penalty' => 0,
  3611. 'presence_penalty' => 0,
  3612. 'thinking' => ['type' => $thinkingMode],
  3613. 'response_format' => ['type' => 'text'],
  3614. 'stream' => false
  3615. ];
  3616. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3617. // 根据模型类型选择调用方法
  3618. $fullContent = '';
  3619. $usage = [];
  3620. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3621. // DeepSeek 官方模型使用 DeepSeek API
  3622. $chatResult = $this->chatOnly($post_data);
  3623. } else if (in_array($model, $this->gpt_text_models)) {
  3624. // GPT-5.4 模型使用 TokenRouter API
  3625. $chatResult = $this->gpt54ChatOnly($post_data);
  3626. } else {
  3627. // 其他模型使用火山引擎API
  3628. $chatResult = $this->volcEngineChatCompletion($post_data);
  3629. }
  3630. if (is_array($chatResult)) {
  3631. $fullContent = $chatResult['fullContent'];
  3632. $usage = $chatResult['usage'];
  3633. }
  3634. $script_arr = [];
  3635. // 处理结果
  3636. if ($fullContent) {
  3637. $script_arr = extractScriptContent($fullContent);
  3638. }
  3639. // 返回前保存剧本内容
  3640. DB::table('mp_scripts')->where('id', $script_id)->update([
  3641. 'content' => $content,
  3642. 'updated_at' => date('Y-m-d H:i:s')
  3643. ]);
  3644. return [
  3645. 'script' => $script_arr,
  3646. 'answer' => $fullContent,
  3647. 'usage' => $usage
  3648. ];
  3649. }
  3650. public function getEpisodeContent($data) {
  3651. $group_id = getProp($data, 'group_id');
  3652. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  3653. }
  3654. public function saveEpisodeContent($data) {
  3655. $script_id = getProp($data, 'script_id');
  3656. $group_id = getProp($data, 'group_id');
  3657. $start_episode_sequence = getProp($data, 'start_episode_number');
  3658. $end_episode_sequence = getProp($data, 'end_episode_number');
  3659. // 检查是否存在重叠的剧集序号范围
  3660. $exists_groups = DB::table('mp_script_episode_group')
  3661. ->where('script_id', $script_id)
  3662. ->where('id', '<>', $group_id) // 排除当前组
  3663. ->where('is_deleted', 0)
  3664. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3665. // 检查新范围是否与现有范围重叠
  3666. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3667. // 新范围的开始在现有范围内
  3668. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3669. ->where('end_episode_number', '>=', $start_episode_sequence);
  3670. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3671. // 新范围的结束在现有范围内
  3672. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3673. ->where('end_episode_number', '>=', $end_episode_sequence);
  3674. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3675. // 新范围完全包含现有范围
  3676. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3677. ->where('end_episode_number', '<=', $end_episode_sequence);
  3678. });
  3679. })
  3680. ->select('start_episode_number', 'end_episode_number')
  3681. ->get();
  3682. if ($exists_groups->isNotEmpty()) {
  3683. $conflict_ranges = [];
  3684. foreach ($exists_groups as $group) {
  3685. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3686. }
  3687. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3688. }
  3689. $episode_content = getProp($data, 'episode_content');
  3690. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  3691. 'content' => $episode_content,
  3692. 'start_episode_number' => $start_episode_sequence,
  3693. 'end_episode_number' => $end_episode_sequence,
  3694. 'updated_at' => date('Y-m-d H:i:s')
  3695. ]);
  3696. $script_arr =getProp($data, 'script', []);
  3697. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  3698. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3699. $script_id = getProp($data, 'script_id');
  3700. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  3701. try {
  3702. DB::beginTransaction();
  3703. $update_data = [
  3704. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3705. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3706. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3707. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3708. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3709. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3710. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3711. 'status' => 3,
  3712. 'start_episode_sequence' => $start_episode_sequence,
  3713. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  3714. 'episode_num' => count($script_arr['episodes']),
  3715. 'updated_at' => date('Y-m-d H:i:s')
  3716. ];
  3717. // 保存剧本内容
  3718. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  3719. if (!$boolen) {
  3720. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  3721. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  3722. Utils::throwError('20003:剧本内容保存失败');
  3723. }
  3724. // 保存分集内容
  3725. // 删除历史分集内容
  3726. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  3727. $episodes = [];
  3728. $sequence = 1;
  3729. foreach ($script_arr['episodes'] as $episode) {
  3730. $segment_number = 1;
  3731. foreach($episode['segments'] as $segment) {
  3732. $episodes[] = [
  3733. 'script_id' => $script_id,
  3734. 'episode_number' => $episode['episode_number'],
  3735. 'title' => $episode['title'],
  3736. // 'content' => $episode['content'],
  3737. 'content' => '',
  3738. 'segment_number' => $segment_number,
  3739. 'segment_content' => $segment['segment_content'],
  3740. 'sequence' => $sequence,
  3741. 'created_at' => date('Y-m-d H:i:s'),
  3742. 'updated_at' => date('Y-m-d H:i:s')
  3743. ];
  3744. $sequence++;
  3745. $segment_number++;
  3746. }
  3747. }
  3748. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3749. if (!$boolen2) {
  3750. dLog('deepseek')->info('分集内容保存失败', $episodes);
  3751. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  3752. Utils::throwError('20003:分集内容保存失败');
  3753. }
  3754. } catch (\Exception $e) {
  3755. DB::rollBack();
  3756. Utils::throwError('20003:'.$e->getMessage());
  3757. }
  3758. DB::commit();
  3759. return true;
  3760. }
  3761. public function getBookContent($data) {
  3762. $bid = getProp($data, 'bid');
  3763. $start_sequence = getProp($data, 'start_sequence');
  3764. $end_sequence = getProp($data, 'end_sequence');
  3765. $chapter_contents = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', 'cc.id')->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->whereBetween('c.sequence', [$start_sequence, $end_sequence])
  3766. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3767. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3768. return $return_content;
  3769. }
  3770. public function exportScript($data) {
  3771. $filename = getProp($data, 'filename');
  3772. $script_id = getProp($data, 'script_id');
  3773. $group_id = getProp($data, 'group_id');
  3774. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3775. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3776. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3777. $script = (array)$script;
  3778. // 获取分集组信息
  3779. if ($group_id) {
  3780. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3781. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3782. ->get()->map(function($value) {
  3783. return (array)$value;
  3784. })->toArray();
  3785. }else {
  3786. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3787. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3788. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3789. return (array)$value;
  3790. })->toArray();
  3791. }
  3792. if (!$groups) Utils::throwError('20003:分集不存在');
  3793. $script['group'] = $groups;
  3794. $export_type = getProp($data, 'export_type', 'txt');
  3795. // 生成文件名
  3796. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3797. // 根据导出类型生成不同格式的文件
  3798. switch ($export_type) {
  3799. case 'txt':
  3800. return $this->exportScriptAsTxt($script, $filename);
  3801. case 'pdf':
  3802. return $this->exportScriptAsPdf($script, $filename);
  3803. default:
  3804. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3805. }
  3806. }
  3807. /**
  3808. * 导出剧本为TXT格式
  3809. */
  3810. private function exportScriptAsTxt($script, $filename) {
  3811. // 构建TXT内容
  3812. $content = $this->buildScriptContent($script);
  3813. // 设置响应头,直接下载
  3814. header('Content-Type: text/plain; charset=utf-8');
  3815. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3816. header('Content-Length: ' . strlen($content));
  3817. // 输出内容并结束
  3818. echo $content;
  3819. exit();
  3820. }
  3821. /**
  3822. * 导出剧本为PDF格式
  3823. */
  3824. private function exportScriptAsPdf($script, $filename) {
  3825. // 使用HTML转PDF的方式来更好地支持中文
  3826. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3827. // 创建PDF实例
  3828. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3829. // 设置文档信息
  3830. $pdf->SetCreator('剧本导出系统');
  3831. $pdf->SetAuthor('系统');
  3832. $pdf->SetTitle($script['script_name']);
  3833. $pdf->SetSubject('剧本导出');
  3834. // 设置边距
  3835. $pdf->SetMargins(15, 15, 15);
  3836. $pdf->SetAutoPageBreak(TRUE, 15);
  3837. // 添加页面
  3838. $pdf->AddPage();
  3839. // 注册并使用 simsun.ttf 字体
  3840. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3841. // 使用HTML内容生成PDF
  3842. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3843. // 直接输出PDF文件供下载
  3844. header('Content-Type: application/pdf');
  3845. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3846. // 直接输出PDF内容
  3847. $pdf->Output($filename . '.pdf', 'D');
  3848. exit();
  3849. }
  3850. /**
  3851. * 构建用于PDF的HTML内容
  3852. */
  3853. private function buildScriptHtmlForPdf($script) {
  3854. $html = '<style>
  3855. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3856. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3857. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3858. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3859. .info { margin-bottom: 8px; }
  3860. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3861. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3862. .segment { margin-bottom: 10px; margin-left: 20px; }
  3863. .episode-content { white-space: pre-wrap; }
  3864. </style>';
  3865. // 标题
  3866. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3867. // 处理分组数据
  3868. if (!empty($script['group']) && is_array($script['group'])) {
  3869. $groups = (array)$script['group'];
  3870. foreach ($groups as $group) {
  3871. $html .= '<div class="group">';
  3872. // 分组标题
  3873. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3874. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3875. // 故事梗概
  3876. if (!empty($group['intro'])) {
  3877. $html .= '<h3>故事梗概</h3>';
  3878. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3879. }
  3880. // 剧本亮点
  3881. if (!empty($group['highlights'])) {
  3882. $html .= '<h3>剧本亮点</h3>';
  3883. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3884. }
  3885. // 人物关系
  3886. if (!empty($group['role_relationship'])) {
  3887. $html .= '<h3>人物关系</h3>';
  3888. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3889. }
  3890. // 核心矛盾
  3891. if (!empty($group['core_contradiction'])) {
  3892. $html .= '<h3>核心矛盾</h3>';
  3893. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3894. }
  3895. // 主体列表
  3896. if (!empty($group['roles']) && is_array($group['roles'])) {
  3897. $html .= '<h3>主体列表</h3>';
  3898. $html .= '<ul>';
  3899. foreach ($group['roles'] as $role) {
  3900. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3901. }
  3902. $html .= '</ul>';
  3903. }
  3904. // 美术风格
  3905. if (!empty($group['art_style'])) {
  3906. $html .= '<h3>美术风格</h3>';
  3907. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3908. }
  3909. // 场景列表
  3910. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3911. $html .= '<h3>场景列表</h3>';
  3912. $html .= '<ul>';
  3913. foreach ($group['scenes'] as $scene) {
  3914. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3915. }
  3916. $html .= '</ul>';
  3917. }
  3918. // 分集剧本
  3919. if (!empty($group['episode_content'])) {
  3920. $html .= '<h3>分集剧本</h3>';
  3921. // 去除零宽字符和其他不可见字符
  3922. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3923. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3924. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3925. }
  3926. $html .= '</div>';
  3927. }
  3928. }
  3929. return $html;
  3930. }
  3931. /**
  3932. * 构建PDF内容
  3933. */
  3934. private function buildPdfContent($pdf, $script) {
  3935. // 标题
  3936. $pdf->SetFont('dejavusans', 'B', 18);
  3937. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3938. $pdf->Ln(5);
  3939. // 基本信息
  3940. $pdf->SetFont('dejavusans', '', 12);
  3941. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3942. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3943. $pdf->Ln(5);
  3944. // 剧本简介
  3945. if (!empty($script['intro'])) {
  3946. $pdf->SetFont('dejavusans', 'B', 14);
  3947. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3948. $pdf->SetFont('dejavusans', '', 12);
  3949. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3950. $pdf->Ln(3);
  3951. }
  3952. // 亮点
  3953. if (!empty($script['highlights'])) {
  3954. $pdf->SetFont('dejavusans', 'B', 14);
  3955. $pdf->Cell(0, 10, '亮点', 0, 1);
  3956. $pdf->SetFont('dejavusans', '', 12);
  3957. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3958. $pdf->Ln(3);
  3959. }
  3960. // 核心矛盾
  3961. if (!empty($script['core_contradiction'])) {
  3962. $pdf->SetFont('dejavusans', 'B', 14);
  3963. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3964. $pdf->SetFont('dejavusans', '', 12);
  3965. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3966. $pdf->Ln(3);
  3967. }
  3968. // 艺术风格
  3969. if (!empty($script['art_style'])) {
  3970. $pdf->SetFont('dejavusans', 'B', 14);
  3971. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3972. $pdf->SetFont('dejavusans', '', 12);
  3973. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3974. $pdf->Ln(3);
  3975. }
  3976. // 备注
  3977. if (!empty($script['remark'])) {
  3978. $pdf->SetFont('dejavusans', 'B', 14);
  3979. $pdf->Cell(0, 10, '备注', 0, 1);
  3980. $pdf->SetFont('dejavusans', '', 12);
  3981. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3982. $pdf->Ln(3);
  3983. }
  3984. // 角色列表
  3985. if (!empty($script['roles']) && is_array($script['roles'])) {
  3986. $pdf->SetFont('dejavusans', 'B', 14);
  3987. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3988. $pdf->SetFont('dejavusans', '', 12);
  3989. foreach ($script['roles'] as $index => $role) {
  3990. if (is_array($role) || is_object($role)) {
  3991. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3992. } else {
  3993. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3994. }
  3995. }
  3996. $pdf->Ln(3);
  3997. }
  3998. // 角色关系
  3999. if (!empty($script['role_relationship'])) {
  4000. $pdf->SetFont('dejavusans', 'B', 14);
  4001. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4002. $pdf->SetFont('dejavusans', '', 12);
  4003. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4004. $pdf->Ln(3);
  4005. }
  4006. // 场景列表
  4007. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4008. $pdf->SetFont('dejavusans', 'B', 14);
  4009. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4010. $pdf->SetFont('dejavusans', '', 12);
  4011. foreach ($script['scenes'] as $index => $scene) {
  4012. if (is_array($scene) || is_object($scene)) {
  4013. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4014. } else {
  4015. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4016. }
  4017. }
  4018. $pdf->Ln(5);
  4019. }
  4020. // 分集内容
  4021. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4022. $pdf->SetFont('dejavusans', 'B', 16);
  4023. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4024. $pdf->Ln(3);
  4025. foreach ($script['episodes'] as $episode) {
  4026. // 检查是否需要新页面
  4027. if ($pdf->GetY() > 250) {
  4028. $pdf->AddPage();
  4029. }
  4030. $pdf->SetFont('dejavusans', 'B', 14);
  4031. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4032. if (!empty($episode['title'])) {
  4033. $episodeTitle .= ':' . $episode['title'];
  4034. }
  4035. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4036. // 处理分段内容
  4037. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4038. $pdf->SetFont('dejavusans', '', 12);
  4039. foreach ($episode['segments'] as $segment) {
  4040. if (!empty($segment['segment_content'])) {
  4041. // 如果有分段编号,显示分段标题
  4042. if (!empty($segment['segment_number'])) {
  4043. $pdf->SetFont('dejavusans', 'B', 12);
  4044. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4045. $pdf->SetFont('dejavusans', '', 12);
  4046. }
  4047. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4048. $pdf->Ln(2);
  4049. }
  4050. }
  4051. }
  4052. $pdf->Ln(5);
  4053. }
  4054. }
  4055. }
  4056. /**
  4057. * 构建剧本文本内容
  4058. */
  4059. private function buildScriptContent($script) {
  4060. $content = '';
  4061. $groups = $script['group'];
  4062. $groups = (array)$groups;
  4063. foreach ($groups as $group) {
  4064. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4065. // 剧本基本信息
  4066. if (!empty($group['intro'])) {
  4067. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4068. }
  4069. if (!empty($group['highlights'])) {
  4070. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4071. }
  4072. if (!empty($group['role_relationship'])) {
  4073. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4074. }
  4075. if (!empty($group['core_contradiction'])) {
  4076. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4077. }
  4078. if (!empty($group['roles']) && is_array($group['roles'])) {
  4079. $content .= "###主体列表\n";
  4080. foreach ($group['roles'] as $role) {
  4081. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4082. }
  4083. $content .= "\n\n";
  4084. }
  4085. if (!empty($group['art_style'])) {
  4086. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4087. }
  4088. // 场景信息
  4089. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4090. $content .= "###场景列表\n";
  4091. foreach ($group['scenes'] as $scene) {
  4092. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4093. }
  4094. $content .= "\n\n";
  4095. }
  4096. // 分集内容
  4097. if (!empty($group['episode_content'])) {
  4098. $content .= "###分集剧本\n";
  4099. $content .= $group['episode_content'];
  4100. // foreach ($script['episodes'] as $episode) {
  4101. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4102. // // if (!empty($episode['episode_name'])) {
  4103. // // $content .= ":" . $episode['episode_name'];
  4104. // // }
  4105. // // $content .= "\n";
  4106. // $content .= $episode['episode_content'] . "\n\n";
  4107. // }
  4108. }
  4109. }
  4110. return $content;
  4111. }
  4112. /**
  4113. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4114. *
  4115. * @param array $data 包含以下参数:
  4116. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4117. * - question: 用户问题(可选)
  4118. * - model: 使用的模型(r1 或 v3,默认 v3)
  4119. * @return \Generator 返回生成器,用于流式输出
  4120. */
  4121. public function addChat($data) {
  4122. $uid = Site::getUid();
  4123. $anime_id = getProp($data, 'anime_id');
  4124. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4125. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4126. if (!$anime) Utils::throwError('20003:对话不存在');
  4127. $file = getProp($data, 'file');
  4128. $content = getProp($data, 'content', '');
  4129. $bid = getProp($data, 'bid', 0);
  4130. $script_id = getProp($data, 'script_id', 0);
  4131. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4132. $prompt = getProp($data, 'prompt');
  4133. $user_anime_name = getProp($anime, 'anime_name');
  4134. // 处理文本模型
  4135. $model = getProp($data, 'model');
  4136. if (!$model) {
  4137. // 用户没有输入,从anime表获取
  4138. $model = getProp($anime, 'model');
  4139. if (!$model) {
  4140. // anime表也没有,使用默认值
  4141. $model = 'doubao-seed-2-0-mini-260215';
  4142. }
  4143. }
  4144. // 验证模型是否在可用模型表中
  4145. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4146. $model = 'doubao-seed-2-0-mini-260215';
  4147. }
  4148. $is_multi = getProp($anime, 'is_multi');
  4149. $is_single = (int)$is_multi !== 1;
  4150. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4151. if ($prompt) {
  4152. $question .= "本次修改要求如下:\n{$prompt}";
  4153. }
  4154. // if (!$file && !$content && !$bid) {
  4155. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4156. // }
  4157. // 提取文件内容
  4158. if ($file) {
  4159. $content = $this->extractFileContent($file);
  4160. if (!$content) {
  4161. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4162. }
  4163. } elseif ($script_id) {
  4164. $content = $this->getContentByScriptId($script_id);
  4165. if (!$content) {
  4166. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4167. }
  4168. } elseif ($bid) {
  4169. $content = $this->getContentByBid($bid);
  4170. if (!$content) {
  4171. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4172. }
  4173. } elseif ($content) {
  4174. $content = filterContent($content);
  4175. } else {
  4176. $content = getProp($anime, 'content');
  4177. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4178. $need_generate_content = true;
  4179. }
  4180. }
  4181. // 美术风格
  4182. $input_art_style = getProp($data, 'art_style');
  4183. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4184. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4185. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4186. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4187. 中年女:邻居阿姨
  4188. 老年男:幽默大爷
  4189. 老年女:婆婆
  4190. 萌娃:奶气萌娃";
  4191. // 判断是否需要生成原文内容
  4192. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4193. // 如果需要生成原文内容,添加额外的要求
  4194. $content_generation_requirement = $need_generate_content
  4195. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4196. : "";
  4197. // 美术风格
  4198. if (!$mappedArtStyle) {
  4199. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4200. }else {
  4201. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4202. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4203. }else {
  4204. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4205. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4206. }
  4207. }
  4208. $systemPrompt = $is_single
  4209. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4210. 强制要求:
  4211. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4212. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4213. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4214. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4215. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4216. 普通要求:
  4217. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4218. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4219. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4220. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4221. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4222. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4223. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4224. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4225. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4226. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4227. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4228. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4229. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4230. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4231. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4232. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4233. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4234. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4235. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4236. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4237. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4238. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4239. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4240. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4241. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4242. 5.{$mappedArtStyle_prompt}\n\n
  4243. 示例如下:\n
  4244. ###剧本名:西昆仑
  4245. ###故事梗概
  4246. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4247. ###剧本亮点
  4248. 亮点1:绝境奇药,生死一线
  4249. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4250. 亮点2:结拜兄妹,化解尴尬
  4251. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4252. 亮点3:纤发夺命,情愫暗涌
  4253. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4254. ###人物关系
  4255. 阿雪与梁萧之间存在兄妹之情。
  4256. ###核心矛盾
  4257. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4258. ###主体列表
  4259. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4260. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4261. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4262. 姿态:站立。}{{甜心小美}}
  4263. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4264. 全景,正面拍摄,青年女性,亚洲人。
  4265. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4266. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4267. 姿态:站立。}{{阳光青年}}
  4268. ###美术风格
  4269. 基础画风风格词:厚涂古风
  4270. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4271. ###场景列表
  4272. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4273. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4274. 无人物。}
  4275. ###分镜剧本
  4276. ##第1幕:徐家老旧厨房 白天 室内
  4277. 分镜1
  4278. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4279. 场景:徐家老旧厨房
  4280. 构图设计:全景,低角度仰视
  4281. 运镜调度:手持拍摄
  4282. 配音角色:旁白
  4283. 出镜角色:许芸-校服装、徐母
  4284. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4285. 画面类型:普通画面
  4286. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4287. 分镜2
  4288. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4289. 场景:徐家老旧厨房
  4290. 构图设计:近景,徐母面部特写
  4291. 运镜调度:固定镜头
  4292. 配音角色:徐母
  4293. 出镜角色:徐母
  4294. 台词内容:问我夜不归宿死哪儿去了。
  4295. 画面类型:对口型
  4296. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4297. ##第2幕:徐家简陋客厅 黄昏 室内
  4298. 分镜3
  4299. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4300. 场景:徐家简陋客厅
  4301. 构图设计:全景,景深虚化
  4302. 运镜调度:固定镜头
  4303. 配音角色:旁白
  4304. 出镜角色:无
  4305. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4306. 画面类型:普通画面
  4307. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4308. 分镜4
  4309. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4310. 场景:徐家简陋客厅
  4311. 构图设计:特写,火车票
  4312. 运镜调度:固定镜头
  4313. 配音角色:旁白
  4314. 出镜角色:无
  4315. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4316. 画面类型:普通画面
  4317. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4318. "
  4319. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4320. 强制要求:\n
  4321. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4322. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4323. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4324. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4325. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4326. 普通要求:\n
  4327. 1.剧本名(必须生成)必须与文档内容高度相关
  4328. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4329. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4330. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4331. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4332. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4333. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4334. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4335. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4336. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4337. 4.{$mappedArtStyle_prompt}\n\n
  4338. 示例如下:\n
  4339. ###剧本名:西昆仑
  4340. ###故事梗概
  4341. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4342. ###剧本亮点
  4343. 亮点1:绝境奇药,生死一线
  4344. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4345. 亮点2:结拜兄妹,化解尴尬
  4346. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4347. 亮点3:纤发夺命,情愫暗涌
  4348. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4349. ###人物关系
  4350. 阿雪与梁萧之间存在兄妹之情。
  4351. ###核心矛盾
  4352. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4353. ###主体列表
  4354. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4355. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4356. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4357. 姿态:站立。}{{甜心小美}}
  4358. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4359. 全景,正面拍摄,青年女性,亚洲人。
  4360. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4361. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4362. 姿态:站立。}{{阳光青年}}
  4363. ###美术风格
  4364. 基础画风风格词:厚涂古风
  4365. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4366. ###场景列表
  4367. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4368. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4369. 无人物。}";
  4370. // 构建消息
  4371. $messages = [
  4372. [
  4373. 'role' => 'system',
  4374. 'content' => $systemPrompt
  4375. ],
  4376. [
  4377. 'role' => 'user',
  4378. 'content' => "以下是文档内容:
  4379. {$content}
  4380. 用户问题:
  4381. {$question}"
  4382. ]
  4383. ];
  4384. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4385. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4386. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4387. if ($model === 'deepseek-chat') {
  4388. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4389. $model = 'deepseek-v4-flash';
  4390. $thinkingMode = 'disabled';
  4391. } elseif ($model === 'deepseek-reasoner') {
  4392. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4393. $model = 'deepseek-v4-flash';
  4394. $thinkingMode = 'enabled';
  4395. }
  4396. $post_data = [
  4397. 'model' => $model,
  4398. 'messages' => $messages,
  4399. // 'max_tokens' => 8192,
  4400. 'temperature' => 0.7,
  4401. 'frequency_penalty' => 0,
  4402. 'presence_penalty' => 0,
  4403. 'response_format' => ['type' => 'text'],
  4404. 'thinking' => ['type'=>$thinkingMode],
  4405. 'stream' => true // 启用流式输出
  4406. ];
  4407. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4408. // 根据模型类型选择调用方法
  4409. $fullContent = '';
  4410. $fullReasoningContent = '';
  4411. $usage = [];
  4412. try {
  4413. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4414. // DeepSeek 官方模型使用 DeepSeek API
  4415. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4416. } else if (in_array($model, $this->gpt_text_models)) {
  4417. // GPT-5.4 模型使用 TokenRouter API
  4418. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4419. } else if (in_array($model, $this->gemini_text_models)) {
  4420. // Gemini 模型使用 Gemini API
  4421. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4422. } else {
  4423. // 其他模型使用火山引擎API
  4424. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4425. }
  4426. // 验证返回值类型
  4427. if (!is_iterable($streamGenerator)) {
  4428. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4429. dLog('deepseek')->error('addChat流式生成器无效', [
  4430. 'generator_type' => $errorType,
  4431. 'model' => $model,
  4432. 'anime_id' => $anime_id
  4433. ]);
  4434. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4435. 'type' => $errorType,
  4436. 'model' => $model
  4437. ]);
  4438. yield [
  4439. 'type' => 'error',
  4440. 'script' => [],
  4441. 'episode' => [],
  4442. 'answer' => '',
  4443. 'reasoning' => '',
  4444. 'usage' => [],
  4445. 'error' => '接口返回数据异常,请重新请求'
  4446. ];
  4447. return;
  4448. }
  4449. // 处理流式输出
  4450. foreach ($streamGenerator as $chunk) {
  4451. if (isset($chunk['type'])) {
  4452. if ($chunk['type'] === 'done') {
  4453. // 最终结果
  4454. $fullContent = $chunk['full_content'];
  4455. $fullReasoningContent = $chunk['full_reasoning'];
  4456. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4457. } else {
  4458. // 逐块yield数据
  4459. yield $chunk;
  4460. }
  4461. }
  4462. }
  4463. } catch (\Exception $e) {
  4464. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4465. 'model' => $model,
  4466. 'anime_id' => $anime_id,
  4467. 'trace' => $e->getTraceAsString()
  4468. ]);
  4469. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4470. 'error' => $e->getMessage(),
  4471. 'model' => $model
  4472. ]);
  4473. yield [
  4474. 'type' => 'error',
  4475. 'script' => [],
  4476. 'episode' => [],
  4477. 'answer' => '',
  4478. 'reasoning' => '',
  4479. 'usage' => [],
  4480. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4481. ];
  4482. return;
  4483. }
  4484. dLog('deepseek')->info('完整内容: '.$fullContent);
  4485. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4486. // 处理完整内容并返回最终结果
  4487. $script_arr = [];
  4488. if ($fullContent) {
  4489. $script_arr = handleScriptContent($fullContent);
  4490. dLog('deepseek')->info('解析内容', $script_arr);
  4491. logDB('deepseek', 'info', '解析内容', $script_arr);
  4492. }
  4493. if (empty($script_arr['roles'])) {
  4494. // 未生成剧本相关内容,保存对话记录并返回提示
  4495. dLog('deepseek')->info('未生成剧本相关的内容');
  4496. try {
  4497. DB::beginTransaction();
  4498. $now = date('Y-m-d H:i:s');
  4499. // 保存对话记录
  4500. $records = [
  4501. [
  4502. 'uid' => $uid,
  4503. 'anime_id' => $anime_id,
  4504. 'sequence' => 0,
  4505. 'role' => 'user',
  4506. 'content' => $prompt,
  4507. 'created_at' => $now,
  4508. 'updated_at' => $now
  4509. ],
  4510. [
  4511. 'uid' => $uid,
  4512. 'anime_id' => $anime_id,
  4513. 'sequence' => 0,
  4514. 'role' => 'assistant',
  4515. // 'content' => $fullContent,
  4516. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  4517. 'created_at' => $now,
  4518. 'updated_at' => $now
  4519. ]
  4520. ];
  4521. DB::table('mp_anime_records')->insert($records);
  4522. DB::commit();
  4523. } catch (\Exception $e) {
  4524. DB::rollBack();
  4525. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4526. }
  4527. yield [
  4528. 'type' => 'done',
  4529. 'script' => [],
  4530. 'episode' => [],
  4531. 'answer' => $fullContent,
  4532. 'reasoning' => $fullReasoningContent,
  4533. 'usage' => $usage,
  4534. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4535. ];
  4536. return;
  4537. }
  4538. // 如果需要生成原文内容,从script_arr中提取
  4539. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4540. $content = $script_arr['content'];
  4541. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  4542. if (!$content) {
  4543. yield [
  4544. 'type' => 'done',
  4545. 'script' => [],
  4546. 'episode' => [],
  4547. 'answer' => $fullContent,
  4548. 'reasoning' => $fullReasoningContent,
  4549. 'usage' => $usage,
  4550. 'error' => '未生成剧本内容,请调整提示词再试'
  4551. ];
  4552. return;
  4553. }
  4554. }
  4555. // 替换美术风格
  4556. if ($mappedArtStyle !== '') {
  4557. $script_arr['art_style'] = $mappedArtStyle;
  4558. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4559. }
  4560. // 新建动漫
  4561. if ($user_anime_name == '新剧本策划') {
  4562. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  4563. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  4564. // if (!$anime_name) {
  4565. // // 未识别到剧本名,保存对话记录并返回提示
  4566. // dLog('deepseek')->info('未能识别到剧本名称');
  4567. // try {
  4568. // DB::beginTransaction();
  4569. // $now = date('Y-m-d H:i:s');
  4570. // // 保存对话记录
  4571. // $records = [
  4572. // [
  4573. // 'uid' => $uid,
  4574. // 'anime_id' => $anime_id,
  4575. // 'sequence' => 0,
  4576. // 'role' => 'user',
  4577. // 'content' => $prompt,
  4578. // 'created_at' => $now,
  4579. // 'updated_at' => $now
  4580. // ],
  4581. // [
  4582. // 'uid' => $uid,
  4583. // 'anime_id' => $anime_id,
  4584. // 'sequence' => 0,
  4585. // 'role' => 'assistant',
  4586. // 'content' => '未能生成剧本名称,请重试',
  4587. // 'created_at' => $now,
  4588. // 'updated_at' => $now
  4589. // ]
  4590. // ];
  4591. // DB::table('mp_anime_records')->insert($records);
  4592. // DB::commit();
  4593. // } catch (\Exception $e) {
  4594. // DB::rollBack();
  4595. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4596. // }
  4597. // yield [
  4598. // 'type' => 'done',
  4599. // 'script' => [],
  4600. // 'episode' => [],
  4601. // 'answer' => $fullContent,
  4602. // 'reasoning' => $fullReasoningContent,
  4603. // 'usage' => $usage,
  4604. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  4605. // ];
  4606. // return;
  4607. // }
  4608. // 确认对话名称唯一性
  4609. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4610. $anime_name = $anime_name . '_' . date('YmdHis');
  4611. }
  4612. }else {
  4613. $anime_name = $user_anime_name;
  4614. }
  4615. $table_data = [
  4616. 'user_id' => $uid,
  4617. 'anime_name' => $anime_name,
  4618. 'model' => $model,
  4619. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4620. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4621. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4622. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4623. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4624. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4625. 'art_style_type' => $input_art_style,
  4626. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4627. 'status' => '解析完成',
  4628. 'content' => $content,
  4629. 'is_multi' => $is_multi,
  4630. 'ace_mode' => $ace_mode,
  4631. 'generate_status' => '待执行',
  4632. 'updated_at' => date('Y-m-d H:i:s')
  4633. ];
  4634. if ($table_data['content']) {
  4635. $chapters = splitContent($table_data['content']);
  4636. $chapter_count = count($chapters);
  4637. if ($chapter_count > 0) {
  4638. $table_data['start_episode_sequence'] = 1;
  4639. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4640. }
  4641. }
  4642. // 如果有剧本ID则进行绑定
  4643. if ($script_id) {
  4644. $table_data['script_id'] = $script_id;
  4645. }
  4646. $single_episode = [];
  4647. try {
  4648. DB::beginTransaction();
  4649. $now = date('Y-m-d H:i:s');
  4650. // 更新动漫大纲
  4651. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4652. if (!$boolen) {
  4653. dLog('deepseek')->info('动漫保存失败', $table_data);
  4654. Utils::throwError('20003:动漫保存失败');
  4655. }
  4656. // 保存对话记录
  4657. $records = [
  4658. [
  4659. 'uid' => $uid,
  4660. 'anime_id' => $anime_id,
  4661. 'sequence' => 0,
  4662. 'role' => 'user',
  4663. 'content' => $prompt,
  4664. 'created_at' => date('Y-m-d H:i:s'),
  4665. 'updated_at' => date('Y-m-d H:i:s')
  4666. ],
  4667. [
  4668. 'uid' => $uid,
  4669. 'anime_id' => $anime_id,
  4670. 'sequence' => 0,
  4671. 'role' => 'assistant',
  4672. 'content' => $fullContent,
  4673. 'created_at' => date('Y-m-d H:i:s'),
  4674. 'updated_at' => date('Y-m-d H:i:s')
  4675. ]
  4676. ];
  4677. // 保存对话记录
  4678. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4679. if (!$boolen3) {
  4680. Utils::throwError('20003:对话记录保存失败');
  4681. }
  4682. if ($is_single) {
  4683. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4684. if (empty($episode_arr['acts'])) {
  4685. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4686. }
  4687. $saveResult = $this->saveEpisodeVersionData(
  4688. $anime_id,
  4689. 1,
  4690. $episode_arr,
  4691. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4692. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4693. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4694. null,
  4695. null,
  4696. false,
  4697. $content,
  4698. $now
  4699. );
  4700. $single_episode = $saveResult['episode'];
  4701. $episode_id = $saveResult['episode_id'];
  4702. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4703. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4704. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4705. 'props' => json_encode($saveResult['merged_props'], 256),
  4706. 'updated_at' => $now
  4707. ]);
  4708. if ($boolen5 === false) {
  4709. Utils::throwError('20003:单剧集主表资源同步失败');
  4710. }
  4711. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4712. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4713. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4714. $episode_record_content = '确认分镜大纲';
  4715. if ($content !== '') {
  4716. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4717. }
  4718. $episode_records = [
  4719. [
  4720. 'uid' => $uid,
  4721. 'anime_id' => $anime_id,
  4722. 'role' => 'user',
  4723. 'content' => $episode_record_content,
  4724. 'sequence' => 1,
  4725. 'episode_id' => $episode_id,
  4726. 'created_at' => $now,
  4727. 'updated_at' => $now
  4728. ],
  4729. [
  4730. 'uid' => $uid,
  4731. 'anime_id' => $anime_id,
  4732. 'role' => 'assistant',
  4733. 'content' => $fullContent,
  4734. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4735. 'sequence' => 1,
  4736. 'episode_id' => $episode_id,
  4737. 'created_at' => $now,
  4738. 'updated_at' => $now
  4739. ]
  4740. ];
  4741. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4742. if (!$boolen4) {
  4743. Utils::throwError('20003:单剧集分镜记录保存失败');
  4744. }
  4745. }
  4746. }catch (\Exception $e) {
  4747. DB::rollBack();
  4748. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4749. yield [
  4750. 'type' => 'done',
  4751. 'answer' => $fullContent,
  4752. 'reasoning' => $fullReasoningContent,
  4753. 'usage' => $usage,
  4754. 'error' => $e->getMessage(),
  4755. ];
  4756. return;
  4757. }
  4758. DB::commit();
  4759. dLog('deepseek')->info('保存完毕');
  4760. if ($is_single && !empty($single_episode)) {
  4761. // $this->batchSetGlobalRoleImg([
  4762. // 'anime_id' => $anime_id,
  4763. // ]);
  4764. // $this->batchSetGlobalSceneImg([
  4765. // 'anime_id' => $anime_id,
  4766. // ]);
  4767. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4768. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4769. }
  4770. $table_data['anime_id'] = $anime_id;
  4771. $table_data['roles'] = json_decode($table_data['roles'], true);
  4772. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4773. // $table_data['episodes'] = $script_arr['episodes'];
  4774. unset($table_data['created_at']);
  4775. unset($table_data['updated_at']);
  4776. unset($table_data['status']);
  4777. dLog('deepseek')->info('开始返回');
  4778. yield [
  4779. 'type' => 'done',
  4780. 'script' => $table_data,
  4781. 'episode' => $single_episode,
  4782. 'answer' => $fullContent,
  4783. 'reasoning' => $fullReasoningContent,
  4784. 'usage' => $usage
  4785. ];
  4786. }
  4787. public function reGenerateAnime($data) {
  4788. $uid = Site::getUid();
  4789. $file = getProp($data, 'file');
  4790. $content = getProp($data, 'content', '');
  4791. $bid = getProp($data, 'bid', 0);
  4792. $script_id = getProp($data, 'script_id', 0);
  4793. $anime_id = getProp($data, 'anime_id');
  4794. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4795. if (!$anime) {
  4796. Utils::throwError('20003:该对话不存在');
  4797. }
  4798. $user_anime_name = getProp($anime, 'anime_name');
  4799. $prompt = getProp($data, 'prompt');
  4800. // 处理文本模型
  4801. $model = getProp($data, 'model');
  4802. if (!$model) {
  4803. // 用户没有输入,从anime表获取
  4804. $model = getProp($anime, 'model');
  4805. if (!$model) {
  4806. // anime表也没有,使用默认值
  4807. $model = 'doubao-seed-2-0-mini-260215';
  4808. }
  4809. }
  4810. // 验证模型是否在可用模型表中
  4811. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4812. $model = 'doubao-seed-2-0-mini-260215';
  4813. }
  4814. $is_multi = getProp($anime, 'is_multi', 1);
  4815. $is_single = (int)$is_multi !== 1;
  4816. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4817. if ($is_single) {
  4818. $episode_exists = DB::table('mp_anime_episodes')
  4819. ->where('anime_id', $anime_id)
  4820. ->where('sequence', 1)
  4821. ->exists();
  4822. if ($episode_exists) {
  4823. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4824. }
  4825. }
  4826. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4827. if ($prompt) {
  4828. $question .= "本次修改要求如下:\n{$prompt}";
  4829. }
  4830. // 提取文件内容
  4831. if ($file) {
  4832. $content = $this->extractFileContent($file);
  4833. if (!$content) {
  4834. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4835. }
  4836. } elseif ($script_id) {
  4837. $content = $this->getContentByScriptId($script_id);
  4838. if (!$content) {
  4839. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4840. }
  4841. } elseif ($bid) {
  4842. $content = $this->getContentByBid($bid);
  4843. if (!$content) {
  4844. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4845. }
  4846. } elseif ($content) {
  4847. $content = filterContent($content);
  4848. }else {
  4849. $content = filterContent(getProp($anime, 'content'));
  4850. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4851. $need_generate_content = true;
  4852. }
  4853. }
  4854. // 判断是否需要生成原文内容
  4855. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4856. // 如果需要生成原文内容,添加额外的要求
  4857. $content_generation_requirement = $need_generate_content
  4858. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4859. : "";
  4860. // 美术风格
  4861. $input_art_style = getProp($anime, 'art_style');
  4862. if (!$input_art_style) {
  4863. $input_art_style = getProp($data, 'art_style');
  4864. }
  4865. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4866. // 美术风格
  4867. if (!$mappedArtStyle) {
  4868. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4869. }else {
  4870. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4871. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4872. }else {
  4873. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4874. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4875. }
  4876. }
  4877. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4878. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4879. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4880. 中年女:邻居阿姨
  4881. 老年男:幽默大爷
  4882. 老年女:婆婆
  4883. 萌娃:奶气萌娃";
  4884. $system_message = ['role'=>'system', 'content'=>$is_single
  4885. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4886. 强制要求:
  4887. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4888. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4889. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4890. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4891. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4892. 普通要求:
  4893. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4894. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4895. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4896. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4897. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4898. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4899. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4900. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4901. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4902. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4903. 3.$mappedArtStyle_prompt\n\n
  4904. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4905. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4906. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4907. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4908. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4909. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4910. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4911. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4912. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4913. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4914. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4915. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4916. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4917. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4918. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4919. 示例如下:\n
  4920. ###剧本名:西昆仑
  4921. ###故事梗概
  4922. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4923. ###剧本亮点
  4924. 亮点1:绝境奇药,生死一线
  4925. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4926. 亮点2:结拜兄妹,化解尴尬
  4927. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4928. 亮点3:纤发夺命,情愫暗涌
  4929. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4930. ###人物关系
  4931. 阿雪与梁萧之间存在兄妹之情。
  4932. ###核心矛盾
  4933. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4934. ###主体列表
  4935. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4936. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4937. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4938. 姿态:站立。}{{甜心小美}}
  4939. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4940. 全景,正面拍摄,青年女性,亚洲人。
  4941. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4942. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4943. 姿态:站立。}{{阳光青年}}
  4944. ###美术风格
  4945. 基础画风风格词:厚涂古风
  4946. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4947. ###场景列表
  4948. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4949. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4950. 无人物。}
  4951. ###分镜剧本
  4952. ##第1幕:徐家老旧厨房 白天 室内
  4953. 分镜1
  4954. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4955. 场景:徐家老旧厨房
  4956. 构图设计:全景,低角度仰视
  4957. 运镜调度:手持拍摄
  4958. 配音角色:旁白
  4959. 出镜角色:许芸-校服装、徐母
  4960. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4961. 画面类型:普通画面
  4962. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4963. 分镜2
  4964. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4965. 场景:徐家老旧厨房
  4966. 构图设计:近景,徐母面部特写
  4967. 运镜调度:固定镜头
  4968. 配音角色:徐母
  4969. 出镜角色:徐母
  4970. 台词内容:问我夜不归宿死哪儿去了。
  4971. 画面类型:对口型
  4972. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4973. ##第2幕:徐家简陋客厅 黄昏 室内
  4974. 分镜3
  4975. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4976. 场景:徐家简陋客厅
  4977. 构图设计:全景,景深虚化
  4978. 运镜调度:固定镜头
  4979. 配音角色:旁白
  4980. 出镜角色:无
  4981. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4982. 画面类型:普通画面
  4983. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4984. 分镜4
  4985. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4986. 场景:徐家简陋客厅
  4987. 构图设计:特写,火车票
  4988. 运镜调度:固定镜头
  4989. 配音角色:旁白
  4990. 出镜角色:无
  4991. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4992. 画面类型:普通画面
  4993. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4994. "
  4995. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4996. 强制要求:\n
  4997. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4998. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4999. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5000. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5001. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5002. 普通要求:\n
  5003. 1.剧本名(必须生成)必须与文档内容高度相关
  5004. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5005. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5006. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5007. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5008. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5009. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5010. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5011. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5012. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5013. 4.$mappedArtStyle_prompt\n\n
  5014. 示例如下:\n
  5015. ###剧本名:西昆仑
  5016. ###故事梗概
  5017. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5018. ###剧本亮点
  5019. 亮点1:绝境奇药,生死一线
  5020. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5021. 亮点2:结拜兄妹,化解尴尬
  5022. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5023. 亮点3:纤发夺命,情愫暗涌
  5024. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5025. ###人物关系
  5026. 阿雪与梁萧之间存在兄妹之情。
  5027. ###核心矛盾
  5028. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5029. ###主体列表
  5030. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5031. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5032. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5033. 姿态:站立。}{{甜心小美}}
  5034. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5035. 全景,正面拍摄,青年女性,亚洲人。
  5036. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5037. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5038. 姿态:站立。}{{阳光青年}}
  5039. ###美术风格
  5040. 基础画风风格词:厚涂古风
  5041. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5042. ###场景列表
  5043. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5044. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5045. 无人物。}"];
  5046. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5047. $episode_count = $this->extractEpisodeNumber($prompt);
  5048. if ((int)getProp($anime, 'is_multi') !== 1) {
  5049. yield [
  5050. 'type' => 'done',
  5051. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5052. 'reasoning' => '',
  5053. 'usage' => []
  5054. ];
  5055. return;
  5056. }
  5057. if ($episode_count) {
  5058. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5059. $system_message = [
  5060. 'role' => 'system',
  5061. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5062. 强制要求:\n
  5063. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5064. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5065. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5066. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5067. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5068. 普通要求:\n
  5069. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5070. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5071. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5072. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5073. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5074. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5075. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5076. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5077. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5078. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5079. 示例如下:\n
  5080. ###剧本名:西昆仑
  5081. ###故事梗概
  5082. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5083. ###剧本亮点
  5084. 亮点1:绝境奇药,生死一线
  5085. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5086. 亮点2:结拜兄妹,化解尴尬
  5087. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5088. 亮点3:纤发夺命,情愫暗涌
  5089. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5090. ###人物关系
  5091. 阿雪与梁萧之间存在兄妹之情。
  5092. ###核心矛盾
  5093. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5094. ###主体列表
  5095. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5096. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5097. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5098. 姿态:站立。}{{甜心小美}}
  5099. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5100. 全景,正面拍摄,青年女性,亚洲人。
  5101. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5102. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5103. 姿态:站立。}{{阳光青年}}
  5104. ###美术风格
  5105. 基础画风风格词:厚涂古风
  5106. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5107. ###场景列表
  5108. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5109. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5110. 无人物。}
  5111. ###分集详细内容
  5112. ##第1章 重生
  5113. 我重生了。
  5114. 源于一个男人偏执的暗恋。
  5115. ##第2章 相救
  5116. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5117. 我眼睛扫向站在锅炉后的卞大伟。"
  5118. ];
  5119. // 构建消息
  5120. $messages = [
  5121. $system_message,
  5122. [
  5123. 'role' => 'user',
  5124. 'content' => "以下是文档内容:
  5125. {$content}
  5126. 用户问题:
  5127. {$question}"
  5128. ]
  5129. ];
  5130. }else {
  5131. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5132. // 构建消息
  5133. $messages = [
  5134. $system_message,
  5135. [
  5136. 'role' => 'user',
  5137. 'content' => "以下是文档内容:
  5138. {$content}
  5139. 用户问题:
  5140. {$question}"
  5141. ]
  5142. ];
  5143. }else {
  5144. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5145. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5146. return (array)$value;
  5147. })->toArray();
  5148. array_unshift($messages, $system_message);
  5149. $messages[] = [
  5150. 'role' => 'user',
  5151. 'content' => $prompt
  5152. ];
  5153. }
  5154. }
  5155. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5156. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5157. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5158. if ($model === 'deepseek-chat') {
  5159. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5160. $model = 'deepseek-v4-flash';
  5161. $thinkingMode = 'disabled';
  5162. } elseif ($model === 'deepseek-reasoner') {
  5163. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5164. $model = 'deepseek-v4-flash';
  5165. $thinkingMode = 'enabled';
  5166. }
  5167. $post_data = [
  5168. 'model' => $model,
  5169. 'messages' => $messages,
  5170. // 'max_tokens' => 8192,
  5171. 'temperature' => 0.7,
  5172. 'frequency_penalty' => 0,
  5173. 'presence_penalty' => 0,
  5174. 'response_format' => ['type' => 'text'],
  5175. 'thinking' => ['type' => $thinkingMode],
  5176. 'stream' => true // 启用流式输出
  5177. ];
  5178. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5179. // 根据模型类型选择调用方法
  5180. $fullContent = '';
  5181. $fullReasoningContent = '';
  5182. $usage = [];
  5183. // dd($post_data);
  5184. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5185. try {
  5186. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5187. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5188. } else if (in_array($model, $this->gpt_text_models)) {
  5189. // GPT-5.4 模型使用 TokenRouter API
  5190. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5191. } else if (in_array($model, $this->gemini_text_models)) {
  5192. // Gemini 模型使用 Gemini API
  5193. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5194. } else {
  5195. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5196. }
  5197. // 验证返回值类型
  5198. if (!is_iterable($streamGenerator)) {
  5199. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5200. dLog('deepseek')->error('方法名流式生成器无效', [
  5201. 'generator_type' => $errorType,
  5202. 'model' => $model,
  5203. // 添加其他上下文信息
  5204. ]);
  5205. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5206. 'type' => $errorType,
  5207. 'model' => $model
  5208. ]);
  5209. yield [
  5210. 'type' => 'error',
  5211. // 根据方法返回相应的空数据结构
  5212. 'answer' => '',
  5213. 'reasoning' => '',
  5214. 'usage' => [],
  5215. 'error' => '接口返回数据异常,请重新请求'
  5216. ];
  5217. return;
  5218. }
  5219. // 处理流式输出
  5220. foreach ($streamGenerator as $chunk) {
  5221. if (isset($chunk['type'])) {
  5222. if ($chunk['type'] === 'done') {
  5223. $fullContent = $chunk['full_content'];
  5224. $fullReasoningContent = $chunk['full_reasoning'];
  5225. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5226. } else {
  5227. yield $chunk;
  5228. }
  5229. }
  5230. }
  5231. } catch (\Exception $e) {
  5232. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5233. 'model' => $model,
  5234. 'trace' => $e->getTraceAsString()
  5235. ]);
  5236. logDB('deepseek', 'error', '方法名流式处理失败', [
  5237. 'error' => $e->getMessage(),
  5238. 'model' => $model
  5239. ]);
  5240. yield [
  5241. 'type' => 'error',
  5242. // 根据方法返回相应的空数据结构
  5243. 'answer' => '',
  5244. 'reasoning' => '',
  5245. 'usage' => [],
  5246. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5247. ];
  5248. return;
  5249. }
  5250. dLog('deepseek')->info('完整内容: '.$fullContent);
  5251. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5252. // 处理完整内容并返回最终结果
  5253. $script_arr = [];
  5254. if ($fullContent) {
  5255. $script_arr = handleScriptContent($fullContent);
  5256. dLog('deepseek')->info('解析内容', $script_arr);
  5257. logDB('deepseek', 'info', '解析内容', $script_arr);
  5258. }
  5259. if (empty($script_arr['roles'])) {
  5260. // 未生成剧本相关内容,保存对话记录并返回提示
  5261. dLog('deepseek')->info('未生成剧本相关的内容');
  5262. try {
  5263. $now = date('Y-m-d H:i:s');
  5264. // 保存对话记录
  5265. $records = [
  5266. [
  5267. 'uid' => $uid,
  5268. 'anime_id' => $anime_id,
  5269. 'sequence' => 0,
  5270. 'role' => 'user',
  5271. 'content' => $prompt,
  5272. 'created_at' => $now,
  5273. 'updated_at' => $now
  5274. ],
  5275. [
  5276. 'uid' => $uid,
  5277. 'anime_id' => $anime_id,
  5278. 'sequence' => 0,
  5279. 'role' => 'assistant',
  5280. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5281. 'created_at' => $now,
  5282. 'updated_at' => $now
  5283. ]
  5284. ];
  5285. DB::table('mp_anime_records')->insert($records);
  5286. } catch (\Exception $e) {
  5287. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5288. }
  5289. yield [
  5290. 'type' => 'done',
  5291. 'script' => [],
  5292. 'episode' => [],
  5293. 'answer' => $fullContent,
  5294. 'reasoning' => $fullReasoningContent,
  5295. 'usage' => $usage,
  5296. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5297. ];
  5298. return;
  5299. }
  5300. // 替换美术风格
  5301. if ($mappedArtStyle !== '') {
  5302. $script_arr['art_style'] = $mappedArtStyle;
  5303. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5304. }
  5305. if ($user_anime_name != '新剧本策划') {
  5306. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5307. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5308. // 确认对话名称唯一性
  5309. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5310. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5311. }
  5312. }else {
  5313. $anime_name = $user_anime_name;
  5314. }
  5315. $table_data = [
  5316. 'user_id' => $uid,
  5317. 'model' => $model,
  5318. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5319. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5320. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5321. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5322. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5323. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5324. 'art_style_type' => $input_art_style,
  5325. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5326. 'status' => '解析完成',
  5327. 'generate_status' => '待执行',
  5328. 'updated_at' => date('Y-m-d H:i:s')
  5329. ];
  5330. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5331. // 如果是修改集数,则将content内容更新(会改变原文)
  5332. if (isset($episode_count) && $episode_count > 0) {
  5333. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5334. $table_data['start_episode_sequence'] = 1;
  5335. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5336. }else {
  5337. // 如果需要生成原文内容,从script_arr中提取
  5338. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5339. $table_data['content'] = $script_arr['content'];
  5340. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5341. if (!$table_data['content']) {
  5342. yield [
  5343. 'type' => 'done',
  5344. 'script' => [],
  5345. 'episode' => [],
  5346. 'answer' => $fullContent,
  5347. 'reasoning' => $fullReasoningContent,
  5348. 'usage' => $usage,
  5349. 'error' => '未生成剧本内容,请调整提示词再试'
  5350. ];
  5351. return;
  5352. }
  5353. }
  5354. if (isset($table_data['content']) && $table_data['content']) {
  5355. $chapters = splitContent($table_data['content']);
  5356. $chapter_count = count($chapters);
  5357. if ($chapter_count > 0) {
  5358. $table_data['start_episode_sequence'] = 1;
  5359. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5360. }
  5361. }
  5362. }
  5363. $single_episode = [];
  5364. try {
  5365. DB::beginTransaction();
  5366. $now = date('Y-m-d H:i:s');
  5367. // 更新动漫大纲
  5368. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5369. if (!$boolen) {
  5370. dLog('deepseek')->info('对话修改失败', $table_data);
  5371. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5372. Utils::throwError('20003:对话修改失败');
  5373. }
  5374. // 保存对话记录
  5375. $records = [
  5376. [
  5377. 'uid' => $uid,
  5378. 'anime_id' => $anime_id,
  5379. 'sequence' => 0,
  5380. 'role' => 'user',
  5381. 'content' => $prompt,
  5382. 'created_at' => $now,
  5383. 'updated_at' => $now
  5384. ],
  5385. [
  5386. 'uid' => $uid,
  5387. 'anime_id' => $anime_id,
  5388. 'sequence' => 0,
  5389. 'role' => 'assistant',
  5390. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5391. 'content' => $fullContent,
  5392. 'created_at' => $now,
  5393. 'updated_at' => $now
  5394. ]
  5395. ];
  5396. // 保存对话记录
  5397. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5398. if (!$boolen3) {
  5399. Utils::throwError('20003:对话记录保存失败');
  5400. }
  5401. // 单剧集模式:生成并保存剧集信息
  5402. if ($is_single) {
  5403. $anime_name = getProp($anime, 'anime_name', '未命名');
  5404. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5405. if (empty($episode_arr['acts'])) {
  5406. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5407. }
  5408. $saveResult = $this->saveEpisodeVersionData(
  5409. $anime_id,
  5410. 1,
  5411. $episode_arr,
  5412. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5413. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5414. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5415. null,
  5416. null,
  5417. false,
  5418. $content,
  5419. $now
  5420. );
  5421. $single_episode = $saveResult['episode'];
  5422. $episode_id = $saveResult['episode_id'];
  5423. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5424. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5425. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5426. 'props' => json_encode($saveResult['merged_props'], 256),
  5427. 'updated_at' => $now
  5428. ]);
  5429. if ($boolen5 === false) {
  5430. Utils::throwError('20003:单剧集主表资源同步失败');
  5431. }
  5432. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5433. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5434. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5435. $episode_record_content = '确认分镜大纲';
  5436. if ($content !== '') {
  5437. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5438. }
  5439. $episode_records = [
  5440. [
  5441. 'uid' => $uid,
  5442. 'anime_id' => $anime_id,
  5443. 'role' => 'user',
  5444. 'content' => $episode_record_content,
  5445. 'sequence' => 1,
  5446. 'episode_id' => $episode_id,
  5447. 'created_at' => $now,
  5448. 'updated_at' => $now
  5449. ],
  5450. [
  5451. 'uid' => $uid,
  5452. 'anime_id' => $anime_id,
  5453. 'role' => 'assistant',
  5454. 'content' => $fullContent,
  5455. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5456. 'sequence' => 1,
  5457. 'episode_id' => $episode_id,
  5458. 'created_at' => $now,
  5459. 'updated_at' => $now
  5460. ]
  5461. ];
  5462. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5463. if (!$boolen4) {
  5464. Utils::throwError('20003:单剧集分镜记录保存失败');
  5465. }
  5466. }
  5467. }catch (\Exception $e) {
  5468. DB::rollBack();
  5469. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5470. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5471. yield [
  5472. 'type' => 'done',
  5473. 'answer' => $fullContent,
  5474. 'reasoning' => $fullReasoningContent,
  5475. 'usage' => $usage,
  5476. 'error' => $e->getMessage(),
  5477. ];
  5478. return;
  5479. }
  5480. DB::commit();
  5481. dLog('deepseek')->info('保存完毕');
  5482. if ($is_single && !empty($single_episode)) {
  5483. // $this->batchSetGlobalRoleImg([
  5484. // 'anime_id' => $anime_id,
  5485. // ]);
  5486. // $this->batchSetGlobalSceneImg([
  5487. // 'anime_id' => $anime_id,
  5488. // ]);
  5489. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5490. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5491. }
  5492. $table_data['anime_id'] = $anime_id;
  5493. $table_data['roles'] = json_decode($table_data['roles'], true);
  5494. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5495. unset($table_data['updated_at']);
  5496. unset($table_data['status']);
  5497. yield [
  5498. 'type' => 'done',
  5499. 'script' => $table_data,
  5500. 'episode' => $single_episode,
  5501. 'answer' => $fullContent,
  5502. 'reasoning' => $fullReasoningContent,
  5503. 'usage' => $usage
  5504. ];
  5505. }
  5506. public function chat($data) {
  5507. $uid = Site::getUid();
  5508. $anime_id = getProp($data, 'anime_id');
  5509. $file = getProp($data, 'file');
  5510. $content = getProp($data, 'content', '');
  5511. $bid = getProp($data, 'bid', 0);
  5512. $script_id = getProp($data, 'script_id', 0);
  5513. $episode_number = getProp($data, 'episode_number', 1);
  5514. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5515. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5516. if (!$anime) Utils::throwError('20003:该对话不存在!');
  5517. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  5518. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  5519. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  5520. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  5521. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  5522. $roles = is_array($roles) ? $roles : [];
  5523. $scenes = is_array($scenes) ? $scenes : [];
  5524. // 获取最后一集序号
  5525. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  5526. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  5527. // 转换主体列表和场景列表的格式
  5528. // 获取参考主体或场景
  5529. if ((int)$episode_number === 1) {
  5530. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  5531. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  5532. }else {
  5533. $prev_episode_number = $episode_number - 1;
  5534. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  5535. }
  5536. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  5537. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  5538. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  5539. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  5540. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5541. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5542. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5543. 中年女:邻居阿姨
  5544. 老年男:幽默大爷
  5545. 老年女:婆婆
  5546. 萌娃:奶气萌娃";
  5547. if ($roles_content) {
  5548. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  5549. 主体范围:\n {$roles_content}\n
  5550. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  5551. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5552. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5553. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5554. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5555. }else {
  5556. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5557. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5558. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5559. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5560. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5561. }
  5562. if ($scenes_content) {
  5563. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  5564. 场景范围:\n {$scenes_content}\n
  5565. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  5566. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5567. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5568. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5569. }else {
  5570. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5571. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5572. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5573. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5574. }
  5575. // 提取文件内容
  5576. if ($file) {
  5577. $uploaded_content = $this->extractFileContent($file);
  5578. if (!$uploaded_content) {
  5579. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5580. }
  5581. } elseif ($script_id) {
  5582. $uploaded_content = $this->getContentByScriptId($script_id);
  5583. if (!$uploaded_content) {
  5584. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5585. }
  5586. } elseif ($bid) {
  5587. $uploaded_content = $this->getContentByBid($bid);
  5588. if (!$uploaded_content) {
  5589. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5590. }
  5591. } elseif ($content) {
  5592. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  5593. }
  5594. // elseif ($prompt) {
  5595. // $uploaded_content = filterContent($prompt);
  5596. // }
  5597. else {
  5598. $uploaded_content = '';
  5599. }
  5600. $input_art_style = getProp($anime, 'art_style');
  5601. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5602. // 美术风格
  5603. if (!$mappedArtStyle) {
  5604. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5605. }else {
  5606. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5607. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5608. }else {
  5609. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5610. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5611. }
  5612. }
  5613. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5614. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5615. // 强制要求:
  5616. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5617. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5618. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5619. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  5620. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  5621. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  5622. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  5623. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  5624. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  5625. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  5626. // - 分镜要和场景列表、人物主体保持一致\n
  5627. // 普通要求:
  5628. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5629. // {$role_demo}
  5630. // {$scene_demo}
  5631. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5632. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5633. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5634. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5635. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5636. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5637. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5638. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5639. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5640. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5641. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5642. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5643. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5644. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5645. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5646. // 5.$mappedArtStyle_prompt\n\n
  5647. // 示例格式:\n
  5648. // 第1集:隐形的守护者
  5649. // ###故事梗概
  5650. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5651. // ###美术风格
  5652. // 基础画风风格词:韩漫二次元
  5653. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5654. // ###主体列表
  5655. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5656. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5657. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5658. // ###场景列表
  5659. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5660. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5661. // 无人物。}
  5662. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5663. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5664. // 无人物。}
  5665. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5666. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5667. // 无人物。}
  5668. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5669. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5670. // 无人物。}
  5671. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5672. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5673. // 无人物。}
  5674. // ###分镜剧本
  5675. // ##第1幕:徐家老旧厨房 白天 室内
  5676. // 分镜1
  5677. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5678. // 场景:徐家老旧厨房
  5679. // 构图设计:全景,低角度仰视
  5680. // 运镜调度:手持拍摄
  5681. // 配音角色:旁白
  5682. // 出镜角色:许芸-校服装、徐母
  5683. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5684. // 画面类型:普通画面
  5685. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5686. // 分镜2
  5687. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5688. // 场景:徐家老旧厨房
  5689. // 构图设计:近景,徐母面部特写
  5690. // 运镜调度:固定镜头
  5691. // 配音角色:徐母
  5692. // 出镜角色:徐母
  5693. // 台词内容:问我夜不归宿死哪儿去了。
  5694. // 画面类型:对口型
  5695. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5696. // ##第2幕:徐家简陋客厅 黄昏 室内
  5697. // 分镜3
  5698. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5699. // 场景:徐家简陋客厅
  5700. // 构图设计:全景,景深虚化
  5701. // 运镜调度:固定镜头
  5702. // 配音角色:旁白
  5703. // 出镜角色:无
  5704. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5705. // 画面类型:普通画面
  5706. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5707. // 分镜4
  5708. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5709. // 场景:徐家简陋客厅
  5710. // 构图设计:特写,火车票
  5711. // 运镜调度:固定镜头
  5712. // 配音角色:旁白
  5713. // 出镜角色:无
  5714. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5715. // 画面类型:普通画面
  5716. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5717. // \n\n";
  5718. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  5719. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  5720. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  5721. 普通要求:
  5722. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5723. {$role_demo}
  5724. {$scene_demo}
  5725. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5726. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5727. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5728. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5729. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5730. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5731. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5732. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5733. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5734. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5735. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5736. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5737. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5738. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5739. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5740. 5.$mappedArtStyle_prompt
  5741. 6.《情绪-视听语言映射表》:
  5742. 6.1 场景空间与时间心理学 (Scene & Temporality)
  5743. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5744. -----|---------|------------|----------------
  5745. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  5746. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  5747. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  5748. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  5749. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  5750. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5751. -----|---------|------------|----------------
  5752. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  5753. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  5754. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  5755. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  5756. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  5757. --------|---------|--------------|-------------
  5758. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  5759. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  5760. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  5761. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  5762. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5763. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5764. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5765. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5766. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  5767. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  5768. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5769. -----|---------|------------|------------
  5770. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5771. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5772. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5773. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5774. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5775. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5776. --------|---------|--------------|----------
  5777. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5778. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5779. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5780. 6.6 声音设计与潜意识影响 (Soundscape)
  5781. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5782. -----|---------|------------|------------------
  5783. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5784. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5785. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5786. 理论基石:
  5787. - The Five C's of Cinematography by Joseph V. Mascelli
  5788. - Film Art: An Introduction by David Bordwell
  5789. - Sight, Sound, Motion by Herbert Zettl
  5790. - Notes on the Cinematograph by Robert Bresson
  5791. \n\n
  5792. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5793. 示例格式:\n
  5794. 第1集:隐形的守护者
  5795. ###故事梗概
  5796. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5797. ###美术风格
  5798. 基础画风风格词:韩漫二次元
  5799. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5800. ###主体列表
  5801. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5802. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5803. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5804. ###场景列表
  5805. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5806. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5807. 无人物。}
  5808. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5809. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5810. 无人物。}
  5811. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5812. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5813. 无人物。}
  5814. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5815. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5816. 无人物。}
  5817. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5818. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5819. 无人物。}
  5820. ###分镜剧本
  5821. ##第1幕:徐家老旧厨房 白天 室内
  5822. 分镜1
  5823. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5824. 场景:徐家老旧厨房
  5825. 构图设计:全景,低角度仰视
  5826. 运镜调度:手持拍摄
  5827. 配音角色:旁白
  5828. 出镜角色:许芸-校服装、徐母
  5829. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5830. 画面类型:普通画面
  5831. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5832. 分镜2
  5833. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5834. 场景:徐家老旧厨房
  5835. 构图设计:近景,徐母面部特写
  5836. 运镜调度:固定镜头
  5837. 配音角色:徐母
  5838. 出镜角色:徐母
  5839. 台词内容:问我夜不归宿死哪儿去了。
  5840. 画面类型:对口型
  5841. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5842. ##第2幕:徐家简陋客厅 黄昏 室内
  5843. 分镜3
  5844. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5845. 场景:徐家简陋客厅
  5846. 构图设计:全景,景深虚化
  5847. 运镜调度:固定镜头
  5848. 配音角色:旁白
  5849. 出镜角色:无
  5850. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5851. 画面类型:普通画面
  5852. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5853. 分镜4
  5854. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5855. 场景:徐家简陋客厅
  5856. 构图设计:特写,火车票
  5857. 运镜调度:固定镜头
  5858. 配音角色:旁白
  5859. 出镜角色:无
  5860. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5861. 画面类型:普通画面
  5862. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5863. \n\n";
  5864. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5865. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5866. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5867. $prompt = $origin_prompt;
  5868. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5869. // 获取章节内容
  5870. $full_content = getProp($anime, 'content');
  5871. if ($uploaded_content) {
  5872. $full_content = $uploaded_content;
  5873. }
  5874. // 根据章节内容拆分章节
  5875. $chapters = splitContent($full_content);
  5876. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5877. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5878. $messages = [];
  5879. if ($prompt == '确认分镜大纲') {
  5880. // 暂时保留
  5881. $content = $chapter_content;
  5882. if ($is_single) $content = $full_content; // 单剧集使用全文
  5883. if (!$content) {
  5884. Utils::throwError('20003:章节内容无法获取,请确认');
  5885. }
  5886. $question = $is_single
  5887. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5888. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5889. // 构建消息
  5890. $messages[] =
  5891. [
  5892. 'role' => 'user',
  5893. 'content' => $question
  5894. ];
  5895. }else if ($prompt == '继续策划下一集') {
  5896. if ($is_single) {
  5897. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5898. }
  5899. $content = $chapter_content;
  5900. if (!$content) {
  5901. Utils::throwError('20003:章节内容无法获取,请确认');
  5902. }
  5903. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5904. // 获取上一集最后记录
  5905. $prev_sequence = $episode_number - 1;
  5906. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5907. // 构建消息
  5908. $messages[] =
  5909. [
  5910. 'role' => 'user',
  5911. 'content' => $question
  5912. ];
  5913. }else {
  5914. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5915. if (!$content) {
  5916. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5917. }
  5918. if (!$content) {
  5919. Utils::throwError('20003:章节内容无法获取,请确认');
  5920. }
  5921. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5922. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5923. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5924. if ($origin_prompt) {
  5925. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5926. }
  5927. $messages[] =
  5928. [
  5929. 'role' => 'user',
  5930. 'content' => $question
  5931. ];
  5932. }
  5933. // 处理文本模型
  5934. $model = getProp($data, 'model');
  5935. if (!$model) {
  5936. // 用户没有输入,从anime表获取
  5937. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5938. $model = getProp($anime, 'model');
  5939. if (!$model) {
  5940. // anime表也没有,使用默认值
  5941. $model = 'doubao-seed-2-0-mini-260215';
  5942. }
  5943. }
  5944. // 验证模型是否在可用模型表中
  5945. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5946. $model = 'doubao-seed-2-0-mini-260215';
  5947. }
  5948. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5949. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5950. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5951. if ($model === 'deepseek-chat') {
  5952. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5953. $model = 'deepseek-v4-flash';
  5954. $thinkingMode = 'disabled';
  5955. } elseif ($model === 'deepseek-reasoner') {
  5956. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5957. $model = 'deepseek-v4-flash';
  5958. $thinkingMode = 'enabled';
  5959. }
  5960. $post_data = [
  5961. 'model' => $model,
  5962. 'messages' => $messages,
  5963. // 'max_tokens' => 8192,
  5964. 'temperature' => 0.2,
  5965. 'frequency_penalty' => 0,
  5966. 'presence_penalty' => 0,
  5967. 'response_format' => ['type' => 'text'],
  5968. 'thinking' => ['type' => $thinkingMode],
  5969. 'stream' => true // 启用流式输出
  5970. ];
  5971. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5972. // 根据模型类型选择调用方法
  5973. $fullContent = '';
  5974. $fullReasoningContent = '';
  5975. $usage = [];
  5976. try {
  5977. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5978. // DeepSeek 官方模型使用 DeepSeek API
  5979. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5980. } else if (in_array($model, $this->gpt_text_models)) {
  5981. // GPT-5.4 模型使用 TokenRouter API
  5982. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5983. } else if (in_array($model, $this->gemini_text_models)) {
  5984. // Gemini 模型使用 Gemini API
  5985. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5986. } else {
  5987. // 其他模型使用火山引擎API
  5988. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5989. }
  5990. // 验证返回值类型
  5991. if (!is_iterable($streamGenerator)) {
  5992. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5993. dLog('deepseek')->error('chat流式生成器无效', [
  5994. 'generator_type' => $errorType,
  5995. 'model' => $model,
  5996. 'anime_id' => $anime_id,
  5997. 'episode_number' => $episode_number
  5998. ]);
  5999. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6000. 'type' => $errorType,
  6001. 'model' => $model
  6002. ]);
  6003. yield [
  6004. 'type' => 'error',
  6005. 'episode' => [],
  6006. 'answer' => '',
  6007. 'reasoning' => '',
  6008. 'usage' => [],
  6009. 'error' => '接口返回数据异常,请重新请求'
  6010. ];
  6011. return;
  6012. }
  6013. // 处理流式输出
  6014. foreach ($streamGenerator as $chunk) {
  6015. if (isset($chunk['type'])) {
  6016. if ($chunk['type'] === 'done') {
  6017. // 最终结果
  6018. $fullContent = $chunk['full_content'];
  6019. $fullReasoningContent = $chunk['full_reasoning'];
  6020. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6021. } else {
  6022. // 逐块yield数据
  6023. yield $chunk;
  6024. }
  6025. }
  6026. }
  6027. } catch (\Exception $e) {
  6028. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6029. 'model' => $model,
  6030. 'anime_id' => $anime_id,
  6031. 'episode_number' => $episode_number,
  6032. 'trace' => $e->getTraceAsString()
  6033. ]);
  6034. logDB('deepseek', 'error', 'chat流式处理失败', [
  6035. 'error' => $e->getMessage(),
  6036. 'model' => $model
  6037. ]);
  6038. yield [
  6039. 'type' => 'error',
  6040. 'episode' => [],
  6041. 'answer' => '',
  6042. 'reasoning' => '',
  6043. 'usage' => [],
  6044. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6045. ];
  6046. return;
  6047. }
  6048. dLog('deepseek')->info('完整内容: '.$fullContent);
  6049. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6050. // 处理完整内容并返回最终结果
  6051. $episode_arr = handleEpisodeContent($fullContent);
  6052. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6053. if (empty($episode_arr['acts'])) {
  6054. // 未生成剧本相关内容,保存对话记录并返回提示
  6055. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6056. try {
  6057. $now = date('Y-m-d H:i:s');
  6058. // 保存对话记录
  6059. $records = [
  6060. [
  6061. 'uid' => $uid,
  6062. 'anime_id' => $anime_id,
  6063. 'sequence' => $episode_number,
  6064. 'role' => 'user',
  6065. 'content' => $prompt,
  6066. 'created_at' => $now,
  6067. 'updated_at' => $now
  6068. ],
  6069. [
  6070. 'uid' => $uid,
  6071. 'anime_id' => $anime_id,
  6072. 'sequence' => $episode_number,
  6073. 'role' => 'assistant',
  6074. 'content' => $fullContent,
  6075. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6076. 'created_at' => $now,
  6077. 'updated_at' => $now
  6078. ]
  6079. ];
  6080. DB::table('mp_anime_records')->insert($records);
  6081. } catch (\Exception $e) {
  6082. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6083. }
  6084. yield [
  6085. 'type' => 'done',
  6086. 'episode' => [],
  6087. 'answer' => $fullContent,
  6088. 'reasoning' => $fullReasoningContent,
  6089. 'usage' => $usage,
  6090. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6091. ];
  6092. return;
  6093. }
  6094. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6095. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6096. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6097. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6098. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6099. $existing_props = is_array($existing_props) ? $existing_props : [];
  6100. $now = date('Y-m-d H:i:s');
  6101. try {
  6102. DB::beginTransaction();
  6103. $saveResult = $this->saveEpisodeVersionData(
  6104. $anime_id,
  6105. $episode_number,
  6106. $episode_arr,
  6107. $existing_roles,
  6108. $existing_scenes,
  6109. $existing_props,
  6110. $current_episode,
  6111. $base_episode,
  6112. $is_regenerate_version,
  6113. $content,
  6114. $now
  6115. );
  6116. $episode = $saveResult['episode'];
  6117. $episode_id = $saveResult['episode_id'];
  6118. $merged_roles = $saveResult['merged_roles'];
  6119. $merged_scenes = $saveResult['merged_scenes'];
  6120. $merged_props = $saveResult['merged_props'];
  6121. $record_content = $origin_prompt;
  6122. if ($uploaded_content !== '') {
  6123. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6124. }
  6125. $records = [
  6126. [
  6127. 'uid' => $uid,
  6128. 'anime_id' => $anime_id,
  6129. 'role' => 'user',
  6130. 'content' => $record_content,
  6131. 'sequence' => $episode_number,
  6132. 'episode_id' => $episode_id,
  6133. 'created_at' => $now,
  6134. 'updated_at' => $now
  6135. ],
  6136. [
  6137. 'uid' => $uid,
  6138. 'anime_id' => $anime_id,
  6139. 'role' => 'assistant',
  6140. 'content' => $fullContent,
  6141. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6142. 'sequence' => $episode_number,
  6143. 'episode_id' => $episode_id,
  6144. 'created_at' => $now,
  6145. 'updated_at' => $now
  6146. ]
  6147. ];
  6148. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6149. if (!$boolen4) {
  6150. Utils::throwError('20003:对话记录保存失败');
  6151. }
  6152. // 保存模型和内容到anime表
  6153. $update_anime_data = [
  6154. 'model' => $model,
  6155. 'updated_at' => $now
  6156. ];
  6157. if ($uploaded_content) {
  6158. $update_anime_data['content'] = $uploaded_content;
  6159. }
  6160. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6161. }catch (\Exception $e) {
  6162. DB::rollBack();
  6163. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6164. yield [
  6165. 'type' => 'done',
  6166. 'answer' => $fullContent,
  6167. 'reasoning' => $fullReasoningContent,
  6168. 'usage' => $usage,
  6169. 'error' => $e->getMessage(),
  6170. ];
  6171. return;
  6172. }
  6173. DB::commit();
  6174. if ($is_global_generate_pics) {
  6175. // // 批量生成全局角色图片
  6176. // $this->batchSetGlobalRoleImg([
  6177. // 'anime_id' => $anime_id,
  6178. // ], true);
  6179. // // 批量生成全局场景图片
  6180. // $this->batchSetGlobalSceneImg([
  6181. // 'anime_id' => $anime_id,
  6182. // ], true);
  6183. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6184. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6185. }
  6186. $episode['episode_id'] = $episode_id;
  6187. $episode['roles'] = $merged_roles;
  6188. $episode['scenes'] = $merged_scenes;
  6189. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6190. yield [
  6191. 'type' => 'done',
  6192. 'episode' => $episode,
  6193. 'answer' => $fullContent,
  6194. 'reasoning' => $fullReasoningContent,
  6195. 'usage' => $usage
  6196. ];
  6197. }
  6198. public function addChatForAce($data) {
  6199. $uid = Site::getUid();
  6200. $anime_id = getProp($data, 'anime_id');
  6201. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6202. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6203. if (!$anime) Utils::throwError('20003:对话不存在');
  6204. $file = getProp($data, 'file');
  6205. $content = getProp($data, 'content', '');
  6206. $bid = getProp($data, 'bid', 0);
  6207. $script_id = getProp($data, 'script_id', 0);
  6208. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6209. $prompt = getProp($data, 'prompt');
  6210. $is_multi = getProp($anime, 'is_multi');
  6211. $is_single = (int)$is_multi !== 1;
  6212. $extra_products = getProp($data, 'products', []);
  6213. if (!$extra_products) {
  6214. $extra_products = getProp($anime, 'extra_products');
  6215. if ($extra_products) {
  6216. $extra_products = json_decode($extra_products, true);
  6217. }else {
  6218. $extra_products = [];
  6219. }
  6220. }else {
  6221. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6222. }
  6223. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6224. $anime_script_id = getProp($anime, 'script_id');
  6225. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6226. $cpid = Site::getCpid();
  6227. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6228. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6229. ->where('mapping.script_id', $anime_script_id)
  6230. ->where('product.cpid', $cpid)
  6231. ->where('product.is_deleted', 0);
  6232. $mappings = $script_products_mappings->select(
  6233. 'mapping.product_id',
  6234. 'mapping.episode_number',
  6235. 'product.product_name',
  6236. 'product.type',
  6237. 'product.product',
  6238. 'product.pic_prompt',
  6239. 'product.url',
  6240. 'product.pic_task_id',
  6241. 'product.pic_task_status',
  6242. 'product.three_view_image_url'
  6243. )
  6244. ->get();
  6245. // 按 product_id 分组,合并 episode_number
  6246. $productMap = [];
  6247. foreach ($mappings as $item) {
  6248. $product_id = $item->product_id;
  6249. $product_name = $item->product_name;
  6250. // 处理product_name两边的符号
  6251. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6252. if (!isset($productMap[$product_id])) {
  6253. $productMap[$product_id] = [
  6254. 'product_id' => $product_id,
  6255. 'product_name' => $product_name,
  6256. 'type' => (int)$item->type,
  6257. 'product' => (int)$item->product,
  6258. 'pic_prompt' => $item->pic_prompt,
  6259. 'url' => $item->url,
  6260. 'pic_task_id' => $item->pic_task_id,
  6261. 'pic_task_status' => $item->pic_task_status,
  6262. 'episode_numbers' => [],
  6263. ];
  6264. }
  6265. // 添加 episode_number(去重)
  6266. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6267. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6268. }
  6269. }
  6270. // 将查询到的剧本资产合并到extra_products中
  6271. // 先构建extra_products的索引(以product_id为key,用于去重)
  6272. $extraProductsMap = [];
  6273. foreach ($extra_products as $item) {
  6274. $key = getProp($item, 'product_id');
  6275. if ($key) {
  6276. $extraProductsMap[$key] = $item;
  6277. }
  6278. }
  6279. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6280. foreach ($productMap as $product) {
  6281. $product_id = $product['product_id'];
  6282. // 如果不存在则添加(不带episode_number信息)
  6283. if (!isset($extraProductsMap[$product_id])) {
  6284. $extraProductsMap[$product_id] = [
  6285. 'product_id' => $product['product_id'],
  6286. 'product_name' => $product['product_name'],
  6287. 'type' => $product['type'],
  6288. 'product' => $product['product'],
  6289. 'pic_prompt' => $product['pic_prompt'],
  6290. 'url' => $product['url'],
  6291. 'pic_task_id' => $product['pic_task_id'],
  6292. 'pic_task_status' => $product['pic_task_status'],
  6293. ];
  6294. }
  6295. }
  6296. // 重新赋值给extra_products
  6297. $extra_products = array_values($extraProductsMap);
  6298. }
  6299. $user_anime_name = getProp($anime, 'anime_name');
  6300. // 处理提示词
  6301. if ($prompt && $extra_products) {
  6302. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6303. foreach($extra_products as $item) {
  6304. $product_name = getProp($item, 'product_name');
  6305. if ($product_name) {
  6306. // 替换 {product_name} 为 product_name
  6307. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6308. }
  6309. }
  6310. }
  6311. // 处理文本模型
  6312. $model = getProp($data, 'model');
  6313. if (!$model) {
  6314. // 用户没有输入,从anime表获取
  6315. $model = getProp($anime, 'model');
  6316. if (!$model) {
  6317. // anime表也没有,使用默认值
  6318. $model = 'deepseek-v4-pro';
  6319. }
  6320. }
  6321. // 验证模型是否在可用模型表中
  6322. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6323. $model = 'deepseek-v4-pro';
  6324. }
  6325. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6326. if ($prompt) {
  6327. $question .= "本次修改要求如下:\n{$prompt}";
  6328. }
  6329. // if (!$file && !$content && !$bid) {
  6330. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6331. // }
  6332. // 提取文件内容
  6333. if ($file) {
  6334. $content = $this->extractFileContent($file);
  6335. if (!$content) {
  6336. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6337. }
  6338. } elseif ($script_id) {
  6339. $content = $this->getContentByScriptId($script_id);
  6340. if (!$content) {
  6341. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6342. }
  6343. } elseif ($bid) {
  6344. $content = $this->getContentByBid($bid);
  6345. if (!$content) {
  6346. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6347. }
  6348. } elseif ($content) {
  6349. $content = filterContent($content);
  6350. } else {
  6351. $content = getProp($anime, 'content');
  6352. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6353. $need_generate_content = true;
  6354. }
  6355. }
  6356. // 美术风格
  6357. $input_art_style = getProp($data, 'art_style');
  6358. if (!$input_art_style) {
  6359. $mappedArtStyle = getProp($anime, 'art_style');
  6360. }else {
  6361. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6362. }
  6363. // 判断是否需要生成原文内容
  6364. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6365. // 如果需要生成原文内容,添加额外的要求
  6366. $content_generation_requirement = $need_generate_content
  6367. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6368. : "";
  6369. // 美术风格
  6370. if (!$mappedArtStyle) {
  6371. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6372. }else {
  6373. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6374. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6375. }else {
  6376. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6377. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6378. }
  6379. }
  6380. // 构建主体、场景和道具提示词
  6381. $extra_role_prompt = "\n";
  6382. $extra_scene_prompt = "\n";
  6383. $extra_prop_prompt = "\n";
  6384. $ref_products = []; // 参考资产
  6385. if ($extra_products) {
  6386. foreach($extra_products as $item) {
  6387. $product = getProp($item, 'product');
  6388. $product_name = getProp($item, 'product_name');
  6389. if ($product_name == '旁白') continue;
  6390. $ref_products[$product_name] = $item;
  6391. $pic_prompt = getProp($item, 'pic_prompt');
  6392. if ((int)$product === 1) {
  6393. // 拼接角色信息
  6394. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6395. } elseif ((int)$product === 2) {
  6396. // 拼接场景信息
  6397. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6398. } elseif ((int)$product === 3) {
  6399. // 拼接道具信息
  6400. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6401. }
  6402. }
  6403. // 优化提示词,融入剧本
  6404. if (!empty(trim($extra_role_prompt))) {
  6405. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6406. }
  6407. if (!empty(trim($extra_scene_prompt))) {
  6408. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6409. }
  6410. if (!empty(trim($extra_prop_prompt))) {
  6411. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6412. }
  6413. }
  6414. if ($anime_script_id && $is_single) {
  6415. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6416. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6417. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6418. }else {
  6419. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6420. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6421. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6422. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6423. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6424. {$extra_role_prompt}";
  6425. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6426. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6427. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6428. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6429. {$extra_scene_prompt}";
  6430. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6431. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6432. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6433. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6434. {$extra_prop_prompt}";
  6435. }
  6436. $systemPrompt = $is_single
  6437. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6438. 强制要求:
  6439. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6440. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6441. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6442. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6443. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6444. 普通要求:
  6445. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6446. $role_demo
  6447. $scene_demo
  6448. $prop_demo
  6449. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6450. 5.1片段分割逻辑(优先级从高到低):
  6451. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6452. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6453. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6454. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6455. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6456. - 片段数量格式为: 片段数量:8
  6457. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6458. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6459. 5.3分镜结构:每个分镜包含以下字段:
  6460. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6461. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6462. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6463. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6464. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6465. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6466. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6467. - 运镜:场景+画面描述+运镜
  6468. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6469. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6470. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6471. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6472. 6.{$mappedArtStyle_prompt}\n\n
  6473. 示例如下:\n
  6474. ###剧本名:西昆仑
  6475. ###故事梗概
  6476. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6477. ###剧本亮点
  6478. 亮点1:绝境奇药,生死一线
  6479. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6480. 亮点2:结拜兄妹,化解尴尬
  6481. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6482. 亮点3:纤发夺命,情愫暗涌
  6483. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6484. ###人物关系
  6485. 阿雪与梁萧之间存在兄妹之情。
  6486. ###核心矛盾
  6487. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6488. ###主体列表
  6489. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6490. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6491. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6492. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6493. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6494. 全景,正面拍摄,青年女性,亚洲人。
  6495. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6496. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6497. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6498. ###美术风格
  6499. 基础画风风格词:厚涂古风
  6500. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6501. ###场景列表
  6502. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6503. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6504. 无人物。}
  6505. ###分段剧本
  6506. 片段数量:8
  6507. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6508. ##片段1
  6509. 时长:12s
  6510. 分镜1
  6511. 出场角色:刀疤脸
  6512. 场景:边境小镇街道
  6513. 出场道具:酒杯-高脚杯
  6514. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6515. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6516. 配音台词:
  6517. 背景音效:
  6518. 分镜2
  6519. 出场角色:刀疤脸
  6520. 场景:悦来酒馆
  6521. 出场道具:酒杯-高脚杯
  6522. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6523. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6524. 配音台词:
  6525. 背景音效:
  6526. 分镜3
  6527. 出场角色:刀疤脸
  6528. 场景:悦来酒馆
  6529. 出场道具:酒杯-高脚杯
  6530. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6531. 运镜:从中景推向令牌特写。
  6532. 配音台词:
  6533. 背景音效:
  6534. 分镜4
  6535. 出场角色:刀疤脸
  6536. 场景:悦来酒馆
  6537. 出场道具:酒杯-高脚杯
  6538. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6539. 运镜:极速推向酒水溅起的瞬间。
  6540. 配音台词:
  6541. 背景音效:
  6542. 分镜5
  6543. 出场角色:刀疤脸
  6544. 场景:悦来酒馆
  6545. 出场道具:酒杯-高脚杯
  6546. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6547. 运镜:固定机位,利用倾斜构图制造压迫感。
  6548. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6549. 背景音效:
  6550. \n\n"
  6551. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6552. 强制要求:\n
  6553. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6554. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6555. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6556. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6557. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6558. 普通要求:\n
  6559. 1.剧本名(必须生成)必须与文档内容高度相关
  6560. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6561. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6562. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6563. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6564. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6565. {$extra_role_prompt}
  6566. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6567. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6568. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6569. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6570. {$extra_scene_prompt}
  6571. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6572. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6573. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6574. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6575. {$extra_prop_prompt}
  6576. 5.{$mappedArtStyle_prompt}\n\n
  6577. 示例如下:\n
  6578. ###剧本名:西昆仑
  6579. ###故事梗概
  6580. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6581. ###剧本亮点
  6582. 亮点1:绝境奇药,生死一线
  6583. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6584. 亮点2:结拜兄妹,化解尴尬
  6585. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6586. 亮点3:纤发夺命,情愫暗涌
  6587. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6588. ###人物关系
  6589. 阿雪与梁萧之间存在兄妹之情。
  6590. ###核心矛盾
  6591. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6592. ###主体列表
  6593. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6594. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6595. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6596. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6597. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6598. 全景,正面拍摄,青年女性,亚洲人。
  6599. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6600. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6601. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6602. ###美术风格
  6603. 基础画风风格词:厚涂古风
  6604. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6605. ###场景列表
  6606. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6607. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6608. 无人物。}
  6609. ###道具列表
  6610. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  6611. // 构建消息
  6612. $messages = [
  6613. [
  6614. 'role' => 'system',
  6615. 'content' => $systemPrompt
  6616. ],
  6617. [
  6618. 'role' => 'user',
  6619. 'content' => "以下是文档内容:
  6620. {$content}
  6621. 用户问题:
  6622. {$question}"
  6623. ]
  6624. ];
  6625. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6626. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6627. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6628. if ($model === 'deepseek-chat') {
  6629. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6630. $model = 'deepseek-v4-flash';
  6631. $thinkingMode = 'disabled';
  6632. } elseif ($model === 'deepseek-reasoner') {
  6633. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6634. $model = 'deepseek-v4-flash';
  6635. $thinkingMode = 'enabled';
  6636. }
  6637. $post_data = [
  6638. 'model' => $model,
  6639. 'messages' => $messages,
  6640. // 'max_tokens' => 8192,
  6641. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6642. 'frequency_penalty' => 0,
  6643. 'presence_penalty' => 0,
  6644. 'response_format' => ['type' => 'text'],
  6645. 'thinking' => ['type'=>$thinkingMode],
  6646. 'stream' => true // 启用流式输出
  6647. ];
  6648. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6649. // 根据模型类型选择调用方法
  6650. $fullContent = '';
  6651. $fullReasoningContent = '';
  6652. $usage = [];
  6653. try {
  6654. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6655. // DeepSeek 官方模型使用 DeepSeek API
  6656. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6657. } else if (in_array($model, $this->gpt_text_models)) {
  6658. // GPT-5.4 模型使用 TokenRouter API
  6659. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6660. } else if (in_array($model, $this->gemini_text_models)) {
  6661. // Gemini 模型使用 Gemini API
  6662. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6663. } else {
  6664. // 其他模型使用火山引擎API
  6665. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6666. }
  6667. // 验证返回值类型
  6668. if (!is_iterable($streamGenerator)) {
  6669. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6670. dLog('deepseek')->error('addChat流式生成器无效', [
  6671. 'generator_type' => $errorType,
  6672. 'model' => $model,
  6673. 'anime_id' => $anime_id
  6674. ]);
  6675. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6676. 'type' => $errorType,
  6677. 'model' => $model
  6678. ]);
  6679. yield [
  6680. 'type' => 'error',
  6681. 'script' => [],
  6682. 'episode' => [],
  6683. 'answer' => '',
  6684. 'reasoning' => '',
  6685. 'usage' => [],
  6686. 'error' => '接口返回数据异常,请重新请求'
  6687. ];
  6688. return;
  6689. }
  6690. // 处理流式输出
  6691. foreach ($streamGenerator as $chunk) {
  6692. if (isset($chunk['type'])) {
  6693. if ($chunk['type'] === 'done') {
  6694. // 最终结果
  6695. $fullContent = $chunk['full_content'];
  6696. $fullReasoningContent = $chunk['full_reasoning'];
  6697. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6698. } else {
  6699. // 逐块yield数据
  6700. yield $chunk;
  6701. }
  6702. }
  6703. }
  6704. } catch (\Exception $e) {
  6705. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6706. 'model' => $model,
  6707. 'anime_id' => $anime_id,
  6708. 'trace' => $e->getTraceAsString()
  6709. ]);
  6710. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6711. 'error' => $e->getMessage(),
  6712. 'model' => $model
  6713. ]);
  6714. yield [
  6715. 'type' => 'error',
  6716. 'script' => [],
  6717. 'episode' => [],
  6718. 'answer' => '',
  6719. 'reasoning' => '',
  6720. 'usage' => [],
  6721. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6722. ];
  6723. return;
  6724. }
  6725. dLog('deepseek')->info('完整内容: '.$fullContent);
  6726. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6727. // 处理完整内容并返回最终结果
  6728. $script_arr = [];
  6729. if ($fullContent) {
  6730. $script_arr = handleScriptContentForAce($fullContent);
  6731. dLog('deepseek')->info('解析内容', $script_arr);
  6732. logDB('deepseek', 'info', '解析内容', $script_arr);
  6733. }
  6734. if (empty($script_arr['roles'])) {
  6735. // 未生成剧本相关内容,保存对话记录并返回提示
  6736. dLog('deepseek')->info('未生成剧本相关的内容');
  6737. try {
  6738. DB::beginTransaction();
  6739. $now = date('Y-m-d H:i:s');
  6740. // 保存对话记录
  6741. $records = [
  6742. [
  6743. 'uid' => $uid,
  6744. 'anime_id' => $anime_id,
  6745. 'sequence' => 0,
  6746. 'role' => 'user',
  6747. 'content' => $prompt,
  6748. 'created_at' => $now,
  6749. 'updated_at' => $now
  6750. ],
  6751. [
  6752. 'uid' => $uid,
  6753. 'anime_id' => $anime_id,
  6754. 'sequence' => 0,
  6755. 'role' => 'assistant',
  6756. // 'content' => $fullContent,
  6757. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6758. 'created_at' => $now,
  6759. 'updated_at' => $now
  6760. ]
  6761. ];
  6762. DB::table('mp_anime_records')->insert($records);
  6763. DB::commit();
  6764. } catch (\Exception $e) {
  6765. DB::rollBack();
  6766. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6767. }
  6768. yield [
  6769. 'type' => 'done',
  6770. 'script' => [],
  6771. 'episode' => [],
  6772. 'answer' => $fullContent,
  6773. 'reasoning' => $fullReasoningContent,
  6774. 'usage' => $usage,
  6775. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6776. ];
  6777. return;
  6778. }
  6779. // 如果需要生成原文内容,从script_arr中提取
  6780. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6781. $content = $script_arr['content'];
  6782. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6783. if (!$content) {
  6784. yield [
  6785. 'type' => 'done',
  6786. 'script' => [],
  6787. 'episode' => [],
  6788. 'answer' => $fullContent,
  6789. 'reasoning' => $fullReasoningContent,
  6790. 'usage' => $usage,
  6791. 'error' => '未生成剧本内容,请调整提示词再试'
  6792. ];
  6793. return;
  6794. }
  6795. }
  6796. // 替换美术风格
  6797. if ($mappedArtStyle !== '') {
  6798. $script_arr['art_style'] = $mappedArtStyle;
  6799. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6800. }
  6801. // 新建动漫
  6802. if ($user_anime_name == '新剧本策划') {
  6803. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6804. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6805. // if (!$anime_name) {
  6806. // // 未识别到剧本名,保存对话记录并返回提示
  6807. // dLog('deepseek')->info('未能识别到剧本名称');
  6808. // try {
  6809. // DB::beginTransaction();
  6810. // $now = date('Y-m-d H:i:s');
  6811. // // 保存对话记录
  6812. // $records = [
  6813. // [
  6814. // 'uid' => $uid,
  6815. // 'anime_id' => $anime_id,
  6816. // 'sequence' => 0,
  6817. // 'role' => 'user',
  6818. // 'content' => $prompt,
  6819. // 'created_at' => $now,
  6820. // 'updated_at' => $now
  6821. // ],
  6822. // [
  6823. // 'uid' => $uid,
  6824. // 'anime_id' => $anime_id,
  6825. // 'sequence' => 0,
  6826. // 'role' => 'assistant',
  6827. // 'content' => '未能生成剧本名称,请重试',
  6828. // 'created_at' => $now,
  6829. // 'updated_at' => $now
  6830. // ]
  6831. // ];
  6832. // DB::table('mp_anime_records')->insert($records);
  6833. // DB::commit();
  6834. // } catch (\Exception $e) {
  6835. // DB::rollBack();
  6836. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6837. // }
  6838. // yield [
  6839. // 'type' => 'done',
  6840. // 'script' => [],
  6841. // 'episode' => [],
  6842. // 'answer' => $fullContent,
  6843. // 'reasoning' => $fullReasoningContent,
  6844. // 'usage' => $usage,
  6845. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6846. // ];
  6847. // return;
  6848. // }
  6849. // 确认对话名称唯一性
  6850. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6851. $anime_name = $anime_name . '_' . date('YmdHis');
  6852. }
  6853. }else {
  6854. $anime_name = $user_anime_name;
  6855. }
  6856. $table_data = [
  6857. 'user_id' => $uid,
  6858. 'anime_name' => $anime_name,
  6859. 'model' => $model,
  6860. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6861. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6862. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6863. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6864. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6865. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6866. 'art_style_type' => $input_art_style,
  6867. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6868. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6869. 'status' => '解析完成',
  6870. 'content' => $content,
  6871. 'is_multi' => $is_multi,
  6872. 'ace_mode' => $ace_mode,
  6873. 'generate_status' => '待执行',
  6874. 'updated_at' => date('Y-m-d H:i:s')
  6875. ];
  6876. if ($table_data['content']) {
  6877. $chapters = splitContent($table_data['content']);
  6878. $chapter_count = count($chapters);
  6879. if ($chapter_count > 0) {
  6880. $table_data['start_episode_sequence'] = 1;
  6881. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6882. }
  6883. }
  6884. if ($extra_products) {
  6885. $table_data['extra_products'] = json_encode($extra_products, 256);
  6886. }
  6887. // 如果有剧本ID则进行绑定
  6888. if ($script_id) {
  6889. $table_data['script_id'] = $script_id;
  6890. }
  6891. $single_episode = [];
  6892. try {
  6893. DB::beginTransaction();
  6894. $now = date('Y-m-d H:i:s');
  6895. // 更新动漫大纲
  6896. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6897. if (!$boolen) {
  6898. dLog('deepseek')->info('动漫保存失败', $table_data);
  6899. Utils::throwError('20003:动漫保存失败');
  6900. }
  6901. // 保存对话记录
  6902. $records = [
  6903. [
  6904. 'uid' => $uid,
  6905. 'anime_id' => $anime_id,
  6906. 'sequence' => 0,
  6907. 'role' => 'user',
  6908. 'content' => $prompt,
  6909. 'created_at' => date('Y-m-d H:i:s'),
  6910. 'updated_at' => date('Y-m-d H:i:s')
  6911. ],
  6912. [
  6913. 'uid' => $uid,
  6914. 'anime_id' => $anime_id,
  6915. 'sequence' => 0,
  6916. 'role' => 'assistant',
  6917. 'content' => $fullContent,
  6918. 'created_at' => date('Y-m-d H:i:s'),
  6919. 'updated_at' => date('Y-m-d H:i:s')
  6920. ]
  6921. ];
  6922. // 保存对话记录
  6923. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6924. if (!$boolen3) {
  6925. Utils::throwError('20003:对话记录保存失败');
  6926. }
  6927. if ($is_single) {
  6928. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6929. if (empty($episode_arr['acts'])) {
  6930. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6931. }
  6932. $saveResult = $this->saveEpisodeVersionData(
  6933. $anime_id,
  6934. 1,
  6935. $episode_arr,
  6936. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6937. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6938. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6939. null,
  6940. null,
  6941. false,
  6942. $content,
  6943. $now,
  6944. $ref_products
  6945. );
  6946. $single_episode = $saveResult['episode'];
  6947. $episode_id = $saveResult['episode_id'];
  6948. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6949. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6950. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6951. 'props' => json_encode($saveResult['merged_props'], 256),
  6952. 'updated_at' => $now
  6953. ]);
  6954. if ($boolen5 === false) {
  6955. Utils::throwError('20003:单剧集主表资源同步失败');
  6956. }
  6957. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6958. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6959. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6960. $episode_record_content = '确认分镜大纲';
  6961. if ($content !== '') {
  6962. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6963. }
  6964. $episode_records = [
  6965. [
  6966. 'uid' => $uid,
  6967. 'anime_id' => $anime_id,
  6968. 'role' => 'user',
  6969. 'content' => $episode_record_content,
  6970. 'sequence' => 1,
  6971. 'episode_id' => $episode_id,
  6972. 'created_at' => $now,
  6973. 'updated_at' => $now
  6974. ],
  6975. [
  6976. 'uid' => $uid,
  6977. 'anime_id' => $anime_id,
  6978. 'role' => 'assistant',
  6979. 'content' => $fullContent,
  6980. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6981. 'sequence' => 1,
  6982. 'episode_id' => $episode_id,
  6983. 'created_at' => $now,
  6984. 'updated_at' => $now
  6985. ]
  6986. ];
  6987. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6988. if (!$boolen4) {
  6989. Utils::throwError('20003:单剧集分镜记录保存失败');
  6990. }
  6991. }
  6992. }catch (\Exception $e) {
  6993. DB::rollBack();
  6994. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6995. yield [
  6996. 'type' => 'done',
  6997. 'answer' => $fullContent,
  6998. 'reasoning' => $fullReasoningContent,
  6999. 'usage' => $usage,
  7000. 'error' => $e->getMessage(),
  7001. ];
  7002. return;
  7003. }
  7004. DB::commit();
  7005. dLog('deepseek')->info('保存完毕');
  7006. if ($is_single && !empty($single_episode)) {
  7007. // $this->batchSetGlobalRoleImg([
  7008. // 'anime_id' => $anime_id,
  7009. // ]);
  7010. // $this->batchSetGlobalSceneImg([
  7011. // 'anime_id' => $anime_id,
  7012. // ]);
  7013. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7014. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7015. }
  7016. $table_data['anime_id'] = $anime_id;
  7017. $table_data['roles'] = json_decode($table_data['roles'], true);
  7018. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7019. // $table_data['episodes'] = $script_arr['episodes'];
  7020. unset($table_data['created_at']);
  7021. unset($table_data['updated_at']);
  7022. unset($table_data['status']);
  7023. dLog('deepseek')->info('开始返回');
  7024. yield [
  7025. 'type' => 'done',
  7026. 'script' => $table_data,
  7027. 'episode' => $single_episode,
  7028. 'answer' => $fullContent,
  7029. 'reasoning' => $fullReasoningContent,
  7030. 'usage' => $usage
  7031. ];
  7032. }
  7033. public function reGenerateAnimeForAce($data) {
  7034. $uid = Site::getUid();
  7035. $file = getProp($data, 'file');
  7036. $content = getProp($data, 'content', '');
  7037. $bid = getProp($data, 'bid', 0);
  7038. $script_id = getProp($data, 'script_id', 0);
  7039. $anime_id = getProp($data, 'anime_id');
  7040. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7041. if (!$anime) {
  7042. Utils::throwError('20003:该对话不存在');
  7043. }
  7044. $is_multi = getProp($anime, 'is_multi', 1);
  7045. $is_single = (int)$is_multi !== 1;
  7046. $extra_products = getProp($data, 'products', []);
  7047. if (!$extra_products) {
  7048. $extra_products = getProp($anime, 'extra_products');
  7049. if ($extra_products) {
  7050. $extra_products = json_decode($extra_products, true);
  7051. }else {
  7052. $extra_products = [];
  7053. }
  7054. }else {
  7055. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7056. }
  7057. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7058. $anime_script_id = getProp($anime, 'script_id');
  7059. if ($anime_script_id && $is_single) {
  7060. $cpid = Site::getCpid();
  7061. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7062. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7063. ->where('mapping.script_id', $anime_script_id)
  7064. ->where('product.cpid', $cpid)
  7065. ->where('product.is_deleted', 0);
  7066. $mappings = $script_products_mappings->select(
  7067. 'mapping.product_id',
  7068. 'mapping.episode_number',
  7069. 'product.product_name',
  7070. 'product.type',
  7071. 'product.product',
  7072. 'product.pic_prompt',
  7073. 'product.url',
  7074. 'product.pic_task_id',
  7075. 'product.pic_task_status',
  7076. 'product.three_view_image_url'
  7077. )
  7078. ->get();
  7079. // 按 product_id 分组,合并 episode_number
  7080. $productMap = [];
  7081. foreach ($mappings as $item) {
  7082. $product_id = $item->product_id;
  7083. $product_name = $item->product_name;
  7084. // 处理product_name两边的符号
  7085. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7086. if (!isset($productMap[$product_id])) {
  7087. $productMap[$product_id] = [
  7088. 'product_id' => $product_id,
  7089. 'product_name' => $product_name,
  7090. 'type' => (int)$item->type,
  7091. 'product' => (int)$item->product,
  7092. 'pic_prompt' => $item->pic_prompt,
  7093. 'url' => $item->url,
  7094. 'pic_task_id' => $item->pic_task_id,
  7095. 'pic_task_status' => $item->pic_task_status,
  7096. 'episode_numbers' => [],
  7097. ];
  7098. }
  7099. // 添加 episode_number(去重)
  7100. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7101. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7102. }
  7103. }
  7104. // 将查询到的剧本资产合并到extra_products中
  7105. // 先构建extra_products的索引(以product_id为key,用于去重)
  7106. $extraProductsMap = [];
  7107. foreach ($extra_products as $item) {
  7108. $key = getProp($item, 'product_id');
  7109. if ($key) {
  7110. $extraProductsMap[$key] = $item;
  7111. }
  7112. }
  7113. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7114. foreach ($productMap as $product) {
  7115. $product_id = $product['product_id'];
  7116. // 如果不存在则添加(不带episode_number信息)
  7117. if (!isset($extraProductsMap[$product_id])) {
  7118. $extraProductsMap[$product_id] = [
  7119. 'product_id' => $product['product_id'],
  7120. 'product_name' => $product['product_name'],
  7121. 'type' => $product['type'],
  7122. 'product' => $product['product'],
  7123. 'pic_prompt' => $product['pic_prompt'],
  7124. 'url' => $product['url'],
  7125. 'pic_task_id' => $product['pic_task_id'],
  7126. 'pic_task_status' => $product['pic_task_status'],
  7127. ];
  7128. }
  7129. }
  7130. // 重新赋值给extra_products
  7131. $extra_products = array_values($extraProductsMap);
  7132. }
  7133. $user_anime_name = getProp($anime, 'anime_name');
  7134. $prompt = getProp($data, 'prompt');
  7135. // 处理提示词
  7136. if ($prompt && $extra_products) {
  7137. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7138. foreach($extra_products as $item) {
  7139. $product_name = getProp($item, 'product_name');
  7140. if ($product_name) {
  7141. // 替换 {product_name} 为 product_name
  7142. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7143. }
  7144. }
  7145. }
  7146. // 处理文本模型
  7147. $model = getProp($data, 'model');
  7148. if (!$model) {
  7149. // 用户没有输入,从anime表获取
  7150. $model = getProp($anime, 'model');
  7151. if (!$model) {
  7152. // anime表也没有,使用默认值
  7153. $model = 'deepseek-v4-pro';
  7154. }
  7155. }
  7156. // 验证模型是否在可用模型表中
  7157. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7158. $model = 'deepseek-v4-pro';
  7159. }
  7160. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7161. if ($is_single) {
  7162. $episode_exists = DB::table('mp_anime_episodes')
  7163. ->where('anime_id', $anime_id)
  7164. ->where('sequence', 1)
  7165. ->exists();
  7166. if ($episode_exists) {
  7167. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7168. }
  7169. }
  7170. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7171. if ($prompt) {
  7172. $question .= "本次修改要求如下:\n{$prompt}";
  7173. }
  7174. // 提取文件内容
  7175. if ($file) {
  7176. $content = $this->extractFileContent($file);
  7177. if (!$content) {
  7178. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7179. }
  7180. } elseif ($script_id) {
  7181. $content = $this->getContentByScriptId($script_id);
  7182. if (!$content) {
  7183. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7184. }
  7185. } elseif ($bid) {
  7186. $content = $this->getContentByBid($bid);
  7187. if (!$content) {
  7188. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7189. }
  7190. } elseif ($content) {
  7191. $content = filterContent($content);
  7192. }else {
  7193. $content = filterContent(getProp($anime, 'content'));
  7194. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7195. $need_generate_content = true;
  7196. }
  7197. }
  7198. // 判断是否需要生成原文内容
  7199. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7200. // 如果需要生成原文内容,添加额外的要求
  7201. $content_generation_requirement = $need_generate_content
  7202. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7203. : "";
  7204. // 美术风格
  7205. $input_art_style = getProp($data, 'art_style');
  7206. if (!$input_art_style) {
  7207. $mappedArtStyle = getProp($anime, 'art_style');
  7208. }else {
  7209. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7210. }
  7211. if (!$mappedArtStyle) {
  7212. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7213. }else {
  7214. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7215. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7216. }else {
  7217. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7218. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7219. }
  7220. }
  7221. // 构建主体、场景和道具提示词
  7222. $extra_role_prompt = "\n";
  7223. $extra_scene_prompt = "\n";
  7224. $extra_prop_prompt = "\n";
  7225. $ref_products = []; // 参考资产
  7226. if ($extra_products) {
  7227. foreach($extra_products as $item) {
  7228. $product = getProp($item, 'product');
  7229. $product_name = getProp($item, 'product_name');
  7230. if ($product_name == '旁白') continue;
  7231. $ref_products[$product_name] = $item;
  7232. $pic_prompt = getProp($item, 'pic_prompt');
  7233. if ((int)$product === 1) {
  7234. // 拼接角色信息
  7235. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7236. } elseif ((int)$product === 2) {
  7237. // 拼接场景信息
  7238. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7239. } elseif ((int)$product === 3) {
  7240. // 拼接道具信息
  7241. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7242. }
  7243. }
  7244. // 优化提示词,融入剧本
  7245. if (!empty(trim($extra_role_prompt))) {
  7246. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7247. }
  7248. if (!empty(trim($extra_scene_prompt))) {
  7249. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7250. }
  7251. if (!empty(trim($extra_prop_prompt))) {
  7252. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7253. }
  7254. }
  7255. if ($anime_script_id && $is_single) {
  7256. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7257. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7258. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7259. }else {
  7260. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7261. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7262. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7263. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7264. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7265. {$extra_role_prompt}";
  7266. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7267. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7268. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7269. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7270. {$extra_scene_prompt}";
  7271. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7272. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7273. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7274. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7275. {$extra_prop_prompt}";
  7276. }
  7277. $system_message = ['role'=>'system', 'content'=>$is_single
  7278. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7279. 强制要求:
  7280. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7281. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7282. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7283. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7284. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7285. 普通要求:
  7286. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7287. $role_demo
  7288. $scene_demo
  7289. $prop_demo
  7290. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7291. 5.1片段分割逻辑(优先级从高到低):
  7292. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7293. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7294. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7295. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7296. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7297. - 片段数量格式为: 片段数量:8
  7298. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7299. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7300. 5.3分镜结构:每个分镜包含以下字段:
  7301. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7302. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7303. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7304. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7305. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7306. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7307. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7308. - 运镜:场景+画面描述+运镜
  7309. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7310. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7311. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7312. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7313. 6.{$mappedArtStyle_prompt}\n\n
  7314. 示例如下:\n
  7315. ###剧本名:西昆仑
  7316. ###故事梗概
  7317. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7318. ###剧本亮点
  7319. 亮点1:绝境奇药,生死一线
  7320. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7321. 亮点2:结拜兄妹,化解尴尬
  7322. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7323. 亮点3:纤发夺命,情愫暗涌
  7324. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7325. ###人物关系
  7326. 阿雪与梁萧之间存在兄妹之情。
  7327. ###核心矛盾
  7328. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7329. ###主体列表
  7330. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7331. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7332. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7333. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7334. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7335. 全景,正面拍摄,青年女性,亚洲人。
  7336. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7337. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7338. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7339. ###美术风格
  7340. 基础画风风格词:厚涂古风
  7341. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7342. ###场景列表
  7343. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7344. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7345. 无人物。}
  7346. ###分段剧本
  7347. 片段数量:8
  7348. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7349. ##片段1
  7350. 时长:12s
  7351. 分镜1
  7352. 出场角色:刀疤脸
  7353. 场景:边境小镇街道
  7354. 出场道具:酒杯-高脚杯
  7355. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7356. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7357. 配音台词:
  7358. 背景音效:
  7359. 分镜2
  7360. 出场角色:刀疤脸
  7361. 场景:悦来酒馆
  7362. 出场道具:酒杯-高脚杯
  7363. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7364. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7365. 配音台词:
  7366. 背景音效:
  7367. 分镜3
  7368. 出场角色:刀疤脸
  7369. 场景:悦来酒馆
  7370. 出场道具:酒杯-高脚杯
  7371. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7372. 运镜:从中景推向令牌特写。
  7373. 配音台词:
  7374. 背景音效:
  7375. 分镜4
  7376. 出场角色:刀疤脸
  7377. 场景:悦来酒馆
  7378. 出场道具:酒杯-高脚杯
  7379. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7380. 运镜:极速推向酒水溅起的瞬间。
  7381. 配音台词:
  7382. 背景音效:
  7383. 分镜5
  7384. 出场角色:刀疤脸
  7385. 场景:悦来酒馆
  7386. 出场道具:酒杯-高脚杯
  7387. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7388. 运镜:固定机位,利用倾斜构图制造压迫感。
  7389. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7390. 背景音效:
  7391. \n\n"
  7392. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7393. 强制要求:\n
  7394. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7395. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7396. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7397. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7398. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7399. 普通要求:\n
  7400. 1.剧本名(必须生成)必须与文档内容高度相关
  7401. $role_demo
  7402. $scene_demo
  7403. $prop_demo
  7404. 5.{$mappedArtStyle_prompt}\n\n
  7405. 示例如下:\n
  7406. ###剧本名:西昆仑
  7407. ###故事梗概
  7408. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7409. ###剧本亮点
  7410. 亮点1:绝境奇药,生死一线
  7411. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7412. 亮点2:结拜兄妹,化解尴尬
  7413. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7414. 亮点3:纤发夺命,情愫暗涌
  7415. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7416. ###人物关系
  7417. 阿雪与梁萧之间存在兄妹之情。
  7418. ###核心矛盾
  7419. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7420. ###主体列表
  7421. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7422. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7423. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7424. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7425. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7426. 全景,正面拍摄,青年女性,亚洲人。
  7427. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7428. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7429. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7430. ###美术风格
  7431. 基础画风风格词:厚涂古风
  7432. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7433. ###场景列表
  7434. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7435. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7436. 无人物。}
  7437. ###道具列表
  7438. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7439. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7440. $episode_count = $this->extractEpisodeNumber($prompt);
  7441. if ((int)getProp($anime, 'is_multi') !== 1) {
  7442. yield [
  7443. 'type' => 'done',
  7444. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7445. 'reasoning' => '',
  7446. 'usage' => []
  7447. ];
  7448. return;
  7449. }
  7450. if ($episode_count) {
  7451. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7452. $system_message = [
  7453. 'role' => 'system',
  7454. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7455. 强制要求:\n
  7456. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7457. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7458. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7459. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7460. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7461. 普通要求:\n
  7462. 1.<故事梗概>控制在200-300字左右
  7463. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7464. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7465. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7466. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7467. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7468. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7469. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7470. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7471. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7472. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  7473. 示例如下:\n
  7474. ###剧本名:西昆仑
  7475. ###故事梗概
  7476. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7477. ###剧本亮点
  7478. 亮点1:绝境奇药,生死一线
  7479. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7480. 亮点2:结拜兄妹,化解尴尬
  7481. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7482. 亮点3:纤发夺命,情愫暗涌
  7483. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7484. ###人物关系
  7485. 阿雪与梁萧之间存在兄妹之情。
  7486. ###核心矛盾
  7487. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7488. ###主体列表
  7489. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7490. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7491. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7492. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7493. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7494. 全景,正面拍摄,青年女性,亚洲人。
  7495. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7496. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7497. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7498. ###美术风格
  7499. 基础画风风格词:厚涂古风
  7500. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7501. ###场景列表
  7502. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7503. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7504. 无人物。}
  7505. ###分集详细内容
  7506. ##第1章 重生
  7507. 我重生了。
  7508. 源于一个男人偏执的暗恋。
  7509. ##第2章 相救
  7510. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  7511. 我眼睛扫向站在锅炉后的卞大伟。"
  7512. ];
  7513. // 构建消息
  7514. $messages = [
  7515. $system_message,
  7516. [
  7517. 'role' => 'user',
  7518. 'content' => "以下是文档内容:
  7519. {$content}
  7520. 用户问题:
  7521. {$question}"
  7522. ]
  7523. ];
  7524. }else {
  7525. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  7526. // 构建消息
  7527. $messages = [
  7528. $system_message,
  7529. [
  7530. 'role' => 'user',
  7531. 'content' => "以下是文档内容:
  7532. {$content}
  7533. 用户问题:
  7534. {$question}"
  7535. ]
  7536. ];
  7537. }else {
  7538. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  7539. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  7540. return (array)$value;
  7541. })->toArray();
  7542. array_unshift($messages, $system_message);
  7543. $messages[] = [
  7544. 'role' => 'user',
  7545. 'content' => $prompt
  7546. ];
  7547. }
  7548. }
  7549. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7550. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7551. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7552. if ($model === 'deepseek-chat') {
  7553. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7554. $model = 'deepseek-v4-flash';
  7555. $thinkingMode = 'disabled';
  7556. } elseif ($model === 'deepseek-reasoner') {
  7557. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7558. $model = 'deepseek-v4-flash';
  7559. $thinkingMode = 'enabled';
  7560. }
  7561. $post_data = [
  7562. 'model' => $model,
  7563. 'messages' => $messages,
  7564. // 'max_tokens' => 8192,
  7565. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7566. 'frequency_penalty' => 0,
  7567. 'presence_penalty' => 0,
  7568. 'response_format' => ['type' => 'text'],
  7569. 'thinking' => ['type' => $thinkingMode],
  7570. 'stream' => true // 启用流式输出
  7571. ];
  7572. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7573. // 根据模型类型选择调用方法
  7574. $fullContent = '';
  7575. $fullReasoningContent = '';
  7576. $usage = [];
  7577. // dd($post_data);
  7578. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  7579. try {
  7580. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7581. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7582. } else if (in_array($model, $this->gpt_text_models)) {
  7583. // GPT-5.4 模型使用 TokenRouter API
  7584. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7585. } else if (in_array($model, $this->gemini_text_models)) {
  7586. // Gemini 模型使用 Gemini API
  7587. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7588. } else {
  7589. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7590. }
  7591. // 验证返回值类型
  7592. if (!is_iterable($streamGenerator)) {
  7593. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7594. dLog('deepseek')->error('方法名流式生成器无效', [
  7595. 'generator_type' => $errorType,
  7596. 'model' => $model,
  7597. // 添加其他上下文信息
  7598. ]);
  7599. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  7600. 'type' => $errorType,
  7601. 'model' => $model
  7602. ]);
  7603. yield [
  7604. 'type' => 'error',
  7605. // 根据方法返回相应的空数据结构
  7606. 'answer' => '',
  7607. 'reasoning' => '',
  7608. 'usage' => [],
  7609. 'error' => '接口返回数据异常,请重新请求'
  7610. ];
  7611. return;
  7612. }
  7613. // 处理流式输出
  7614. foreach ($streamGenerator as $chunk) {
  7615. if (isset($chunk['type'])) {
  7616. if ($chunk['type'] === 'done') {
  7617. $fullContent = $chunk['full_content'];
  7618. $fullReasoningContent = $chunk['full_reasoning'];
  7619. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7620. } else {
  7621. yield $chunk;
  7622. }
  7623. }
  7624. }
  7625. } catch (\Exception $e) {
  7626. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  7627. 'model' => $model,
  7628. 'trace' => $e->getTraceAsString()
  7629. ]);
  7630. logDB('deepseek', 'error', '方法名流式处理失败', [
  7631. 'error' => $e->getMessage(),
  7632. 'model' => $model
  7633. ]);
  7634. yield [
  7635. 'type' => 'error',
  7636. // 根据方法返回相应的空数据结构
  7637. 'answer' => '',
  7638. 'reasoning' => '',
  7639. 'usage' => [],
  7640. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7641. ];
  7642. return;
  7643. }
  7644. dLog('deepseek')->info('完整内容: '.$fullContent);
  7645. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7646. // 处理完整内容并返回最终结果
  7647. $script_arr = [];
  7648. if ($fullContent) {
  7649. $script_arr = handleScriptContentForAce($fullContent);
  7650. dLog('deepseek')->info('解析内容', $script_arr);
  7651. logDB('deepseek', 'info', '解析内容', $script_arr);
  7652. }
  7653. if (empty($script_arr['roles'])) {
  7654. // 未生成剧本相关内容,保存对话记录并返回提示
  7655. dLog('deepseek')->info('未生成剧本相关的内容');
  7656. try {
  7657. $now = date('Y-m-d H:i:s');
  7658. // 保存对话记录
  7659. $records = [
  7660. [
  7661. 'uid' => $uid,
  7662. 'anime_id' => $anime_id,
  7663. 'sequence' => 0,
  7664. 'role' => 'user',
  7665. 'content' => $prompt,
  7666. 'created_at' => $now,
  7667. 'updated_at' => $now
  7668. ],
  7669. [
  7670. 'uid' => $uid,
  7671. 'anime_id' => $anime_id,
  7672. 'sequence' => 0,
  7673. 'role' => 'assistant',
  7674. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  7675. 'created_at' => $now,
  7676. 'updated_at' => $now
  7677. ]
  7678. ];
  7679. DB::table('mp_anime_records')->insert($records);
  7680. } catch (\Exception $e) {
  7681. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7682. }
  7683. yield [
  7684. 'type' => 'done',
  7685. 'script' => [],
  7686. 'episode' => [],
  7687. 'answer' => $fullContent,
  7688. 'reasoning' => $fullReasoningContent,
  7689. 'usage' => $usage,
  7690. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7691. ];
  7692. return;
  7693. }
  7694. // 替换美术风格
  7695. if ($mappedArtStyle !== '') {
  7696. $script_arr['art_style'] = $mappedArtStyle;
  7697. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7698. }
  7699. if ($user_anime_name != '新剧本策划') {
  7700. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7701. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7702. // 确认对话名称唯一性
  7703. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7704. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  7705. }
  7706. }else {
  7707. $anime_name = $user_anime_name;
  7708. }
  7709. $table_data = [
  7710. 'user_id' => $uid,
  7711. 'model' => $model,
  7712. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7713. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7714. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7715. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7716. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7717. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7718. 'art_style_type' => $input_art_style,
  7719. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7720. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7721. 'status' => '解析完成',
  7722. 'generate_status' => '待执行',
  7723. 'updated_at' => date('Y-m-d H:i:s')
  7724. ];
  7725. if ($anime_name) $table_data['anime_name'] = $anime_name;
  7726. // 如果是修改集数,则将content内容更新(会改变原文)
  7727. if (isset($episode_count) && $episode_count > 0) {
  7728. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  7729. $table_data['start_episode_sequence'] = 1;
  7730. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  7731. }else {
  7732. // 如果需要生成原文内容,从script_arr中提取
  7733. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7734. $table_data['content'] = $script_arr['content'];
  7735. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  7736. if (!$table_data['content']) {
  7737. yield [
  7738. 'type' => 'done',
  7739. 'script' => [],
  7740. 'episode' => [],
  7741. 'answer' => $fullContent,
  7742. 'reasoning' => $fullReasoningContent,
  7743. 'usage' => $usage,
  7744. 'error' => '未生成剧本内容,请调整提示词再试'
  7745. ];
  7746. return;
  7747. }
  7748. }
  7749. if (isset($table_data['content']) && $table_data['content']) {
  7750. $chapters = splitContent($table_data['content']);
  7751. $chapter_count = count($chapters);
  7752. if ($chapter_count > 0) {
  7753. $table_data['start_episode_sequence'] = 1;
  7754. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7755. }
  7756. }
  7757. }
  7758. if ($extra_products) {
  7759. $table_data['extra_products'] = json_encode($extra_products, 256);
  7760. }
  7761. $single_episode = [];
  7762. try {
  7763. DB::beginTransaction();
  7764. $now = date('Y-m-d H:i:s');
  7765. // 更新动漫大纲
  7766. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7767. if (!$boolen) {
  7768. dLog('deepseek')->info('对话修改失败', $table_data);
  7769. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7770. Utils::throwError('20003:对话修改失败');
  7771. }
  7772. // 保存对话记录
  7773. $records = [
  7774. [
  7775. 'uid' => $uid,
  7776. 'anime_id' => $anime_id,
  7777. 'sequence' => 0,
  7778. 'role' => 'user',
  7779. 'content' => $prompt,
  7780. 'created_at' => $now,
  7781. 'updated_at' => $now
  7782. ],
  7783. [
  7784. 'uid' => $uid,
  7785. 'anime_id' => $anime_id,
  7786. 'sequence' => 0,
  7787. 'role' => 'assistant',
  7788. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7789. 'content' => $fullContent,
  7790. 'created_at' => $now,
  7791. 'updated_at' => $now
  7792. ]
  7793. ];
  7794. // 保存对话记录
  7795. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7796. if (!$boolen3) {
  7797. Utils::throwError('20003:对话记录保存失败');
  7798. }
  7799. // 单剧集模式:生成并保存剧集信息
  7800. if ($is_single) {
  7801. $anime_name = getProp($anime, 'anime_name', '未命名');
  7802. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7803. if (empty($episode_arr['acts'])) {
  7804. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7805. }
  7806. $saveResult = $this->saveEpisodeVersionData(
  7807. $anime_id,
  7808. 1,
  7809. $episode_arr,
  7810. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7811. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7812. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7813. null,
  7814. null,
  7815. false,
  7816. $content,
  7817. $now,
  7818. $ref_products
  7819. );
  7820. $single_episode = $saveResult['episode'];
  7821. $episode_id = $saveResult['episode_id'];
  7822. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7823. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7824. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7825. 'props' => json_encode($saveResult['merged_props'], 256),
  7826. 'updated_at' => $now
  7827. ]);
  7828. if ($boolen5 === false) {
  7829. Utils::throwError('20003:单剧集主表资源同步失败');
  7830. }
  7831. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7832. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7833. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7834. $episode_record_content = '确认分镜大纲';
  7835. if ($content !== '') {
  7836. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7837. }
  7838. $episode_records = [
  7839. [
  7840. 'uid' => $uid,
  7841. 'anime_id' => $anime_id,
  7842. 'role' => 'user',
  7843. 'content' => $episode_record_content,
  7844. 'sequence' => 1,
  7845. 'episode_id' => $episode_id,
  7846. 'created_at' => $now,
  7847. 'updated_at' => $now
  7848. ],
  7849. [
  7850. 'uid' => $uid,
  7851. 'anime_id' => $anime_id,
  7852. 'role' => 'assistant',
  7853. 'content' => $fullContent,
  7854. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7855. 'sequence' => 1,
  7856. 'episode_id' => $episode_id,
  7857. 'created_at' => $now,
  7858. 'updated_at' => $now
  7859. ]
  7860. ];
  7861. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7862. if (!$boolen4) {
  7863. Utils::throwError('20003:单剧集分镜记录保存失败');
  7864. }
  7865. }
  7866. }catch (\Exception $e) {
  7867. DB::rollBack();
  7868. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7869. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7870. yield [
  7871. 'type' => 'done',
  7872. 'answer' => $fullContent,
  7873. 'reasoning' => $fullReasoningContent,
  7874. 'usage' => $usage,
  7875. 'error' => $e->getMessage(),
  7876. ];
  7877. return;
  7878. }
  7879. DB::commit();
  7880. dLog('deepseek')->info('保存完毕');
  7881. if ($is_single && !empty($single_episode)) {
  7882. // $this->batchSetGlobalRoleImg([
  7883. // 'anime_id' => $anime_id,
  7884. // ]);
  7885. // $this->batchSetGlobalSceneImg([
  7886. // 'anime_id' => $anime_id,
  7887. // ]);
  7888. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7889. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7890. }
  7891. $table_data['anime_id'] = $anime_id;
  7892. $table_data['roles'] = json_decode($table_data['roles'], true);
  7893. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7894. $table_data['props'] = json_decode($table_data['props'], true);
  7895. unset($table_data['updated_at']);
  7896. unset($table_data['status']);
  7897. yield [
  7898. 'type' => 'done',
  7899. 'script' => $table_data,
  7900. 'episode' => $single_episode,
  7901. 'answer' => $fullContent,
  7902. 'reasoning' => $fullReasoningContent,
  7903. 'usage' => $usage
  7904. ];
  7905. }
  7906. public function chatForAce($data) {
  7907. $uid = Site::getUid();
  7908. $anime_id = getProp($data, 'anime_id');
  7909. $file = getProp($data, 'file');
  7910. $content = getProp($data, 'content', '');
  7911. $bid = getProp($data, 'bid', 0);
  7912. $script_id = getProp($data, 'script_id', 0);
  7913. $episode_number = getProp($data, 'episode_number', 1);
  7914. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7915. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7916. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7917. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7918. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7919. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7920. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7921. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7922. $roles = is_array($roles) ? $roles : [];
  7923. $scenes = is_array($scenes) ? $scenes : [];
  7924. $extra_products = getProp($data, 'products', []);
  7925. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7926. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7927. $anime_script_id = getProp($anime, 'script_id');
  7928. if ($anime_script_id) {
  7929. $cpid = Site::getCpid();
  7930. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7931. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7932. ->where('mapping.script_id', $anime_script_id)
  7933. ->where('product.cpid', $cpid)
  7934. ->where('product.is_deleted', 0);
  7935. // 如果提供了 episode_number,则过滤指定集数
  7936. if ($episode_number !== null && $episode_number !== '') {
  7937. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7938. }
  7939. $mappings = $script_products_mappings->select(
  7940. 'mapping.product_id',
  7941. 'mapping.episode_number',
  7942. 'product.product_name',
  7943. 'product.type',
  7944. 'product.product',
  7945. 'product.pic_prompt',
  7946. 'product.url',
  7947. 'product.pic_task_id',
  7948. 'product.pic_task_status',
  7949. 'product.three_view_image_url'
  7950. )
  7951. ->get();
  7952. // 按 product_id 分组,合并 episode_number
  7953. $productMap = [];
  7954. foreach ($mappings as $item) {
  7955. $product_id = $item->product_id;
  7956. $product_name = $item->product_name;
  7957. // 处理product_name两边的符号
  7958. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7959. if (!isset($productMap[$product_id])) {
  7960. $productMap[$product_id] = [
  7961. 'product_id' => $product_id,
  7962. 'product_name' => $product_name,
  7963. 'type' => (int)$item->type,
  7964. 'product' => (int)$item->product,
  7965. 'pic_prompt' => $item->pic_prompt,
  7966. 'url' => $item->url,
  7967. 'pic_task_id' => $item->pic_task_id,
  7968. 'pic_task_status' => $item->pic_task_status,
  7969. 'episode_numbers' => [],
  7970. ];
  7971. }
  7972. // 添加 episode_number(去重)
  7973. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7974. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7975. }
  7976. }
  7977. // 将查询到的剧本资产合并到extra_products中
  7978. // 先构建extra_products的索引(以product_id+episode_number为key)
  7979. $extraProductsMap = [];
  7980. foreach ($extra_products as $item) {
  7981. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7982. $extraProductsMap[$key] = $item;
  7983. }
  7984. // 合并剧本资产(去重:product_id+episode_number)
  7985. foreach ($productMap as $product) {
  7986. foreach ($product['episode_numbers'] as $ep_num) {
  7987. $key = $product['product_id'] . '_' . $ep_num;
  7988. // 如果不存在则添加
  7989. if (!isset($extraProductsMap[$key])) {
  7990. $extraProductsMap[$key] = [
  7991. 'product_id' => $product['product_id'],
  7992. 'product_name' => $product['product_name'],
  7993. 'type' => $product['type'],
  7994. 'product' => $product['product'],
  7995. 'pic_prompt' => $product['pic_prompt'],
  7996. 'url' => $product['url'],
  7997. 'pic_task_id' => $product['pic_task_id'],
  7998. 'pic_task_status' => $product['pic_task_status'],
  7999. 'episode_number' => $ep_num,
  8000. ];
  8001. }
  8002. }
  8003. }
  8004. // 重新赋值给extra_products
  8005. $extra_products = array_values($extraProductsMap);
  8006. }
  8007. // 处理提示词
  8008. if ($prompt && $extra_products) {
  8009. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8010. foreach($extra_products as $item) {
  8011. $product_name = getProp($item, 'product_name');
  8012. if ($product_name) {
  8013. // 替换 {product_name} 为 product_name
  8014. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8015. }
  8016. }
  8017. }
  8018. // 获取最后一集序号
  8019. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8020. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8021. // 转换主体列表和场景列表的格式
  8022. // 获取参考主体或场景
  8023. if ((int)$episode_number === 1) {
  8024. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8025. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8026. }else {
  8027. $prev_episode_number = $episode_number - 1;
  8028. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8029. }
  8030. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8031. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8032. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8033. // 合并anime_products和extra_products(extra_products优先,去重)
  8034. $anime_products = getProp($anime, 'extra_products');
  8035. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8036. $ref_products = [];
  8037. foreach($anime_products as $item) {
  8038. $product_name = getProp($item, 'product_name');
  8039. $ref_products[$product_name] = $item;
  8040. }
  8041. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8042. $extra_roles = []; // 从extra_products中提取的角色
  8043. $extra_scenes = []; // 从extra_products中提取的场景
  8044. $extra_props = []; // 从extra_products中提取的道具
  8045. if ($extra_products && is_array($extra_products)) {
  8046. foreach($extra_products as $item) {
  8047. $product = (int)getProp($item, 'product');
  8048. $product_name = getProp($item, 'product_name');
  8049. if ($product_name == '旁白') continue;
  8050. $pic_prompt = getProp($item, 'pic_prompt');
  8051. $ref_products[$product_name] = $item;
  8052. if ($product === 1) {
  8053. // 角色
  8054. $extra_roles[$product_name] = [
  8055. 'role' => $product_name,
  8056. 'pic_prompt' => $pic_prompt,
  8057. 'url' => getProp($item, 'url', ''),
  8058. ];
  8059. } elseif ($product === 2) {
  8060. // 场景
  8061. $extra_scenes[$product_name] = [
  8062. 'scene' => $product_name,
  8063. 'pic_prompt' => $pic_prompt,
  8064. 'url' => getProp($item, 'url', ''),
  8065. ];
  8066. } elseif ($product === 3) {
  8067. // 道具
  8068. $extra_props[$product_name] = [
  8069. 'prop' => $product_name,
  8070. 'pic_prompt' => $pic_prompt,
  8071. 'url' => getProp($item, 'url', ''),
  8072. ];
  8073. }
  8074. }
  8075. }
  8076. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8077. $merged_roles = [];
  8078. foreach($ref_roles as $role) {
  8079. $role_name = getProp($role, 'role');
  8080. if (!isset($extra_roles[$role_name])) {
  8081. $merged_roles[$role_name] = $role;
  8082. }
  8083. }
  8084. // 添加extra_roles
  8085. foreach($extra_roles as $role_name => $role) {
  8086. $merged_roles[$role_name] = $role;
  8087. }
  8088. $ref_roles = array_values($merged_roles);
  8089. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8090. $merged_scenes = [];
  8091. foreach($ref_scenes as $scene) {
  8092. $scene_name = getProp($scene, 'scene');
  8093. if (!isset($extra_scenes[$scene_name])) {
  8094. $merged_scenes[$scene_name] = $scene;
  8095. }
  8096. }
  8097. // 添加extra_scenes
  8098. foreach($extra_scenes as $scene_name => $scene) {
  8099. $merged_scenes[$scene_name] = $scene;
  8100. }
  8101. $ref_scenes = array_values($merged_scenes);
  8102. // 合并ref_props和extra_props(extra_props优先,去重)
  8103. $merged_props = [];
  8104. foreach($ref_props as $prop) {
  8105. $prop_name = getProp($prop, 'prop');
  8106. if (!isset($extra_props[$prop_name])) {
  8107. $merged_props[$prop_name] = $prop;
  8108. }
  8109. }
  8110. // 添加extra_props
  8111. foreach($extra_props as $prop_name => $prop) {
  8112. $merged_props[$prop_name] = $prop;
  8113. }
  8114. $ref_props = array_values($merged_props);
  8115. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8116. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8117. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8118. // 构建强制主体、场景和道具提示词
  8119. $forced_roles_prompt = "";
  8120. $forced_scenes_prompt = "";
  8121. $forced_props_prompt = "";
  8122. if (!empty($extra_roles)) {
  8123. $forced_roles_list = "";
  8124. foreach($extra_roles as $role_name => $role) {
  8125. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8126. }
  8127. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8128. }
  8129. if (!empty($extra_scenes)) {
  8130. $forced_scenes_list = "";
  8131. foreach($extra_scenes as $scene_name => $scene) {
  8132. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8133. }
  8134. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8135. }
  8136. if (!empty($extra_props)) {
  8137. $forced_props_list = "";
  8138. foreach($extra_props as $prop_name => $prop) {
  8139. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8140. }
  8141. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8142. }
  8143. if ($anime_script_id) {
  8144. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8145. }else if ($roles_content) {
  8146. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8147. 主体范围:\n {$roles_content}\n
  8148. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8149. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8150. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8151. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8152. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8153. }else {
  8154. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8155. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8156. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8157. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8158. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8159. }
  8160. if ($anime_script_id) {
  8161. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8162. }else if ($scenes_content) {
  8163. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8164. 场景范围:\n {$scenes_content}\n
  8165. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8166. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8167. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8168. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8169. }else {
  8170. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8171. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8172. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8173. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8174. }
  8175. if ($anime_script_id) {
  8176. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8177. }else if ($props_content) {
  8178. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8179. 道具范围:\n {$props_content}\n
  8180. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8181. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8182. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8183. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8184. }else {
  8185. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8186. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8187. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8188. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8189. }
  8190. // 提取文件内容
  8191. if ($file) {
  8192. $uploaded_content = $this->extractFileContent($file);
  8193. if (!$uploaded_content) {
  8194. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8195. }
  8196. } elseif ($script_id) {
  8197. $uploaded_content = $this->getContentByScriptId($script_id);
  8198. if (!$uploaded_content) {
  8199. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8200. }
  8201. } elseif ($bid) {
  8202. $uploaded_content = $this->getContentByBid($bid);
  8203. if (!$uploaded_content) {
  8204. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8205. }
  8206. } elseif ($content) {
  8207. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8208. }
  8209. // elseif ($prompt) {
  8210. // $uploaded_content = filterContent($prompt);
  8211. // }
  8212. else {
  8213. $uploaded_content = '';
  8214. }
  8215. // 美术风格
  8216. $input_art_style = getProp($data, 'art_style');
  8217. if (!$input_art_style) {
  8218. $mappedArtStyle = getProp($anime, 'art_style');
  8219. }else {
  8220. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8221. }
  8222. if (!$mappedArtStyle) {
  8223. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8224. }else {
  8225. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8226. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8227. }else {
  8228. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8229. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8230. }
  8231. }
  8232. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8233. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8234. // 强制要求:
  8235. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8236. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8237. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8238. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8239. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8240. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8241. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8242. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8243. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8244. // 10.分镜要和场景列表、人物主体保持一致\n
  8245. // 普通要求:
  8246. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8247. // {$role_demo}
  8248. // {$scene_demo}
  8249. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8250. // 4.1片段分割逻辑(优先级从高到低):
  8251. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8252. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8253. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8254. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8255. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8256. // - 片段数量格式为: 片段数量:8
  8257. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8258. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8259. // 4.3分镜结构:每个分镜包含以下字段:
  8260. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8261. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8262. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8263. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8264. // - 运镜:场景+画面描述+运镜
  8265. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8266. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8267. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8268. // 5.$mappedArtStyle_prompt\n\n
  8269. // 示例格式:\n
  8270. // 第1集:隐形的守护者
  8271. // ###故事梗概
  8272. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8273. // ###美术风格
  8274. // 基础画风风格词:胡金铨武侠
  8275. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8276. // ###主体列表
  8277. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8278. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8279. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8280. // ###场景列表
  8281. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8282. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8283. // ###分段剧本
  8284. // 片段数量:8
  8285. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8286. // ##片段1
  8287. // 时长:12s
  8288. // 分镜1
  8289. // 场景:边境小镇街道
  8290. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8291. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8292. // 配音台词:
  8293. // 背景音效:
  8294. // 分镜2
  8295. // 场景:悦来酒馆
  8296. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8297. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8298. // 配音台词:
  8299. // 背景音效:
  8300. // 分镜3
  8301. // 场景:悦来酒馆
  8302. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8303. // 运镜:从中景推向令牌特写。
  8304. // 配音台词:
  8305. // 背景音效:
  8306. // 分镜4
  8307. // 场景:悦来酒馆
  8308. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8309. // 运镜:极速推向酒水溅起的瞬间。
  8310. // 配音台词:
  8311. // 背景音效:
  8312. // 分镜5
  8313. // 镜头描述
  8314. // 场景:悦来酒馆
  8315. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8316. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8317. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8318. // 背景音效:
  8319. // \n\n";
  8320. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8321. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8322. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8323. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8324. 普通要求:
  8325. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8326. {$role_demo}
  8327. {$scene_demo}
  8328. {$prop_demo}
  8329. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8330. 5.1片段分割逻辑(优先级从高到低):
  8331. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8332. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8333. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8334. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8335. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8336. - 片段数量格式为: 片段数量:8
  8337. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8338. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8339. 5.3分镜结构:每个分镜包含以下字段:
  8340. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8341. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8342. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8343. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8344. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8345. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8346. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8347. - 运镜:场景+画面描述+运镜
  8348. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8349. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8350. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8351. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8352. 6.《情绪-视听语言映射表》:
  8353. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8354. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8355. -----|---------|------------|----------------
  8356. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8357. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8358. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8359. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8360. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8361. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8362. -----|---------|------------|----------------
  8363. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8364. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8365. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8366. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8367. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8368. --------|---------|--------------|-------------
  8369. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8370. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8371. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8372. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8373. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8374. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8375. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8376. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8377. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8378. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8379. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8380. -----|---------|------------|------------
  8381. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8382. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8383. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8384. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8385. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8386. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8387. --------|---------|--------------|----------
  8388. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8389. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8390. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8391. 6.6 声音设计与潜意识影响 (Soundscape)
  8392. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8393. -----|---------|------------|------------------
  8394. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8395. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8396. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8397. 理论基石:
  8398. - The Five C's of Cinematography by Joseph V. Mascelli
  8399. - Film Art: An Introduction by David Bordwell
  8400. - Sight, Sound, Motion by Herbert Zettl
  8401. - Notes on the Cinematograph by Robert Bresson
  8402. \n\n
  8403. 7.{$mappedArtStyle_prompt}
  8404. 示例格式:\n
  8405. 第1集:隐形的守护者
  8406. ###故事梗概
  8407. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8408. ###美术风格
  8409. 基础画风风格词:胡金铨武侠
  8410. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8411. ###主体列表
  8412. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8413. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8414. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8415. ###场景列表
  8416. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8417. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8418. ###道具列表
  8419. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8420. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8421. ###分段剧本
  8422. 片段数量:8
  8423. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8424. ##片段1
  8425. 时长:12s
  8426. 分镜1
  8427. 出场角色:刀疤脸
  8428. 场景:边境小镇街道
  8429. 出场道具:酒杯-高脚杯
  8430. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8431. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8432. 配音台词:
  8433. 背景音效:
  8434. 分镜2
  8435. 出场角色:刀疤脸
  8436. 场景:悦来酒馆
  8437. 出场道具:酒杯-高脚杯
  8438. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8439. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8440. 配音台词:
  8441. 背景音效:
  8442. 分镜3
  8443. 出场角色:刀疤脸
  8444. 场景:悦来酒馆
  8445. 出场道具:酒杯-高脚杯
  8446. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8447. 运镜:从中景推向令牌特写。
  8448. 配音台词:
  8449. 背景音效:
  8450. 分镜4
  8451. 出场角色:刀疤脸
  8452. 场景:悦来酒馆
  8453. 出场道具:酒杯-高脚杯
  8454. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8455. 运镜:极速推向酒水溅起的瞬间。
  8456. 配音台词:
  8457. 背景音效:
  8458. 分镜5
  8459. 出场角色:刀疤脸
  8460. 场景:悦来酒馆
  8461. 出场道具:酒杯-高脚杯
  8462. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8463. 运镜:固定机位,利用倾斜构图制造压迫感。
  8464. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8465. 背景音效:
  8466. \n\n";
  8467. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8468. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  8469. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  8470. $prompt = $origin_prompt;
  8471. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  8472. // 获取章节内容
  8473. $full_content = getProp($anime, 'content');
  8474. if ($uploaded_content) {
  8475. $full_content = $uploaded_content;
  8476. }
  8477. // 根据章节内容拆分章节
  8478. $chapters = splitContent($full_content);
  8479. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  8480. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  8481. $messages = [];
  8482. if ($prompt == '确认分镜大纲') {
  8483. // 暂时保留
  8484. $content = $chapter_content;
  8485. if ($is_single) $content = $full_content; // 单剧集使用全文
  8486. if (!$content) {
  8487. Utils::throwError('20003:章节内容无法获取,请确认');
  8488. }
  8489. $question = $is_single
  8490. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  8491. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  8492. // 构建消息
  8493. $messages[] =
  8494. [
  8495. 'role' => 'user',
  8496. 'content' => $question
  8497. ];
  8498. }else if ($prompt == '继续策划下一集') {
  8499. if ($is_single) {
  8500. Utils::throwError('20003:单剧集不支持继续策划下一集');
  8501. }
  8502. $content = $chapter_content;
  8503. if (!$content) {
  8504. Utils::throwError('20003:章节内容无法获取,请确认');
  8505. }
  8506. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  8507. // 获取上一集最后记录
  8508. $prev_sequence = $episode_number - 1;
  8509. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  8510. // 构建消息
  8511. $messages[] =
  8512. [
  8513. 'role' => 'user',
  8514. 'content' => $question
  8515. ];
  8516. // dd($messages);
  8517. }else {
  8518. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  8519. if (!$content) {
  8520. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  8521. }
  8522. if (!$content) {
  8523. Utils::throwError('20003:章节内容无法获取,请确认');
  8524. }
  8525. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  8526. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  8527. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  8528. if ($origin_prompt) {
  8529. $question .= "本次修改要求如下:\n{$origin_prompt}";
  8530. }
  8531. $messages[] =
  8532. [
  8533. 'role' => 'user',
  8534. 'content' => $question
  8535. ];
  8536. }
  8537. // 处理文本模型
  8538. $model = getProp($data, 'model');
  8539. if (!$model) {
  8540. // 用户没有输入,从anime表获取
  8541. $model = getProp($anime, 'model');
  8542. if (!$model) {
  8543. // anime表也没有,使用默认值
  8544. $model = 'deepseek-v4-pro';
  8545. }
  8546. }
  8547. // 验证模型是否在可用模型表中
  8548. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8549. $model = 'deepseek-v4-pro';
  8550. }
  8551. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8552. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8553. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8554. if ($model === 'deepseek-chat') {
  8555. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8556. $model = 'deepseek-v4-flash';
  8557. $thinkingMode = 'disabled';
  8558. } elseif ($model === 'deepseek-reasoner') {
  8559. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8560. $model = 'deepseek-v4-flash';
  8561. $thinkingMode = 'enabled';
  8562. }
  8563. $post_data = [
  8564. 'model' => $model,
  8565. 'messages' => $messages,
  8566. // 'max_tokens' => 8192,
  8567. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8568. 'frequency_penalty' => 0,
  8569. 'presence_penalty' => 0,
  8570. 'response_format' => ['type' => 'text'],
  8571. 'thinking' => ['type' => $thinkingMode],
  8572. 'stream' => true // 启用流式输出
  8573. ];
  8574. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8575. // 根据模型类型选择调用方法
  8576. $fullContent = '';
  8577. $fullReasoningContent = '';
  8578. $usage = [];
  8579. try {
  8580. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8581. // DeepSeek 官方模型使用 DeepSeek API
  8582. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8583. } else if (in_array($model, $this->gpt_text_models)) {
  8584. // GPT-5.4 模型使用 TokenRouter API
  8585. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8586. } else if (in_array($model, $this->gemini_text_models)) {
  8587. // Gemini 模型使用 Gemini API
  8588. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8589. } else {
  8590. // 其他模型使用火山引擎API
  8591. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8592. }
  8593. // 验证返回值类型
  8594. if (!is_iterable($streamGenerator)) {
  8595. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8596. dLog('deepseek')->error('chat流式生成器无效', [
  8597. 'generator_type' => $errorType,
  8598. 'model' => $model,
  8599. 'anime_id' => $anime_id,
  8600. 'episode_number' => $episode_number
  8601. ]);
  8602. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  8603. 'type' => $errorType,
  8604. 'model' => $model
  8605. ]);
  8606. yield [
  8607. 'type' => 'error',
  8608. 'episode' => [],
  8609. 'answer' => '',
  8610. 'reasoning' => '',
  8611. 'usage' => [],
  8612. 'error' => '接口返回数据异常,请重新请求'
  8613. ];
  8614. return;
  8615. }
  8616. // 处理流式输出
  8617. foreach ($streamGenerator as $chunk) {
  8618. if (isset($chunk['type'])) {
  8619. if ($chunk['type'] === 'done') {
  8620. // 最终结果
  8621. $fullContent = $chunk['full_content'];
  8622. $fullReasoningContent = $chunk['full_reasoning'];
  8623. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8624. } else {
  8625. // 逐块yield数据
  8626. yield $chunk;
  8627. }
  8628. }
  8629. }
  8630. } catch (\Exception $e) {
  8631. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  8632. 'model' => $model,
  8633. 'anime_id' => $anime_id,
  8634. 'episode_number' => $episode_number,
  8635. 'trace' => $e->getTraceAsString()
  8636. ]);
  8637. logDB('deepseek', 'error', 'chat流式处理失败', [
  8638. 'error' => $e->getMessage(),
  8639. 'model' => $model
  8640. ]);
  8641. yield [
  8642. 'type' => 'error',
  8643. 'episode' => [],
  8644. 'answer' => '',
  8645. 'reasoning' => '',
  8646. 'usage' => [],
  8647. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8648. ];
  8649. return;
  8650. }
  8651. dLog('deepseek')->info('完整内容: '.$fullContent);
  8652. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8653. // 处理完整内容并返回最终结果
  8654. $episode_arr = handleEpisodeContentForAce($fullContent);
  8655. logDB('deepseek', 'info', '解析内容', $episode_arr);
  8656. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  8657. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8658. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8659. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  8660. // }
  8661. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  8662. $max_retries = 3;
  8663. $retry_count = 0;
  8664. $validation_failed = false;
  8665. $validation_error_msg = '';
  8666. // 验证生成的内容
  8667. if ($anime_script_id) {
  8668. // 检查是否有acts数据
  8669. if (empty($episode_arr['acts'])) {
  8670. $validation_failed = true;
  8671. $validation_error_msg = '未生成分镜剧本相关的内容';
  8672. } else {
  8673. // 仅当存在强制主体设定时校验主体列表
  8674. if (!empty($extra_roles)) {
  8675. $generated_roles = array_column($episode_arr['roles'], 'role');
  8676. // 过滤掉"旁白"角色
  8677. $generated_roles = array_filter($generated_roles, function($role) {
  8678. return $role !== '旁白';
  8679. });
  8680. $expected_roles = array_keys($extra_roles);
  8681. // 找出生成的主体中不在预期列表中的主体
  8682. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8683. if (!empty($invalid_roles)) {
  8684. $validation_failed = true;
  8685. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8686. }
  8687. }
  8688. // 仅当存在强制场景设定时校验场景列表
  8689. if (!$validation_failed && !empty($extra_scenes)) {
  8690. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8691. $expected_scenes = array_keys($extra_scenes);
  8692. // 找出生成的场景中不在预期列表中的场景
  8693. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8694. if (!empty($invalid_scenes)) {
  8695. $validation_failed = true;
  8696. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8697. }
  8698. }
  8699. // 仅当存在强制道具设定时校验道具列表
  8700. if (!$validation_failed && !empty($extra_props)) {
  8701. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8702. $expected_props = array_keys($extra_props);
  8703. // 找出生成的道具中不在预期列表中的道具
  8704. $invalid_props = array_diff($generated_props, $expected_props);
  8705. if (!empty($invalid_props)) {
  8706. $validation_failed = true;
  8707. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8708. }
  8709. }
  8710. }
  8711. } else {
  8712. // 如果没有anime_script_id,只检查是否有acts数据
  8713. if (empty($episode_arr['acts'])) {
  8714. $validation_failed = true;
  8715. $validation_error_msg = '未生成分镜剧本相关的内容';
  8716. }
  8717. }
  8718. // 重试逻辑
  8719. while ($validation_failed && $retry_count < $max_retries) {
  8720. $retry_count++;
  8721. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8722. 'reason' => $validation_error_msg,
  8723. 'anime_id' => $anime_id,
  8724. 'episode_number' => $episode_number
  8725. ]);
  8726. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8727. 'reason' => $validation_error_msg,
  8728. 'anime_id' => $anime_id
  8729. ]);
  8730. // 发送流式重试提示
  8731. yield [
  8732. 'type' => 'retry',
  8733. 'retry_count' => $retry_count,
  8734. 'reason' => $validation_error_msg
  8735. ];
  8736. // 构建重试提示词
  8737. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8738. if ($anime_script_id) {
  8739. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8740. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8741. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  8742. } else {
  8743. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  8744. }
  8745. // 添加重试消息到messages
  8746. $messages[] = [
  8747. 'role' => 'assistant',
  8748. 'content' => $fullContent
  8749. ];
  8750. $messages[] = [
  8751. 'role' => 'user',
  8752. 'content' => $retry_prompt
  8753. ];
  8754. // 更新post_data的messages
  8755. $post_data['messages'] = $messages;
  8756. // 重新调用API
  8757. try {
  8758. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8759. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8760. } else if (in_array($model, $this->gpt_text_models)) {
  8761. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8762. } else if (in_array($model, $this->gemini_text_models)) {
  8763. // Gemini 模型使用 Gemini API
  8764. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8765. } else {
  8766. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8767. }
  8768. // 处理流式输出
  8769. $fullContent = '';
  8770. $fullReasoningContent = '';
  8771. foreach ($streamGenerator as $chunk) {
  8772. if (isset($chunk['type'])) {
  8773. if ($chunk['type'] === 'done') {
  8774. $fullContent = $chunk['full_content'];
  8775. $fullReasoningContent = $chunk['full_reasoning'];
  8776. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8777. } else {
  8778. yield $chunk;
  8779. }
  8780. }
  8781. }
  8782. // 重新解析内容
  8783. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8784. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8785. $episode_arr = handleEpisodeContentForAce($fullContent);
  8786. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8787. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8788. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8789. // }
  8790. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  8791. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  8792. // 重新验证
  8793. $validation_failed = false;
  8794. $validation_error_msg = '';
  8795. if ($anime_script_id) {
  8796. if (empty($episode_arr['acts'])) {
  8797. $validation_failed = true;
  8798. $validation_error_msg = '未生成分镜剧本相关的内容';
  8799. } else {
  8800. // 仅当存在强制主体设定时校验主体列表
  8801. if (!empty($extra_roles)) {
  8802. $generated_roles = array_column($episode_arr['roles'], 'role');
  8803. // 过滤掉"旁白"角色
  8804. $generated_roles = array_filter($generated_roles, function($role) {
  8805. return $role !== '旁白';
  8806. });
  8807. $expected_roles = array_keys($extra_roles);
  8808. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8809. if (!empty($invalid_roles)) {
  8810. $validation_failed = true;
  8811. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8812. }
  8813. }
  8814. // 仅当存在强制场景设定时校验场景列表
  8815. if (!$validation_failed && !empty($extra_scenes)) {
  8816. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8817. $expected_scenes = array_keys($extra_scenes);
  8818. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8819. if (!empty($invalid_scenes)) {
  8820. $validation_failed = true;
  8821. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8822. }
  8823. }
  8824. // 仅当存在强制道具设定时校验道具列表
  8825. if (!$validation_failed && !empty($extra_props)) {
  8826. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8827. $expected_props = array_keys($extra_props);
  8828. $invalid_props = array_diff($generated_props, $expected_props);
  8829. if (!empty($invalid_props)) {
  8830. $validation_failed = true;
  8831. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8832. }
  8833. }
  8834. }
  8835. } else {
  8836. if (empty($episode_arr['acts'])) {
  8837. $validation_failed = true;
  8838. $validation_error_msg = '未生成分镜剧本相关的内容';
  8839. }
  8840. }
  8841. } catch (\Exception $e) {
  8842. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8843. 'trace' => $e->getTraceAsString()
  8844. ]);
  8845. break;
  8846. }
  8847. }
  8848. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  8849. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  8850. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  8851. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  8852. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  8853. if ($validation_failed && $retry_count >= $max_retries) {
  8854. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8855. 'retry_count' => $retry_count,
  8856. 'last_error' => $validation_error_msg
  8857. ]);
  8858. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8859. 'error' => $validation_error_msg,
  8860. 'anime_id' => $anime_id
  8861. ]);
  8862. $validation_failed = false;
  8863. $validation_error_msg = '';
  8864. }
  8865. // 如果重试后仍然失败
  8866. if ($validation_failed) {
  8867. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8868. 'retry_count' => $retry_count,
  8869. 'last_error' => $validation_error_msg
  8870. ]);
  8871. try {
  8872. $now = date('Y-m-d H:i:s');
  8873. $records = [
  8874. [
  8875. 'uid' => $uid,
  8876. 'anime_id' => $anime_id,
  8877. 'sequence' => $episode_number,
  8878. 'role' => 'user',
  8879. 'content' => $prompt,
  8880. 'created_at' => $now,
  8881. 'updated_at' => $now
  8882. ],
  8883. [
  8884. 'uid' => $uid,
  8885. 'anime_id' => $anime_id,
  8886. 'sequence' => $episode_number,
  8887. 'role' => 'assistant',
  8888. 'content' => $fullContent,
  8889. 'created_at' => $now,
  8890. 'updated_at' => $now
  8891. ]
  8892. ];
  8893. DB::table('mp_anime_records')->insert($records);
  8894. } catch (\Exception $e) {
  8895. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8896. }
  8897. yield [
  8898. 'type' => 'done',
  8899. 'episode' => [],
  8900. 'answer' => $fullContent,
  8901. 'reasoning' => $fullReasoningContent,
  8902. 'usage' => $usage,
  8903. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8904. ];
  8905. return;
  8906. }
  8907. // 验证成功,记录日志
  8908. if ($retry_count > 0) {
  8909. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8910. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8911. }
  8912. // 老逻辑
  8913. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8914. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8915. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8916. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8917. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8918. $existing_props = is_array($existing_props) ? $existing_props : [];
  8919. $now = date('Y-m-d H:i:s');
  8920. try {
  8921. DB::beginTransaction();
  8922. $saveResult = $this->saveEpisodeVersionData(
  8923. $anime_id,
  8924. $episode_number,
  8925. $episode_arr,
  8926. $existing_roles,
  8927. $existing_scenes,
  8928. $existing_props,
  8929. $current_episode,
  8930. $base_episode,
  8931. $is_regenerate_version,
  8932. $content,
  8933. $now,
  8934. $ref_products
  8935. );
  8936. $episode = $saveResult['episode'];
  8937. $episode_id = $saveResult['episode_id'];
  8938. $merged_roles = $saveResult['merged_roles'];
  8939. $merged_scenes = $saveResult['merged_scenes'];
  8940. $merged_props = $saveResult['merged_props'];
  8941. $record_content = $origin_prompt;
  8942. if ($uploaded_content !== '') {
  8943. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8944. }
  8945. $records = [
  8946. [
  8947. 'uid' => $uid,
  8948. 'anime_id' => $anime_id,
  8949. 'role' => 'user',
  8950. 'content' => $record_content,
  8951. 'sequence' => $episode_number,
  8952. 'episode_id' => $episode_id,
  8953. 'created_at' => $now,
  8954. 'updated_at' => $now
  8955. ],
  8956. [
  8957. 'uid' => $uid,
  8958. 'anime_id' => $anime_id,
  8959. 'role' => 'assistant',
  8960. 'content' => $fullContent,
  8961. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8962. 'sequence' => $episode_number,
  8963. 'episode_id' => $episode_id,
  8964. 'created_at' => $now,
  8965. 'updated_at' => $now
  8966. ]
  8967. ];
  8968. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8969. if (!$boolen4) {
  8970. Utils::throwError('20003:对话记录保存失败');
  8971. }
  8972. // 保存模型到anime表
  8973. $update_anime_data = [
  8974. 'model' => $model,
  8975. 'updated_at' => $now
  8976. ];
  8977. if ($uploaded_content) {
  8978. $update_anime_data['content'] = $uploaded_content;
  8979. }
  8980. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8981. }catch (\Exception $e) {
  8982. DB::rollBack();
  8983. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8984. yield [
  8985. 'type' => 'done',
  8986. 'answer' => $fullContent,
  8987. 'reasoning' => $fullReasoningContent,
  8988. 'usage' => $usage,
  8989. 'error' => $e->getMessage(),
  8990. ];
  8991. return;
  8992. }
  8993. DB::commit();
  8994. if ($is_global_generate_pics) {
  8995. // // 批量生成全局角色图片
  8996. // $this->batchSetGlobalRoleImg([
  8997. // 'anime_id' => $anime_id,
  8998. // ], true);
  8999. // // 批量生成全局场景图片
  9000. // $this->batchSetGlobalSceneImg([
  9001. // 'anime_id' => $anime_id,
  9002. // ], true);
  9003. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9004. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9005. }
  9006. $episode['episode_id'] = $episode_id;
  9007. $episode['roles'] = $merged_roles;
  9008. $episode['scenes'] = $merged_scenes;
  9009. $episode['props'] = $merged_props;
  9010. $episode['end_episode_sequence'] = $end_episode_sequence;
  9011. // 获取mp_animes表中的视频参数
  9012. $episode['video_params'] = [
  9013. 'video_model' => getProp($anime, 'video_model'),
  9014. 'video_resolution' => getProp($anime, 'video_resolution'),
  9015. 'ratio' => getProp($anime, 'video_ratio'),
  9016. ];
  9017. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9018. yield [
  9019. 'type' => 'done',
  9020. 'episode' => $episode,
  9021. 'answer' => $fullContent,
  9022. 'reasoning' => $fullReasoningContent,
  9023. 'usage' => $usage
  9024. ];
  9025. }
  9026. /**
  9027. * chatForAce的非流式版本 - 用于定时任务
  9028. * 只获取最终 type=done 的数据,并验证必要字段
  9029. *
  9030. * @param array $data 请求数据
  9031. * @return array 生成结果
  9032. */
  9033. public function chatForAceNonStream($data) {
  9034. $finalResult = null;
  9035. // 调用流式方法,只保存 type=done 的数据
  9036. foreach ($this->chatForAce($data) as $chunk) {
  9037. // 只关注最终结果
  9038. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9039. $finalResult = $chunk;
  9040. break; // 找到 done 就退出循环
  9041. }
  9042. }
  9043. // 验证最终结果
  9044. if (!$finalResult) {
  9045. return ['error' => '生成失败:未获取到最终结果'];
  9046. }
  9047. // 检查是否有错误
  9048. if (isset($finalResult['error']) && $finalResult['error']) {
  9049. return $finalResult;
  9050. }
  9051. // 验证必要字段
  9052. $episode = $finalResult['episode'] ?? [];
  9053. // 验证 roles
  9054. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9055. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9056. }
  9057. // 验证 scenes
  9058. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9059. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9060. }
  9061. // 验证 props(道具可以为空,但必须存在且为数组)
  9062. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9063. $episode['props'] = [];
  9064. }
  9065. // 验证 acts(分镜剧本)
  9066. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9067. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9068. }
  9069. // 更新验证后的 episode 数据
  9070. $finalResult['episode'] = $episode;
  9071. // 记录验证成功日志
  9072. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9073. 'roles_count' => count($episode['roles']),
  9074. 'scenes_count' => count($episode['scenes']),
  9075. 'props_count' => count($episode['props']),
  9076. 'acts_count' => count($episode['acts'])
  9077. ]);
  9078. return $finalResult;
  9079. }
  9080. /**
  9081. * 批量生成多个分集
  9082. *
  9083. * @param array $data 请求数据
  9084. * @return array 任务信息
  9085. */
  9086. public function batchGenerateEpisodes($data) {
  9087. $uid = Site::getUid();
  9088. $cpid = Site::getCpid();
  9089. $anime_id = getProp($data, 'anime_id');
  9090. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9091. if (!$anime_id) {
  9092. Utils::throwError('20003:anime_id参数缺失');
  9093. }
  9094. if ($generate_episode_number < 1) {
  9095. Utils::throwError('20003:生成集数必须大于0');
  9096. }
  9097. // 获取动漫信息
  9098. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9099. if (!$anime) {
  9100. Utils::throwError('20003:该剧集不存在');
  9101. }
  9102. // 检查是否是全能模式
  9103. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9104. Utils::throwError('20003:只有全能模式才支持批量生成');
  9105. }
  9106. // 检查是否是多剧集模式
  9107. if ((int)getProp($anime, 'is_multi') !== 1) {
  9108. Utils::throwError('20003:单剧集不支持批量生成');
  9109. }
  9110. // 获取当前已生成的最大集数
  9111. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9112. ->where('anime_id', $anime_id)
  9113. ->where('is_default', 1)
  9114. ->max('episode_number');
  9115. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9116. // 确定起始集数
  9117. $startEpisodeNumber = $currentMaxEpisode + 1;
  9118. // 计算结束集数
  9119. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9120. // 检查是否超过总集数限制
  9121. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9122. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9123. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9124. }
  9125. $now = date('Y-m-d H:i:s');
  9126. $createdTasks = [];
  9127. $skippedTasks = [];
  9128. // 为每一集创建详情记录
  9129. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9130. // 检查是否已有该集的任务记录
  9131. $existingTask = DB::table('mp_batch_episode_generation_details')
  9132. ->where('anime_id', $anime_id)
  9133. ->where('episode_number', $episodeNumber)
  9134. ->first();
  9135. if ($existingTask) {
  9136. // 如果已存在且未完成,跳过
  9137. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9138. $skippedTasks[] = $episodeNumber;
  9139. continue;
  9140. }
  9141. // 如果是失败状态,可以重新创建(删除旧记录)
  9142. if ($existingTask->status === 'failed') {
  9143. DB::table('mp_batch_episode_generation_details')
  9144. ->where('id', $existingTask->id)
  9145. ->delete();
  9146. }
  9147. // 如果是已完成状态,也跳过
  9148. if ($existingTask->status === 'completed') {
  9149. $skippedTasks[] = $episodeNumber;
  9150. continue;
  9151. }
  9152. }
  9153. // 准备任务数据
  9154. $taskData = [
  9155. 'anime_id' => $anime_id,
  9156. 'uid' => $uid,
  9157. 'cpid' => $cpid,
  9158. 'episode_number' => $episodeNumber,
  9159. 'status' => 'pending',
  9160. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9161. 'retry_count' => 0,
  9162. 'created_at' => $now,
  9163. 'updated_at' => $now
  9164. ];
  9165. // 创建任务记录
  9166. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9167. if ($taskId) {
  9168. $createdTasks[] = $episodeNumber;
  9169. }
  9170. }
  9171. if (empty($createdTasks)) {
  9172. if (!empty($skippedTasks)) {
  9173. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9174. } else {
  9175. Utils::throwError('20003:创建批量生成任务失败');
  9176. }
  9177. }
  9178. return [
  9179. 'anime_id' => $anime_id,
  9180. 'start_episode' => $startEpisodeNumber,
  9181. 'end_episode' => $endEpisodeNumber,
  9182. 'total_episodes' => $generate_episode_number,
  9183. 'created_episodes' => $createdTasks,
  9184. 'skipped_episodes' => $skippedTasks,
  9185. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9186. "已创建: " . implode(',', $createdTasks) .
  9187. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9188. ];
  9189. }
  9190. /**
  9191. * 获取批量生成任务状态
  9192. *
  9193. * @param array $data 请求数据
  9194. * @return array 任务状态信息
  9195. */
  9196. public function getBatchGenerationTaskStatus($data) {
  9197. $anime_id = getProp($data, 'anime_id');
  9198. if (!$anime_id) {
  9199. Utils::throwError('20003:anime_id参数缺失');
  9200. }
  9201. // 获取该anime的所有任务
  9202. $tasks = DB::table('mp_batch_episode_generation_details')
  9203. ->where('anime_id', $anime_id)
  9204. ->orderBy('episode_number')
  9205. ->get()
  9206. ->map(function($item) {
  9207. return [
  9208. 'id' => $item->id,
  9209. 'episode_number' => $item->episode_number,
  9210. 'status' => $item->status,
  9211. 'error_message' => $item->error_message,
  9212. 'retry_count' => $item->retry_count,
  9213. 'created_at' => $item->created_at,
  9214. 'updated_at' => $item->updated_at,
  9215. 'completed_at' => $item->completed_at
  9216. ];
  9217. })
  9218. ->toArray();
  9219. if (empty($tasks)) {
  9220. Utils::throwError('20003:该剧集没有批量生成任务');
  9221. }
  9222. // 统计各状态数量
  9223. $totalCount = count($tasks);
  9224. $pendingCount = 0;
  9225. $processingCount = 0;
  9226. $completedCount = 0;
  9227. $failedCount = 0;
  9228. foreach ($tasks as $task) {
  9229. switch ($task['status']) {
  9230. case 'pending':
  9231. $pendingCount++;
  9232. break;
  9233. case 'processing':
  9234. $processingCount++;
  9235. break;
  9236. case 'completed':
  9237. $completedCount++;
  9238. break;
  9239. case 'failed':
  9240. $failedCount++;
  9241. break;
  9242. }
  9243. }
  9244. // 计算进度百分比
  9245. $progress = 0;
  9246. if ($totalCount > 0) {
  9247. $progress = round(($completedCount / $totalCount) * 100, 2);
  9248. }
  9249. // 判断整体状态
  9250. $overallStatus = 'processing';
  9251. if ($completedCount === $totalCount) {
  9252. $overallStatus = 'completed';
  9253. } elseif ($pendingCount === $totalCount) {
  9254. $overallStatus = 'pending';
  9255. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  9256. $overallStatus = 'failed';
  9257. }
  9258. return [
  9259. 'anime_id' => $anime_id,
  9260. 'total_episodes' => $totalCount,
  9261. 'pending_count' => $pendingCount,
  9262. 'processing_count' => $processingCount,
  9263. 'completed_count' => $completedCount,
  9264. 'failed_count' => $failedCount,
  9265. 'progress' => $progress,
  9266. 'overall_status' => $overallStatus,
  9267. 'tasks' => $tasks
  9268. ];
  9269. }
  9270. /**
  9271. * 将生成内容中不在强制列表中的资源合并进强制列表
  9272. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  9273. *
  9274. * @param array $generated 生成内容中的资源列表
  9275. * @param array $forced 强制资源列表(key为资源名称)
  9276. * @param string $type 资源类型:role、scene、prop
  9277. * @return array
  9278. */
  9279. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  9280. {
  9281. foreach ($generated as $item) {
  9282. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  9283. if ($name === null || $name === '') {
  9284. continue;
  9285. }
  9286. if ($name === '旁白') {
  9287. continue;
  9288. }
  9289. if (!isset($forced[$name])) {
  9290. $forced[$name] = $item;
  9291. }
  9292. }
  9293. return $forced;
  9294. }
  9295. /**
  9296. * 智能匹配并替换主体和场景名称
  9297. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  9298. *
  9299. * @param array $episode_arr 解析后的剧集数据
  9300. * @param array $extra_roles 强制主体设定(key为主体名称)
  9301. * @param array $extra_scenes 强制场景设定(key为场景名称)
  9302. * @return array 替换后的剧集数据
  9303. */
  9304. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  9305. $replaced_count = 0;
  9306. // 1. 处理主体列表
  9307. if (!empty($episode_arr['roles'])) {
  9308. foreach ($episode_arr['roles'] as &$role) {
  9309. $generated_role_name = $role['role'] ?? '';
  9310. // 跳过旁白
  9311. if ($generated_role_name === '旁白') {
  9312. continue;
  9313. }
  9314. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  9315. if (!isset($extra_roles[$generated_role_name])) {
  9316. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  9317. if ($matched_role) {
  9318. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  9319. $role['role'] = $matched_role;
  9320. $replaced_count++;
  9321. }
  9322. }
  9323. }
  9324. }
  9325. // 2. 处理场景列表
  9326. if (!empty($episode_arr['scenes'])) {
  9327. foreach ($episode_arr['scenes'] as &$scene) {
  9328. $generated_scene_name = $scene['scene'] ?? '';
  9329. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  9330. if (!isset($extra_scenes[$generated_scene_name])) {
  9331. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  9332. if ($matched_scene) {
  9333. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  9334. $scene['scene'] = $matched_scene;
  9335. $replaced_count++;
  9336. }
  9337. }
  9338. }
  9339. }
  9340. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  9341. if (!empty($episode_arr['acts'])) {
  9342. foreach ($episode_arr['acts'] as &$act) {
  9343. if (!empty($act['segments'])) {
  9344. foreach ($act['segments'] as &$segment) {
  9345. if (!empty($segment['segment_content'])) {
  9346. $original_content = $segment['segment_content'];
  9347. $replaced_content = $original_content;
  9348. // 替换场景名 - 在文本中查找并替换
  9349. foreach (array_keys($extra_scenes) as $full_scene_name) {
  9350. // 尝试找到可能的短名称
  9351. $potential_short_names = [];
  9352. // 提取场景名的主要部分(冒号之前)
  9353. if (mb_strpos($full_scene_name, ':') !== false) {
  9354. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9355. $potential_short_names[] = $short_name;
  9356. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  9357. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9358. $potential_short_names[] = $short_name;
  9359. }
  9360. // 替换场景字段中的短名称
  9361. foreach ($potential_short_names as $short_name) {
  9362. if ($short_name !== $full_scene_name) {
  9363. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  9364. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  9365. if ($new_content !== $replaced_content) {
  9366. $replaced_content = $new_content;
  9367. $replaced_count++;
  9368. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  9369. }
  9370. }
  9371. }
  9372. }
  9373. // 替换配音角色名(跳过旁白)
  9374. foreach (array_keys($extra_roles) as $full_role_name) {
  9375. if ($full_role_name === '旁白') {
  9376. continue;
  9377. }
  9378. // 尝试找到可能的短名称
  9379. $potential_short_names = [];
  9380. // 提取角色名的主要部分(短横线之前)
  9381. if (mb_strpos($full_role_name, '-') !== false) {
  9382. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  9383. $potential_short_names[] = $short_name;
  9384. }
  9385. // 替换配音台词中的短名称
  9386. foreach ($potential_short_names as $short_name) {
  9387. if ($short_name !== $full_role_name) {
  9388. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  9389. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  9390. if ($new_content !== $replaced_content) {
  9391. $replaced_content = $new_content;
  9392. $replaced_count++;
  9393. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  9394. }
  9395. }
  9396. }
  9397. }
  9398. // 如果有替换,更新segment_content
  9399. if ($replaced_content !== $original_content) {
  9400. $segment['segment_content'] = $replaced_content;
  9401. }
  9402. }
  9403. }
  9404. }
  9405. }
  9406. }
  9407. if ($replaced_count > 0) {
  9408. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  9409. 'replaced_count' => $replaced_count
  9410. ]);
  9411. }
  9412. return $episode_arr;
  9413. }
  9414. /**
  9415. * 查找匹配的名称
  9416. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  9417. *
  9418. * @param string $generated_name 生成的名称
  9419. * @param array $expected_names 预期的名称列表
  9420. * @return string|null 匹配到的名称,如果没有匹配则返回null
  9421. */
  9422. private function findMatchingName($generated_name, $expected_names) {
  9423. if (empty($generated_name)) {
  9424. return null;
  9425. }
  9426. // 尝试精确匹配
  9427. if (in_array($generated_name, $expected_names)) {
  9428. return $generated_name;
  9429. }
  9430. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  9431. foreach ($expected_names as $expected_name) {
  9432. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  9433. if (mb_strpos($expected_name, $generated_name) === 0) {
  9434. return $expected_name;
  9435. }
  9436. }
  9437. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  9438. // 这样可以处理一些变体,但优先级较低
  9439. foreach ($expected_names as $expected_name) {
  9440. if (mb_strpos($expected_name, $generated_name) !== false) {
  9441. return $expected_name;
  9442. }
  9443. }
  9444. return null;
  9445. }
  9446. /**
  9447. * 重新生成分段剧本
  9448. * @param array $data 包含以下字段:
  9449. * - prompt: string|null 用户修改要求(可选)
  9450. * - template_id: int|null 提示词模板ID(可选)
  9451. * - act_id: int|null 单个片段ID(与episode_id二选一)
  9452. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  9453. * @return array 返回生成结果
  9454. */
  9455. public function regenerateSegmentScript($data) {
  9456. $uid = Site::getUid();
  9457. $prompt = trim((string)getProp($data, 'prompt', ''));
  9458. $template_id = getProp($data, 'template_id', 0);
  9459. $act_id = getProp($data, 'act_id', 0);
  9460. $episode_id = getProp($data, 'episode_id', 0);
  9461. // 验证:prompt和template_id至少提供一个
  9462. if (empty($prompt) && empty($template_id)) {
  9463. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  9464. }
  9465. // 验证:act_id和episode_id二选一
  9466. if (empty($act_id) && empty($episode_id)) {
  9467. Utils::throwError('20003:请提供片段ID或剧集ID');
  9468. }
  9469. if (!empty($act_id) && !empty($episode_id)) {
  9470. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  9471. }
  9472. // 如果提供了template_id,获取模板提示词
  9473. $template_prompt = '';
  9474. if ($template_id > 0) {
  9475. $template = DB::table('mp_prompt_templates')
  9476. ->where('id', $template_id)
  9477. ->where('is_deleted', 0)
  9478. ->first();
  9479. if (!$template) {
  9480. Utils::throwError('20003:提示词模板不存在或已删除');
  9481. }
  9482. $template_prompt = $template->template_prompt ?? '';
  9483. }
  9484. // 合并用户提示词和模板提示词
  9485. $final_prompt = '';
  9486. if (!empty($template_prompt)) {
  9487. $final_prompt = $template_prompt;
  9488. if (!empty($prompt)) {
  9489. $final_prompt .= "\n\n补充要求:" . $prompt;
  9490. }
  9491. } else {
  9492. $final_prompt = $prompt;
  9493. }
  9494. // 获取需要重新生成的内容参考
  9495. $reference_content = '';
  9496. $target_episode_id = 0;
  9497. $target_anime_id = 0;
  9498. $target_episode_number = 0;
  9499. if ($act_id > 0) {
  9500. // 单个片段模式:获取该片段的内容
  9501. $segment = DB::table('mp_episode_segments')
  9502. ->where('id', $act_id)
  9503. ->first();
  9504. if (!$segment) {
  9505. Utils::throwError('20003:片段不存在');
  9506. }
  9507. $target_episode_id = $segment->episode_id;
  9508. $target_anime_id = $segment->anime_id;
  9509. $target_episode_number = $segment->episode_number;
  9510. $reference_content = $segment->act_content ?? '';
  9511. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9512. } else {
  9513. // 整个剧集模式:获取所有片段的内容
  9514. $segments = DB::table('mp_episode_segments')
  9515. ->where('episode_id', $episode_id)
  9516. ->orderBy('act_number')
  9517. ->get();
  9518. if ($segments->isEmpty()) {
  9519. Utils::throwError('20003:该剧集没有片段数据');
  9520. }
  9521. $target_episode_id = $episode_id;
  9522. $target_anime_id = $segments[0]->anime_id;
  9523. $target_episode_number = $segments[0]->episode_number;
  9524. // 拼接所有片段内容,保留格式用于AI理解
  9525. $act_contents = [];
  9526. foreach ($segments as $seg) {
  9527. $act_number = $seg->act_number;
  9528. $act_content = $seg->act_content ?? '';
  9529. if (!empty($act_content)) {
  9530. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  9531. }
  9532. }
  9533. $reference_content = implode("\n\n", $act_contents);
  9534. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  9535. if ($episode_content) {
  9536. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  9537. }else {
  9538. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9539. }
  9540. }
  9541. if (empty($reference_content)) {
  9542. Utils::throwError('20003:没有可参考的片段内容');
  9543. }
  9544. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  9545. $episode = DB::table('mp_anime_episodes')
  9546. ->where('id', $target_episode_id)
  9547. ->first();
  9548. if (!$episode) {
  9549. Utils::throwError('20003:剧集不存在');
  9550. }
  9551. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  9552. $anime_script_id = getProp($anime, 'script_id');
  9553. $intro = $episode->intro ?? '';
  9554. $art_style = $episode->art_style ?? '';
  9555. $roles = json_decode($episode->roles ?? '[]', true);
  9556. $scenes = json_decode($episode->scenes ?? '[]', true);
  9557. $props = json_decode($episode->props ?? '[]', true);
  9558. // 构建提示词中的主体列表和场景列表参考
  9559. $roles_ref = '';
  9560. if (!empty($roles) && is_array($roles)) {
  9561. $roles_list = [];
  9562. foreach ($roles as $role) {
  9563. $role_name = getProp($role, 'role', '');
  9564. $role_desc = getProp($role, 'description', '');
  9565. $pic_prompt = getProp($role, 'pic_prompt', '');
  9566. $voice_prompt = getProp($role, 'voice_prompt', '');
  9567. if (!empty($role_name)) {
  9568. $role_line = $role_name;
  9569. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  9570. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  9571. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  9572. $roles_list[] = $role_line;
  9573. }
  9574. }
  9575. if (!empty($roles_list)) {
  9576. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  9577. }
  9578. }
  9579. $scenes_ref = '';
  9580. if (!empty($scenes) && is_array($scenes)) {
  9581. $scenes_list = [];
  9582. foreach ($scenes as $scene) {
  9583. $scene_name = getProp($scene, 'scene', '');
  9584. $scene_desc = getProp($scene, 'description', '');
  9585. $pic_prompt = getProp($scene, 'pic_prompt', '');
  9586. if (!empty($scene_name)) {
  9587. $scene_line = $scene_name;
  9588. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  9589. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  9590. $scenes_list[] = $scene_line;
  9591. }
  9592. }
  9593. if (!empty($scenes_list)) {
  9594. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  9595. }
  9596. }
  9597. $props_ref = '';
  9598. if (!empty($props) && is_array($props)) {
  9599. $props_list = [];
  9600. foreach ($props as $prop) {
  9601. $prop_name = getProp($prop, 'prop', '');
  9602. $prop_desc = getProp($prop, 'description', '');
  9603. $pic_prompt = getProp($prop, 'pic_prompt', '');
  9604. if (!empty($prop_name)) {
  9605. $prop_line = $prop_name;
  9606. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  9607. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  9608. $props_list[] = $prop_line;
  9609. }
  9610. }
  9611. if (!empty($props_list)) {
  9612. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  9613. }
  9614. }
  9615. // 构建美术风格参考
  9616. $art_style_ref = '';
  9617. if (!empty($art_style)) {
  9618. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  9619. }
  9620. // 构建内容简介参考
  9621. $intro_ref = '';
  9622. if (!empty($intro)) {
  9623. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  9624. }
  9625. // 构建完整的AI提示词
  9626. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  9627. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  9628. $user_prompt .= $intro_ref;
  9629. $user_prompt .= $art_style_ref;
  9630. $user_prompt .= $reference_content;
  9631. // $user_prompt .= $roles_ref;
  9632. // $user_prompt .= $scenes_ref;
  9633. $system_prompt = "\n\n【强制要求】\n";
  9634. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  9635. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  9636. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  9637. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  9638. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  9639. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  9640. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  9641. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  9642. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  9643. ###分段剧本
  9644. 片段数量:8
  9645. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9646. ##片段1
  9647. 时长:12s
  9648. 分镜1
  9649. 出场角色:刀疤脸
  9650. 场景:边境小镇街道
  9651. 出场道具:酒杯-高脚杯
  9652. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9653. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9654. 配音台词:
  9655. 背景音效:
  9656. 分镜2
  9657. 出场角色:刀疤脸
  9658. 场景:悦来酒馆
  9659. 出场道具:酒杯-高脚杯
  9660. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9661. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9662. 配音台词:
  9663. 背景音效:
  9664. 分镜3
  9665. 出场角色:刀疤脸
  9666. 场景:悦来酒馆
  9667. 出场道具:酒杯-高脚杯
  9668. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9669. 运镜:从中景推向令牌特写。
  9670. 配音台词:
  9671. 背景音效:
  9672. 分镜4
  9673. 出场角色:刀疤脸
  9674. 场景:悦来酒馆
  9675. 出场道具:酒杯-高脚杯
  9676. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9677. 运镜:极速推向酒水溅起的瞬间。
  9678. 配音台词:
  9679. 背景音效:
  9680. 分镜5
  9681. 出场角色:刀疤脸
  9682. 场景:悦来酒馆
  9683. 出场道具:酒杯-高脚杯
  9684. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9685. 运镜:固定机位,利用倾斜构图制造压迫感。
  9686. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9687. 背景音效:";
  9688. // 获取模型配置
  9689. $model = getProp($data, 'model');
  9690. if (!$model) {
  9691. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  9692. }
  9693. // 验证模型是否在可用模型表中
  9694. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9695. $model = 'deepseek-v4-pro';
  9696. }
  9697. // 模型兼容性处理
  9698. $thinkingMode = 'disabled';
  9699. $reasoningEffort = 'high';
  9700. if ($model === 'deepseek-chat') {
  9701. $model = 'deepseek-v4-flash';
  9702. $thinkingMode = 'disabled';
  9703. } elseif ($model === 'deepseek-reasoner') {
  9704. $model = 'deepseek-v4-flash';
  9705. $thinkingMode = 'enabled';
  9706. }
  9707. // 构建消息
  9708. $messages = [
  9709. [
  9710. 'role' => 'system',
  9711. 'content' => $system_prompt
  9712. ],
  9713. [
  9714. 'role' => 'user',
  9715. 'content' => $user_prompt
  9716. ]
  9717. ];
  9718. // dd($messages);
  9719. // 构建请求参数
  9720. $post_data = [
  9721. 'model' => $model,
  9722. 'messages' => $messages,
  9723. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9724. 'frequency_penalty' => 0,
  9725. 'presence_penalty' => 0,
  9726. 'response_format' => ['type' => 'text'],
  9727. 'thinking' => ['type' => $thinkingMode],
  9728. 'stream' => false // 非流式输出
  9729. ];
  9730. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9731. // 调用AI生成新的分段剧本
  9732. try {
  9733. $fullContent = '';
  9734. $usage = [];
  9735. // 根据模型类型选择调用方法
  9736. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9737. // DeepSeek 官方模型使用 DeepSeek API
  9738. $chatResult = $this->chatOnly($post_data);
  9739. } else if (in_array($model, $this->gpt_text_models)) {
  9740. // GPT 模型使用 TokenRouter API
  9741. $chatResult = $this->gpt54ChatOnly($post_data);
  9742. } else {
  9743. // 其他模型使用火山引擎API
  9744. $chatResult = $this->volcEngineChatCompletion($post_data);
  9745. }
  9746. if (is_array($chatResult)) {
  9747. $fullContent = $chatResult['fullContent'] ?? '';
  9748. $usage = $chatResult['usage'] ?? [];
  9749. }
  9750. $generated_content = $fullContent;
  9751. if (empty($generated_content)) {
  9752. Utils::throwError('20003:AI生成内容为空,请重试');
  9753. }
  9754. // 解析生成的内容 - 按片段分割
  9755. $parsed_segments = [];
  9756. // 先在开头添加换行符,确保第1片段也能被正确分割
  9757. $normalizedText = "\n" . $generated_content;
  9758. $parts = preg_split('/\n\s*##/', $normalizedText);
  9759. foreach ($parts as $part) {
  9760. $part = trim($part);
  9761. if (empty($part)) continue;
  9762. // 匹配"片段X"格式
  9763. if (!preg_match('/^片段\d+/', $part)) {
  9764. continue;
  9765. }
  9766. // 分离标题和内容
  9767. $lines = explode("\n", $part, 2);
  9768. $actTitle = trim($lines[0]);
  9769. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  9770. // 解析标题,提取序号
  9771. $actNumber = 0;
  9772. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  9773. $actNumber = intval($segmentTitleMatch[1]);
  9774. } else {
  9775. $actNumber = count($parsed_segments) + 1;
  9776. }
  9777. // 提取时长(仅保留数字)
  9778. $actDuration = 0;
  9779. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  9780. $actDurationStr = trim($actDurationMatch[1]);
  9781. // 提取数字部分(支持整数和小数)
  9782. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  9783. $actDuration = (float)$numMatch[1];
  9784. }
  9785. }
  9786. // 清理act_content:去除时长、旁白音色等非分镜内容行
  9787. // 只保留分镜内容,并确保分镜标记使用【】格式
  9788. $cleaned_content = '';
  9789. $content_lines = explode("\n", $actContent);
  9790. $is_capturing = false; // 标记是否开始捕获分镜内容
  9791. $count = 0;
  9792. foreach ($content_lines as $line) {
  9793. $trimmed_line = trim($line);
  9794. // 跳过时长和旁白音色行
  9795. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  9796. continue;
  9797. }
  9798. // 检测是否是分镜开始
  9799. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  9800. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  9801. $count++;
  9802. $is_capturing = true;
  9803. // 如果没有【】,则添加
  9804. if (!preg_match('/^【/u', $trimmed_line)) {
  9805. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  9806. }
  9807. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  9808. }
  9809. // 如果已经开始捕获,则添加该行
  9810. if ($is_capturing && !empty($trimmed_line)) {
  9811. $cleaned_content .= $trimmed_line."\n";
  9812. }
  9813. }
  9814. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  9815. $parsed_segments[] = [
  9816. 'act_number' => $actNumber,
  9817. 'act_title' => $actTitle,
  9818. 'act_duration' => $actDuration,
  9819. 'act_content' => $cleaned_content,
  9820. ];
  9821. }
  9822. if (empty($parsed_segments)) {
  9823. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  9824. }
  9825. // 收集所有资产名称(角色、场景、道具)
  9826. $product_names = [];
  9827. // 收集角色名称
  9828. if (!empty($roles) && is_array($roles)) {
  9829. foreach ($roles as $role) {
  9830. $role_name = getProp($role, 'role', '');
  9831. if (!empty($role_name)) {
  9832. $product_names[] = $role_name;
  9833. }
  9834. }
  9835. }
  9836. // 收集场景名称
  9837. if (!empty($scenes) && is_array($scenes)) {
  9838. foreach ($scenes as $scene) {
  9839. $scene_name = getProp($scene, 'scene', '');
  9840. if (!empty($scene_name)) {
  9841. $product_names[] = $scene_name;
  9842. }
  9843. }
  9844. }
  9845. // 收集道具名称
  9846. if (!empty($props) && is_array($props)) {
  9847. foreach ($props as $prop) {
  9848. $prop_name = getProp($prop, 'prop', '');
  9849. if (!empty($prop_name)) {
  9850. $product_names[] = $prop_name;
  9851. }
  9852. }
  9853. }
  9854. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9855. $product_names = array_unique($product_names);
  9856. usort($product_names, function($a, $b) {
  9857. return mb_strlen($b) - mb_strlen($a);
  9858. });
  9859. // 处理每个片段的 act_show_content
  9860. foreach ($parsed_segments as &$segment) {
  9861. $act_content = getProp($segment, 'act_content', '');
  9862. if (empty($act_content)) {
  9863. $segment['act_show_content'] = '';
  9864. continue;
  9865. }
  9866. $processed_content = $act_content;
  9867. // 统一替换所有资产名称为 {资产名} 格式
  9868. // 使用占位符避免嵌套替换问题
  9869. $placeholder_map = [];
  9870. $placeholder_index = 0;
  9871. foreach ($product_names as $product_name) {
  9872. // 转义特殊字符
  9873. $escaped_product = preg_quote($product_name, '/');
  9874. // 检查是否匹配且未被 {} 包裹
  9875. $processed_content = preg_replace_callback(
  9876. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9877. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9878. // 使用唯一占位符
  9879. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9880. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9881. $placeholder_index++;
  9882. return $placeholder;
  9883. },
  9884. $processed_content
  9885. );
  9886. }
  9887. // 将所有占位符替换回实际内容
  9888. foreach ($placeholder_map as $placeholder => $replacement) {
  9889. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9890. }
  9891. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9892. $shot_counter = 0;
  9893. $processed_content = preg_replace_callback(
  9894. '/【(?:镜头|分镜)(\d+)】/u',
  9895. function($matches) use (&$shot_counter) {
  9896. $shot_counter++;
  9897. return '【镜头' . $shot_counter . '】';
  9898. },
  9899. $processed_content
  9900. );
  9901. $segment['act_show_content'] = $processed_content;
  9902. }
  9903. unset($segment); // 解除引用
  9904. // 保存到数据库
  9905. $now = date('Y-m-d H:i:s');
  9906. $saved_acts = []; // 用于记录保存后的片段信息
  9907. if ($act_id > 0) {
  9908. // 单个片段模式:更新单条记录
  9909. if (count($parsed_segments) > 0) {
  9910. $new_segment = $parsed_segments[0];
  9911. $update_data = [
  9912. 'act_content' => getProp($new_segment, 'act_content', ''),
  9913. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9914. 'act_title' => getProp($new_segment, 'act_title', ''),
  9915. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9916. 'updated_at' => $now,
  9917. ];
  9918. DB::table('mp_episode_segments')
  9919. ->where('id', $act_id)
  9920. ->update($update_data);
  9921. // 获取更新后的记录
  9922. $updated_act = DB::table('mp_episode_segments')
  9923. ->where('id', $act_id)
  9924. ->first();
  9925. if ($updated_act) {
  9926. $saved_acts[] = [
  9927. 'act_id' => $updated_act->id,
  9928. 'act_number' => $updated_act->act_number,
  9929. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9930. 'act_content' => $updated_act->act_content,
  9931. 'act_show_content' => $updated_act->act_show_content,
  9932. 'video_url' => $updated_act->video_url ?? '',
  9933. 'video_duration' => $updated_act->video_duration ?? 0,
  9934. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9935. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9936. ];
  9937. }
  9938. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9939. }
  9940. } else {
  9941. // 整个剧集模式:删除原有记录并批量保存新记录
  9942. DB::beginTransaction();
  9943. try {
  9944. // 删除原有的所有片段记录
  9945. DB::table('mp_episode_segments')
  9946. ->where('episode_id', $target_episode_id)
  9947. ->delete();
  9948. // 批量插入新的片段记录
  9949. $segments_to_insert = [];
  9950. foreach ($parsed_segments as $index => $segment) {
  9951. $act_number = $index + 1;
  9952. $segments_to_insert[] = [
  9953. 'anime_id' => $target_anime_id,
  9954. 'episode_id' => $target_episode_id,
  9955. 'episode_number' => $target_episode_number,
  9956. 'act_number' => $act_number,
  9957. 'act_title' => getProp($segment, 'act_title', ''),
  9958. 'act_duration' => getProp($segment, 'act_duration', 0),
  9959. 'act_content' => getProp($segment, 'act_content', ''),
  9960. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9961. 'created_at' => $now,
  9962. 'updated_at' => $now,
  9963. ];
  9964. }
  9965. if (!empty($segments_to_insert)) {
  9966. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9967. }
  9968. DB::commit();
  9969. // 查询保存后的所有片段记录
  9970. $saved_segments = DB::table('mp_episode_segments')
  9971. ->where('episode_id', $target_episode_id)
  9972. ->orderBy('act_number')
  9973. ->get();
  9974. foreach ($saved_segments as $saved_segment) {
  9975. $saved_acts[] = [
  9976. 'act_id' => $saved_segment->id,
  9977. 'act_number' => $saved_segment->act_number,
  9978. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9979. 'act_content' => $saved_segment->act_content,
  9980. 'act_show_content' => $saved_segment->act_show_content,
  9981. 'video_url' => $saved_segment->video_url ?? '',
  9982. 'video_duration' => $saved_segment->video_duration ?? 0,
  9983. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9984. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9985. ];
  9986. }
  9987. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9988. 'episode_id' => $target_episode_id,
  9989. 'segments_count' => count($segments_to_insert)
  9990. ]);
  9991. } catch (\Exception $e) {
  9992. DB::rollBack();
  9993. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9994. Utils::throwError('20003:保存失败,请重试');
  9995. }
  9996. }
  9997. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9998. return [
  9999. 'anime_id' => $target_anime_id,
  10000. 'episode_id' => $target_episode_id,
  10001. 'title' => getProp($episode, 'title', ''),
  10002. 'episode_number' => $target_episode_number,
  10003. 'is_generated' => getProp($episode, 'is_generated', 0),
  10004. 'acts' => $saved_acts,
  10005. ];
  10006. } catch (\Exception $e) {
  10007. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  10008. throw $e;
  10009. }
  10010. }
  10011. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  10012. {
  10013. $episode_arr = [
  10014. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  10015. 'intro' => getProp($script_arr, 'intro'),
  10016. 'art_style' => getProp($script_arr, 'art_style'),
  10017. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10018. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10019. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10020. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  10021. ];
  10022. if (empty($episode_arr['acts'])) {
  10023. $fallback_episode_arr = handleEpisodeContent($fullContent);
  10024. if (!empty($fallback_episode_arr['acts'])) {
  10025. $episode_arr = array_merge($fallback_episode_arr, [
  10026. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  10027. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  10028. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  10029. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  10030. ]);
  10031. }
  10032. }
  10033. // if (!getProp($episode_arr, 'episode_title')) {
  10034. // $episode_title = '';
  10035. // $episodes = getProp($script_arr, 'episodes', []);
  10036. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  10037. // $episode_title = '第1集:' . $episodes[0]['title'];
  10038. // }
  10039. // if (!$episode_title) {
  10040. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  10041. // }
  10042. // $episode_arr['episode_title'] = $episode_title;
  10043. // }
  10044. return $episode_arr;
  10045. }
  10046. private function saveEpisodeVersionData(
  10047. int $anime_id,
  10048. int $episode_number,
  10049. array $episode_arr,
  10050. array $existing_roles,
  10051. array $existing_scenes,
  10052. array $existing_props,
  10053. $current_episode,
  10054. $base_episode,
  10055. bool $is_regenerate_version,
  10056. string $content,
  10057. string $now,
  10058. array $ref_products = []
  10059. ): array {
  10060. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10061. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10062. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10063. // 过滤掉关键字段为空的条目
  10064. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10065. return !empty($item['role'] ?? null);
  10066. }));
  10067. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10068. return !empty($item['scene'] ?? null);
  10069. }));
  10070. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10071. return !empty($item['prop'] ?? null);
  10072. }));
  10073. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10074. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10075. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10076. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10077. $ace_mode = getProp($anime, 'ace_mode');
  10078. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10079. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10080. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10081. $global_roles = is_array($global_roles) ? $global_roles : [];
  10082. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10083. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10084. $art_style_type = getProp($anime, 'art_style_type');
  10085. // 检查并创建 roles 的图片生成任务
  10086. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10087. // 检查并创建 scenes 的图片生成任务
  10088. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10089. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10090. if ($arr && is_array($arr)) {
  10091. $merged_roles = $arr['roles'];
  10092. $merged_scenes = $arr['scenes'];
  10093. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10094. }
  10095. // 确保数据是数组类型
  10096. if (!is_array($merged_roles)) {
  10097. dLog('deepseek')->error('merged_roles不是数组类型', [
  10098. 'type' => gettype($merged_roles),
  10099. 'value' => $merged_roles
  10100. ]);
  10101. $merged_roles = [];
  10102. }
  10103. if (!is_array($merged_scenes)) {
  10104. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10105. 'type' => gettype($merged_scenes),
  10106. 'value' => $merged_scenes
  10107. ]);
  10108. $merged_scenes = [];
  10109. }
  10110. if (!is_array($merged_props)) {
  10111. dLog('deepseek')->error('merged_props不是数组类型', [
  10112. 'type' => gettype($merged_props),
  10113. 'value' => $merged_props
  10114. ]);
  10115. $merged_props = [];
  10116. }
  10117. // 同步新出现的主体和场景到全局
  10118. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10119. $role_arr = [];
  10120. foreach ($merged_roles as $item) {
  10121. $role_arr[$item['role']] = $item;
  10122. }
  10123. $version_count = DB::table('mp_anime_episodes')
  10124. ->where('anime_id', $anime_id)
  10125. ->where('episode_number', $episode_number)
  10126. ->count('id');
  10127. $episode = [
  10128. 'anime_id' => $anime_id,
  10129. 'episode_number' => $episode_number,
  10130. 'title' => getProp($episode_arr, 'episode_title'),
  10131. 'content' => $content,
  10132. 'intro' => getProp($episode_arr, 'intro'),
  10133. 'art_style' => getProp($episode_arr, 'art_style'),
  10134. 'roles' => json_encode($merged_roles, 256),
  10135. 'scenes' => json_encode($merged_scenes, 256),
  10136. 'props' => json_encode($merged_props, 256),
  10137. 'generate_status' => '待执行',
  10138. 'generate_at' => $now,
  10139. 'is_default' => 1,
  10140. 'updated_at' => $now,
  10141. ];
  10142. $del_flag = false;
  10143. if ($is_regenerate_version) {
  10144. DB::table('mp_anime_episodes')
  10145. ->where('anime_id', $anime_id)
  10146. ->where('episode_number', $episode_number)
  10147. ->update(['is_default' => 0, 'updated_at' => $now]);
  10148. $episode['sequence'] = $version_count + 1;
  10149. $episode['created_at'] = $now;
  10150. $episode['cpid'] = Site::getCpid();
  10151. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10152. if (!$episode_id) {
  10153. Utils::throwError('20003:创建剧集版本失败');
  10154. }
  10155. } else {
  10156. $target_episode = $current_episode ?: $base_episode;
  10157. if ($target_episode) {
  10158. $episode_id = getProp($target_episode, 'id');
  10159. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10160. DB::table('mp_anime_episodes')
  10161. ->where('anime_id', $anime_id)
  10162. ->where('episode_number', $episode_number)
  10163. ->where('id', '<>', $episode_id)
  10164. ->update(['is_default' => 0, 'updated_at' => $now]);
  10165. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10166. if ($boolen === false) {
  10167. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10168. Utils::throwError('20003:分集内容保存失败');
  10169. }
  10170. $del_flag = true;
  10171. } else {
  10172. DB::table('mp_anime_episodes')
  10173. ->where('anime_id', $anime_id)
  10174. ->where('episode_number', $episode_number)
  10175. ->update(['is_default' => 0, 'updated_at' => $now]);
  10176. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  10177. $episode['created_at'] = $now;
  10178. $episode['cpid'] = Site::getCpid();
  10179. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10180. if (!$episode_id) {
  10181. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  10182. Utils::throwError('20003:分集内容保存失败');
  10183. }
  10184. }
  10185. }
  10186. $segments = [];
  10187. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10188. // 如果是第2集及以后,获取上一集的主体音色数据
  10189. $previous_roles_voice = [];
  10190. if ($episode_number >= 2) {
  10191. $previous_episode = DB::table('mp_anime_episodes')
  10192. ->where('anime_id', $anime_id)
  10193. ->where('episode_number', $episode_number - 1)
  10194. ->where('is_default', 1)
  10195. ->first();
  10196. if ($previous_episode) {
  10197. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  10198. if (is_array($previous_roles)) {
  10199. foreach ($previous_roles as $prev_role) {
  10200. $role_name = getProp($prev_role, 'role');
  10201. if ($role_name) {
  10202. $previous_roles_voice[$role_name] = [
  10203. 'voice_name' => getProp($prev_role, 'voice_name'),
  10204. 'voice_type' => getProp($prev_role, 'voice_type'),
  10205. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  10206. ];
  10207. $voice_prompt = getProp($prev_role, 'voice_prompt');
  10208. if ($voice_prompt) {
  10209. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  10210. }
  10211. }
  10212. }
  10213. }
  10214. }
  10215. }
  10216. // 将继承的音色数据同步到当前集的主体列表
  10217. if (!empty($previous_roles_voice)) {
  10218. foreach ($merged_roles as &$role) {
  10219. $role_name = getProp($role, 'role');
  10220. if ($role_name && isset($previous_roles_voice[$role_name])) {
  10221. // 强制继承上一集的音色数据
  10222. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  10223. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  10224. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  10225. // 如果上一集有 voice_prompt 则继承,否则跳过
  10226. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  10227. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  10228. }
  10229. }
  10230. }
  10231. unset($role); // 解除引用
  10232. // 更新 role_arr 以便后续使用
  10233. $role_arr = [];
  10234. foreach ($merged_roles as $item) {
  10235. $role_arr[$item['role']] = $item;
  10236. }
  10237. }
  10238. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  10239. $emotion_list = array_flip($emotion_list);
  10240. foreach ($acts as $act) {
  10241. $act_segments = getProp($act, 'segments', []);
  10242. if (!is_array($act_segments)) {
  10243. continue;
  10244. }
  10245. if ((int)$ace_mode === 1) {
  10246. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  10247. $merged_parts = [];
  10248. foreach ($act_segments as $seg) {
  10249. $seg_num = getProp($seg, 'segment_number');
  10250. $seg_content = getProp($seg, 'segment_content');
  10251. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  10252. }
  10253. $act_content = implode("\n", $merged_parts);
  10254. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10255. $segments[] = [
  10256. 'anime_id' => $anime_id,
  10257. 'episode_id' => $episode_id,
  10258. 'episode_number' => $episode_number,
  10259. 'act_number' => getProp($act, 'act_number'),
  10260. 'act_title' => getProp($act, 'act_title'),
  10261. 'act_duration' => getProp($act, 'act_duration'),
  10262. 'act_content' => $act_content,
  10263. 'created_at' => $now,
  10264. 'updated_at' => $now
  10265. ];
  10266. } else {
  10267. foreach ($act_segments as $segment) {
  10268. $voice_actor = getProp($segment, 'voice_actor');
  10269. // 优先从上一集继承音色数据
  10270. $timbre_info = [];
  10271. if (isset($previous_roles_voice[$voice_actor])) {
  10272. // 从上一集继承音色数据
  10273. $timbre_info = $previous_roles_voice[$voice_actor];
  10274. } elseif (isset($role_arr[$voice_actor])) {
  10275. // 使用当前集的主体音色数据
  10276. $timbre_info = $role_arr[$voice_actor];
  10277. }
  10278. $voice_type = getProp($timbre_info, 'voice_type');
  10279. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  10280. if ($timbre_emotion) {
  10281. $timbre_emotion = explode(',', $timbre_emotion);
  10282. } else {
  10283. $timbre_emotion = [];
  10284. }
  10285. $emotion = getProp($segment, 'emotion', '中性');
  10286. if (!in_array($emotion, $timbre_emotion)) {
  10287. $emotion = '中性';
  10288. }
  10289. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  10290. $segments[] = [
  10291. 'anime_id' => $anime_id,
  10292. 'episode_id' => $episode_id,
  10293. 'episode_number' => $episode_number,
  10294. 'act_number' => getProp($act, 'act_number'),
  10295. 'act_title' => getProp($act, 'act_title'),
  10296. 'act_duration' => getProp($act, 'act_duration'),
  10297. 'segment_id' => getProp($segment, 'segment_id'),
  10298. 'segment_number' => getProp($segment, 'segment_number'),
  10299. 'segment_content' => getProp($segment, 'segment_content'),
  10300. 'description' => getProp($segment, 'description'),
  10301. 'composition' => getProp($segment, 'composition'),
  10302. 'camera_movement' => getProp($segment, 'camera_movement'),
  10303. 'voice_actor' => $voice_actor,
  10304. 'dialogue' => getProp($segment, 'dialogue'),
  10305. 'frame_type' => getProp($segment, 'frame_type'),
  10306. 'scene' => getProp($segment, 'scene'),
  10307. 'characters' => getProp($segment, 'characters'),
  10308. 'tail_frame' => getProp($segment, 'tail_frame'),
  10309. 'voice_name' => getProp($timbre_info, 'voice_name'),
  10310. 'voice_type' => $voice_type,
  10311. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  10312. 'emotion' => $emotion,
  10313. 'emotion_type' => $emotion_type,
  10314. 'gender' => getProp($segment, 'gender', '0'),
  10315. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  10316. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  10317. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  10318. 'pitch' => getProp($segment, 'pitch', 0),
  10319. 'created_at' => $now,
  10320. 'updated_at' => $now
  10321. ];
  10322. }
  10323. }
  10324. }
  10325. if ($segments) {
  10326. if ($del_flag) {
  10327. DB::table('mp_episode_segments')
  10328. ->where('anime_id', $anime_id)
  10329. ->where('episode_id', $episode_id)
  10330. ->delete();
  10331. }
  10332. $boolen = DB::table('mp_episode_segments')->insert($segments);
  10333. if (!$boolen) {
  10334. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  10335. Utils::throwError('20003:分镜内容保存失败');
  10336. }
  10337. }
  10338. dLog('deepseek')->info('segments', $segments);
  10339. // ace_mode=1: acts 返回值按合并格式调整
  10340. if ((int)$ace_mode === 1) {
  10341. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  10342. $act_map = [];
  10343. foreach ($table_act_data as $item) {
  10344. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  10345. }
  10346. $restructured_acts = [];
  10347. foreach ($acts as $act) {
  10348. $act_segments = getProp($act, 'segments', []);
  10349. if (!is_array($act_segments)) {
  10350. continue;
  10351. }
  10352. $merged_parts = [];
  10353. foreach ($act_segments as $seg) {
  10354. $seg_num = getProp($seg, 'segment_number');
  10355. $seg_content = getProp($seg, 'segment_content');
  10356. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  10357. }
  10358. $act_content = implode("\n", $merged_parts);
  10359. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10360. $restructured_acts[] = [
  10361. 'anime_id' => $anime_id,
  10362. 'episode_id' => $episode_id,
  10363. 'episode_number' => $episode_number,
  10364. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  10365. 'act_number' => getProp($act, 'act_number'),
  10366. 'act_title' => getProp($act, 'act_title'),
  10367. 'act_duration' => getProp($act, 'act_duration'),
  10368. 'act_content' => $act_content,
  10369. 'created_at' => $now,
  10370. 'updated_at' => $now,
  10371. ];
  10372. }
  10373. $acts = $restructured_acts;
  10374. }
  10375. $episode['episode_id'] = $episode_id;
  10376. $episode['roles'] = $merged_roles;
  10377. $episode['scenes'] = $merged_scenes;
  10378. $episode['props'] = $merged_props;
  10379. $episode['acts'] = $acts;
  10380. return [
  10381. 'episode' => $episode,
  10382. 'episode_id' => $episode_id,
  10383. 'merged_roles' => $merged_roles,
  10384. 'merged_scenes' => $merged_scenes,
  10385. 'merged_props' => $merged_props,
  10386. ];
  10387. }
  10388. private function buildEpisodeItemContent(array $items, string $nameKey): string
  10389. {
  10390. $content = '';
  10391. foreach ($items as $item) {
  10392. $name = trim((string)getProp($item, $nameKey));
  10393. if ($name === '' || $name === '旁白') {
  10394. continue;
  10395. }
  10396. $description = trim((string)getProp($item, 'description'));
  10397. $content .= $name . ': ' . $description;
  10398. if ($nameKey == 'role') {
  10399. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10400. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10401. $voice_name = trim(getProp($item, 'voice_name'));
  10402. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10403. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  10404. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10405. }else {
  10406. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10407. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10408. }
  10409. $content .= "\n";
  10410. }
  10411. return trim($content);
  10412. }
  10413. private function getEpisodeChatContent($animeId, $sequence, $content) {
  10414. if ((int)$sequence <= 0) {
  10415. return [];
  10416. }
  10417. $origin_content = '';
  10418. if ($content) {
  10419. $origin_content = '本集剧情内容:'.$content;
  10420. }else {
  10421. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  10422. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  10423. }
  10424. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  10425. // 获取分集信息
  10426. $episode = DB::table('mp_anime_episodes')
  10427. ->where('anime_id', $animeId)
  10428. ->where('episode_number', $sequence)
  10429. ->where('is_default', 1)
  10430. ->first();
  10431. if (!$episode) {
  10432. return [];
  10433. }
  10434. $episode_id = getProp($episode, 'id');
  10435. $episode_number = getProp($episode, 'episode_number');
  10436. $title = getProp($episode, 'title');
  10437. $intro = getProp($episode, 'intro');
  10438. $art_style = getProp($episode, 'art_style');
  10439. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10440. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10441. // 组装纯文本内容
  10442. $content = '';
  10443. // 添加分集标题和梗概
  10444. $content .= "###第{$episode_number}集:{$title}\n\n";
  10445. $content .= "###故事梗概\n";
  10446. $content .= trim($intro) . "\n\n";
  10447. // 添加美术风格
  10448. $content .= "###美术风格\n";
  10449. $content .= trim($art_style) . "\n\n";
  10450. // 添加主体列表
  10451. $content .= "###主体列表\n";
  10452. $pangbai_voice_prompt = "";
  10453. foreach ($roles as $role) {
  10454. $name = getProp($role, 'role');
  10455. $description = getProp($role, 'description');
  10456. $pic_prompt = getProp($role, 'pic_prompt');
  10457. $voice_prompt = getProp($role, 'voice_prompt');
  10458. $voice_name = getProp($role, 'voice_name');
  10459. $content .= "{$name}: {$description}";
  10460. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10461. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10462. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10463. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  10464. $content .= "\n";
  10465. }
  10466. $content .= "\n";
  10467. // 添加场景列表
  10468. $content .= "###场景列表\n";
  10469. foreach ($scenes as $scene) {
  10470. $name = getProp($scene, 'scene');
  10471. $description = getProp($scene, 'description');
  10472. $pic_prompt = getProp($scene, 'pic_prompt');
  10473. $content .= "{$name}: {$description}";
  10474. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10475. $content .= "\n";
  10476. }
  10477. $content .= "\n";
  10478. // 获取分镜信息
  10479. $segments = DB::table('mp_episode_segments')
  10480. ->where('anime_id', $animeId)
  10481. ->where('episode_id', $episode_id)
  10482. ->orderBy('segment_number')
  10483. ->get();
  10484. if ($segments && count($segments) > 0) {
  10485. if ((int)$ace_mode === 1) {
  10486. $content .= "###分段剧本\n";
  10487. // 获取片段数量
  10488. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  10489. $content .= "片段数量:{$act_count}\n";
  10490. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  10491. $content .= "\n";
  10492. }else {
  10493. $content .= "###分镜剧本\n";
  10494. }
  10495. // 按幕分组
  10496. $currentAct = null;
  10497. foreach ($segments as $segment) {
  10498. $act_number = getProp($segment, 'act_number');
  10499. $act_title = getProp($segment, 'act_title');
  10500. $act_duration = getProp($segment, 'act_duration');
  10501. $segment_number = getProp($segment, 'segment_number');
  10502. $segment_content = getProp($segment, 'segment_content');
  10503. $scene_description = getProp($segment, 'scene_description');
  10504. $scene_name = getProp($segment, 'scene_name');
  10505. $composition = getProp($segment, 'composition');
  10506. $camera_movement = getProp($segment, 'camera_movement');
  10507. $voice_type = getProp($segment, 'voice_type');
  10508. $characters = getProp($segment, 'characters');
  10509. $dialogue = getProp($segment, 'dialogue');
  10510. $frame_type = getProp($segment, 'frame_type');
  10511. $tail_frame_description = getProp($segment, 'tail_frame_description');
  10512. // 判断是否是全能模式
  10513. if ((int)$ace_mode === 1) { // 全能模式
  10514. // 如果是新的分段,添加分段标题
  10515. if ($act_number !== $currentAct) {
  10516. $currentAct = $act_number;
  10517. $content .= "##{$act_title}\n";
  10518. $content .= "时长:{$act_duration}s\n";
  10519. }
  10520. }else {
  10521. // 如果是新的幕,添加幕标题
  10522. if ($act_number !== $currentAct) {
  10523. $currentAct = $act_number;
  10524. $content .= "##第{$act_number}幕:{$scene_name}\n";
  10525. }
  10526. }
  10527. // 添加分镜信息
  10528. $content .= "分镜{$segment_number}\n";
  10529. $content .= "分镜内容:\n{$segment_content}\n";
  10530. // $content .= "画面描述:{$scene_description}\n";
  10531. // $content .= "场景:{$scene_name}\n";
  10532. // $content .= "构图设计:{$composition}\n";
  10533. // $content .= "运镜调度:{$camera_movement}\n";
  10534. // if (!empty($voice_type)) {
  10535. // $content .= "配音角色:{$voice_type}\n";
  10536. // }
  10537. // if (!empty($characters)) {
  10538. // $content .= "出镜角色:{$characters}\n";
  10539. // }
  10540. // if (!empty($dialogue)) {
  10541. // $content .= "台词内容:\"{$dialogue}\"\n";
  10542. // }
  10543. // $content .= "画面类型:{$frame_type}\n";
  10544. // $content .= "尾帧描述:{$tail_frame_description}\n";
  10545. $content .= "\n";
  10546. }
  10547. }
  10548. $content = trim($content);
  10549. if($content) $content = "上集剧本内容:\n{$content}";
  10550. return [
  10551. [
  10552. 'role' => 'user',
  10553. 'content' => $origin_content
  10554. ],
  10555. [
  10556. 'role' => 'assistant',
  10557. 'content' => $content
  10558. ]
  10559. ];
  10560. }
  10561. private function getEpisodeChatMessages($animeId, $sequence): array
  10562. {
  10563. if ((int)$sequence <= 0) {
  10564. return [];
  10565. }
  10566. return DB::table('mp_anime_records')
  10567. ->where('anime_id', $animeId)
  10568. ->where('sequence', $sequence)
  10569. ->where('episode_id', '>', 0)
  10570. ->select('role', 'content')
  10571. ->orderBy('created_at')
  10572. ->orderBy('id')
  10573. ->get()
  10574. ->map(function ($value) {
  10575. return (array)$value;
  10576. })
  10577. ->toArray();
  10578. }
  10579. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  10580. {
  10581. $existingMap = [];
  10582. foreach ($existingItems as $item) {
  10583. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10584. if ($itemKey === '') {
  10585. continue;
  10586. }
  10587. $existingMap[$itemKey] = $item;
  10588. }
  10589. if (!$generatedItems) {
  10590. return array_values($existingItems);
  10591. }
  10592. $merged = [];
  10593. foreach ($generatedItems as $item) {
  10594. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10595. if ($itemKey === '') {
  10596. continue;
  10597. }
  10598. if (isset($existingMap[$itemKey])) {
  10599. if (trim((string)getProp($item, 'description')) === '') {
  10600. $merged[] = $existingMap[$itemKey];
  10601. continue;
  10602. }
  10603. // 检查内容是否发生变化
  10604. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  10605. if (!$isChanged) {
  10606. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  10607. $mergedItem = [
  10608. $nameKey => trim((string)getProp($item, $nameKey)),
  10609. 'description' => trim((string)getProp($item, 'description')),
  10610. ];
  10611. // 如果有 pic_prompt,添加到合并项中
  10612. $picPrompt = getProp($item, 'pic_prompt');
  10613. if (!empty($picPrompt)) {
  10614. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10615. }
  10616. // 继承现有项的 URL
  10617. $existingUrl = getProp($existingMap[$itemKey], 'url');
  10618. if (!empty($existingUrl)) {
  10619. $mergedItem['url'] = $existingUrl;
  10620. }
  10621. // 继承现有项的 task_id
  10622. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  10623. if (!empty($existingTaskId)) {
  10624. $mergedItem['task_id'] = $existingTaskId;
  10625. }
  10626. // 继承现有项的 task_status
  10627. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  10628. if (!empty($existingTaskStatus)) {
  10629. $mergedItem['task_status'] = $existingTaskStatus;
  10630. }
  10631. // 保留生成项的音色字段
  10632. $voiceName = getProp($item, 'voice_name');
  10633. if (!empty($voiceName)) {
  10634. $mergedItem['voice_name'] = $voiceName;
  10635. }
  10636. $voiceType = getProp($item, 'voice_type');
  10637. if (!empty($voiceType)) {
  10638. $mergedItem['voice_type'] = $voiceType;
  10639. }
  10640. $audioUrl = getProp($item, 'voice_audio_url');
  10641. if (!empty($audioUrl)) {
  10642. $mergedItem['voice_audio_url'] = $audioUrl;
  10643. }
  10644. $merged[] = $mergedItem;
  10645. } else {
  10646. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  10647. $mergedItem = [
  10648. $nameKey => trim((string)getProp($item, $nameKey)),
  10649. 'description' => trim((string)getProp($item, 'description')),
  10650. ];
  10651. // 如果有 pic_prompt,添加到合并项中
  10652. $picPrompt = getProp($item, 'pic_prompt');
  10653. if (!empty($picPrompt)) {
  10654. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10655. }
  10656. // 保留生成项的音色字段
  10657. $voiceName = getProp($item, 'voice_name');
  10658. if (!empty($voiceName)) {
  10659. $mergedItem['voice_name'] = $voiceName;
  10660. }
  10661. $voiceType = getProp($item, 'voice_type');
  10662. if (!empty($voiceType)) {
  10663. $mergedItem['voice_type'] = $voiceType;
  10664. }
  10665. $audioUrl = getProp($item, 'voice_audio_url');
  10666. if (!empty($audioUrl)) {
  10667. $mergedItem['voice_audio_url'] = $audioUrl;
  10668. }
  10669. // 不继承 URL、task_id 和 task_status(重置状态)
  10670. $merged[] = $mergedItem;
  10671. }
  10672. } else {
  10673. // 新增项,保留生成项的所有字段
  10674. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  10675. }
  10676. }
  10677. return $merged ?: array_values($existingItems);
  10678. }
  10679. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  10680. {
  10681. $resetItem = [
  10682. $nameKey => trim((string)getProp($item, $nameKey)),
  10683. 'description' => trim((string)getProp($item, 'description')),
  10684. ];
  10685. // 保留指定的字段
  10686. foreach ($preserveFields as $field) {
  10687. $value = getProp($item, $field);
  10688. if (!empty($value)) {
  10689. $resetItem[$field] = $value;
  10690. }
  10691. }
  10692. return $resetItem;
  10693. }
  10694. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  10695. {
  10696. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  10697. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  10698. if ($existingKey !== $generatedKey) {
  10699. return true;
  10700. }
  10701. // 比较 description 是否变化
  10702. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  10703. return true;
  10704. }
  10705. // 比较 pic_prompt 是否变化
  10706. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  10707. }
  10708. private function normalizeEpisodeResourceKey($value): string
  10709. {
  10710. $value = trim((string)$value);
  10711. if ($value === '') {
  10712. return '';
  10713. }
  10714. return strtolower((string)preg_replace('/\s+/u', '', $value));
  10715. }
  10716. // 生成全局角色图片
  10717. private function batchSetGlobalRoleImg($data, $is_force=false) {
  10718. $anime_id = getProp($data, 'anime_id');
  10719. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10720. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10721. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10722. $art_style = getProp($anime, 'art_style');
  10723. $update_flag = false;
  10724. foreach ($roles as &$role) {
  10725. $role_name = getProp($role, 'role');
  10726. if ($role_name == '旁白') continue;
  10727. // 优先使用 pic_prompt,如果没有则使用 description
  10728. $pic_prompt = getProp($role, 'pic_prompt');
  10729. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10730. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10731. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10732. // 参考图地址
  10733. $ref_img_url = getProp($role, 'url');
  10734. if (!$is_force && $ref_img_url) continue;
  10735. $update_flag = true;
  10736. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10737. try {
  10738. $params = [
  10739. 'prompt' => $description,
  10740. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  10741. 'ref_img_urls' => []
  10742. ];
  10743. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10744. $task_id = $task->id;
  10745. if (!$task_id) {
  10746. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  10747. }
  10748. $role['task_id'] = $task_id;
  10749. $role['task_status'] = 'processing';
  10750. } catch (\Exception $e) {
  10751. Utils::throwError("20003:" . $e->getMessage());
  10752. }
  10753. }
  10754. if (!$update_flag) return true;
  10755. // 保存角色信息
  10756. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10757. 'roles' => json_encode($roles, 256),
  10758. 'generate_status' => '执行中',
  10759. 'generate_at' => date('Y-m-d H:i:s'),
  10760. 'updated_at' => date('Y-m-d H:i:s')
  10761. ]);
  10762. if (!$boolen) {
  10763. Utils::throwError('20003:保存角色信息失败');
  10764. }
  10765. return $boolen;
  10766. }
  10767. // 生成全局场景图片
  10768. private function batchSetGlobalSceneImg($data, $is_force=false) {
  10769. $anime_id = getProp($data, 'anime_id');
  10770. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10771. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10772. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10773. $art_style = getProp($anime, 'art_style');
  10774. $update_flag = false;
  10775. foreach ($scenes as &$scene) {
  10776. $scene_name = getProp($scene, 'scene');
  10777. // 优先使用 pic_prompt,如果没有则使用 description
  10778. $pic_prompt = getProp($scene, 'pic_prompt');
  10779. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10780. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  10781. // 参考图地址
  10782. $ref_img_url = getProp($scene, 'url');
  10783. if (!$is_force && $ref_img_url) continue;
  10784. $update_flag = true;
  10785. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10786. try {
  10787. $params = [
  10788. 'prompt' => $description,
  10789. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  10790. 'ref_img_urls' => []
  10791. ];
  10792. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10793. $task_id = $task->id;
  10794. if (!$task_id) {
  10795. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  10796. }
  10797. $scene['task_id'] = $task_id;
  10798. $scene['task_status'] = 'processing';
  10799. } catch (\Exception $e) {
  10800. Utils::throwError("20003:" . $e->getMessage());
  10801. }
  10802. }
  10803. if (!$update_flag) return true;
  10804. // 保存角色信息
  10805. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10806. 'scenes' => json_encode($scenes, 256),
  10807. 'generate_status' => '执行中',
  10808. 'generate_at' => date('Y-m-d H:i:s'),
  10809. 'updated_at' => date('Y-m-d H:i:s')
  10810. ]);
  10811. if (!$boolen) {
  10812. Utils::throwError('20003:保存角色信息失败');
  10813. }
  10814. return $boolen;
  10815. }
  10816. // 生成分镜主体、场景和道具图片
  10817. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  10818. $character_prefix = '';
  10819. $scene_prefix = '';
  10820. $prop_prefix = '';
  10821. if ($art_style_type) {
  10822. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  10823. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  10824. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  10825. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  10826. }
  10827. $update_flag = false;
  10828. // 获取上一集的roles、scenes和props数据
  10829. $prev_roles = [];
  10830. $prev_scenes = [];
  10831. $prev_props = [];
  10832. if ($episode_number > 1) {
  10833. $prev_episode = DB::table('mp_anime_episodes')
  10834. ->where('anime_id', $anime_id)
  10835. ->where('episode_number', $episode_number - 1)
  10836. ->where('is_default', 1)
  10837. ->first();
  10838. if ($prev_episode) {
  10839. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  10840. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  10841. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  10842. dLog('deepseek')->info("获取上一集数据成功", [
  10843. 'anime_id' => $anime_id,
  10844. 'prev_episode_number' => $episode_number - 1,
  10845. 'prev_roles_count' => count($prev_roles),
  10846. 'prev_scenes_count' => count($prev_scenes),
  10847. 'prev_props_count' => count($prev_props)
  10848. ]);
  10849. }
  10850. }
  10851. // 处理角色图片生成
  10852. foreach ($roles as &$role) {
  10853. $role_name = getProp($role, 'role');
  10854. if ($role_name == '旁白') continue;
  10855. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  10856. if (isset($ref_products[$role_name])) {
  10857. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  10858. if ($role['url']) continue;
  10859. }
  10860. $role_description = getProp($role, 'description');
  10861. $role_pic_prompt = getProp($role, 'pic_prompt');
  10862. $role_url = getProp($role, 'url');
  10863. // 检查是否可以从上一集继承
  10864. $inherited = false;
  10865. if (!$is_force && !empty($prev_roles)) {
  10866. foreach ($prev_roles as $prev_role) {
  10867. $prev_role_name = getProp($prev_role, 'role');
  10868. $prev_description = getProp($prev_role, 'description');
  10869. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  10870. $prev_url = getProp($prev_role, 'url');
  10871. $prev_task_id = getProp($prev_role, 'task_id');
  10872. $prev_task_status = getProp($prev_role, 'task_status');
  10873. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  10874. if ($role_name == $prev_role_name
  10875. && $role_description == $prev_description
  10876. && $role_pic_prompt == $prev_pic_prompt
  10877. && !empty($prev_url)) {
  10878. $role['task_id'] = $prev_task_id;
  10879. $role['task_status'] = $prev_task_status;
  10880. $role['url'] = $prev_url;
  10881. $inherited = true;
  10882. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  10883. 'anime_id' => $anime_id,
  10884. 'episode_number' => $episode_number,
  10885. 'task_id' => $prev_task_id,
  10886. 'url' => $prev_url
  10887. ]);
  10888. break;
  10889. }
  10890. }
  10891. }
  10892. // 如果已继承或已有url,跳过生成
  10893. if ($inherited || (!$is_force && $role_url)) {
  10894. continue;
  10895. }
  10896. // 优先使用 pic_prompt,如果没有则使用 description
  10897. $pic_prompt = getProp($role, 'pic_prompt');
  10898. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10899. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10900. $update_flag = true;
  10901. // 调用AIImageGenerationService的生成图片任务接口
  10902. try {
  10903. $params = [
  10904. 'prompt' => $description,
  10905. 'ref_img_urls' => []
  10906. ];
  10907. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10908. $task_id = $task->id;
  10909. if (!$task_id) {
  10910. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10911. continue; // 不中断,继续处理其他角色
  10912. }
  10913. $role['task_id'] = $task_id;
  10914. $role['task_status'] = 'processing';
  10915. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10916. 'anime_id' => $anime_id,
  10917. 'episode_number' => $episode_number,
  10918. 'task_id' => $task_id
  10919. ]);
  10920. } catch (\Exception $e) {
  10921. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10922. // 不抛出异常,继续处理其他角色
  10923. }
  10924. }
  10925. // 处理场景图片生成
  10926. foreach ($scenes as &$scene) {
  10927. $scene_name = getProp($scene, 'scene');
  10928. $scene_description = getProp($scene, 'description');
  10929. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10930. $scene_url = getProp($scene, 'url');
  10931. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10932. if (isset($ref_products[$scene_name])) {
  10933. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10934. if ($scene['url']) continue;
  10935. }
  10936. // 检查是否可以从上一集继承
  10937. $inherited = false;
  10938. if (!$is_force && !empty($prev_scenes)) {
  10939. foreach ($prev_scenes as $prev_scene) {
  10940. $prev_scene_name = getProp($prev_scene, 'scene');
  10941. $prev_description = getProp($prev_scene, 'description');
  10942. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10943. $prev_url = getProp($prev_scene, 'url');
  10944. $prev_task_id = getProp($prev_scene, 'task_id');
  10945. $prev_task_status = getProp($prev_scene, 'task_status');
  10946. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10947. if ($scene_name == $prev_scene_name
  10948. && $scene_description == $prev_description
  10949. && $scene_pic_prompt == $prev_pic_prompt
  10950. && !empty($prev_url)) {
  10951. $scene['task_id'] = $prev_task_id;
  10952. $scene['task_status'] = $prev_task_status;
  10953. $scene['url'] = $prev_url;
  10954. $inherited = true;
  10955. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10956. 'anime_id' => $anime_id,
  10957. 'episode_number' => $episode_number,
  10958. 'task_id' => $prev_task_id,
  10959. 'url' => $prev_url
  10960. ]);
  10961. break;
  10962. }
  10963. }
  10964. }
  10965. // 如果已继承或已有url,跳过生成
  10966. if ($inherited || (!$is_force && $scene_url)) {
  10967. continue;
  10968. }
  10969. // 优先使用 pic_prompt,如果没有则使用 description
  10970. $pic_prompt = getProp($scene, 'pic_prompt');
  10971. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10972. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10973. $update_flag = true;
  10974. // 调用AIImageGenerationService的生成图片任务接口
  10975. try {
  10976. $params = [
  10977. 'prompt' => $description,
  10978. 'ref_img_urls' => []
  10979. ];
  10980. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10981. $task_id = $task->id;
  10982. if (!$task_id) {
  10983. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10984. continue; // 不中断,继续处理其他场景
  10985. }
  10986. $scene['task_id'] = $task_id;
  10987. $scene['task_status'] = 'processing';
  10988. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10989. 'anime_id' => $anime_id,
  10990. 'episode_number' => $episode_number,
  10991. 'task_id' => $task_id
  10992. ]);
  10993. } catch (\Exception $e) {
  10994. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10995. // 不抛出异常,继续处理其他场景
  10996. }
  10997. }
  10998. // 处理道具图片生成(逻辑与场景一致)
  10999. foreach ($props as &$prop) {
  11000. $prop_name = getProp($prop, 'prop');
  11001. $prop_description = getProp($prop, 'description');
  11002. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  11003. $prop_url = getProp($prop, 'url');
  11004. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  11005. if (isset($ref_products[$prop_name])) {
  11006. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  11007. if ($prop['url']) continue;
  11008. }
  11009. // 检查是否可以从上一集继承
  11010. $inherited = false;
  11011. if (!$is_force && !empty($prev_props)) {
  11012. foreach ($prev_props as $prev_prop) {
  11013. $prev_prop_name = getProp($prev_prop, 'prop');
  11014. $prev_description = getProp($prev_prop, 'description');
  11015. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  11016. $prev_url = getProp($prev_prop, 'url');
  11017. $prev_task_id = getProp($prev_prop, 'task_id');
  11018. $prev_task_status = getProp($prev_prop, 'task_status');
  11019. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  11020. if ($prop_name == $prev_prop_name
  11021. && $prop_description == $prev_description
  11022. && $prop_pic_prompt == $prev_pic_prompt
  11023. && !empty($prev_url)) {
  11024. $prop['task_id'] = $prev_task_id;
  11025. $prop['task_status'] = $prev_task_status;
  11026. $prop['url'] = $prev_url;
  11027. $inherited = true;
  11028. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  11029. 'anime_id' => $anime_id,
  11030. 'episode_number' => $episode_number,
  11031. 'task_id' => $prev_task_id,
  11032. 'url' => $prev_url
  11033. ]);
  11034. break;
  11035. }
  11036. }
  11037. }
  11038. // 如果已继承或已有url,跳过生成
  11039. if ($inherited || (!$is_force && $prop_url)) {
  11040. continue;
  11041. }
  11042. // 优先使用 pic_prompt,如果没有则使用 description
  11043. $pic_prompt = getProp($prop, 'pic_prompt');
  11044. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  11045. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11046. $update_flag = true;
  11047. // 调用AIImageGenerationService的生成图片任务接口
  11048. try {
  11049. $params = [
  11050. 'prompt' => $description,
  11051. 'ref_img_urls' => []
  11052. ];
  11053. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11054. $task_id = $task->id;
  11055. if (!$task_id) {
  11056. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11057. continue; // 不中断,继续处理其他道具
  11058. }
  11059. $prop['task_id'] = $task_id;
  11060. $prop['task_status'] = 'processing';
  11061. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11062. 'anime_id' => $anime_id,
  11063. 'episode_number' => $episode_number,
  11064. 'task_id' => $task_id
  11065. ]);
  11066. } catch (\Exception $e) {
  11067. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11068. // 不抛出异常,继续处理其他道具
  11069. }
  11070. }
  11071. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11072. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11073. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11074. // // 保存剧集的角色和场景信息
  11075. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11076. // 'roles' => json_encode($roles, 256),
  11077. // 'scenes' => json_encode($scenes, 256),
  11078. // 'generate_status' => '执行中',
  11079. // 'generate_at' => date('Y-m-d H:i:s'),
  11080. // 'updated_at' => date('Y-m-d H:i:s')
  11081. // ]);
  11082. // if (!$boolen) {
  11083. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11084. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11085. // }
  11086. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11087. // 'episode_id' => $episode_id,
  11088. 'roles_count' => count($roles),
  11089. 'scenes_count' => count($scenes),
  11090. 'props_count' => count($props)
  11091. ]);
  11092. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11093. }
  11094. /**
  11095. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11096. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11097. *
  11098. * @param int $anime_id 动漫对话ID
  11099. * @param array $episode_roles 剧集角色数据
  11100. * @param array $episode_scenes 剧集场景数据
  11101. * @param array $episode_props 剧集道具数据
  11102. * @return bool
  11103. */
  11104. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11105. // 获取全局数据
  11106. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11107. if (!$anime) {
  11108. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11109. return false;
  11110. }
  11111. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11112. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11113. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11114. $roles_added = false;
  11115. $roles_updated = false;
  11116. $scenes_added = false;
  11117. $props_added = false;
  11118. // 处理角色同步
  11119. foreach ($episode_roles as $episode_role) {
  11120. $episode_role_name = getProp($episode_role, 'role');
  11121. $episode_description = getProp($episode_role, 'description');
  11122. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11123. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11124. // 跳过旁白
  11125. if ($episode_role_name == '旁白') {
  11126. continue;
  11127. }
  11128. // 检查全局中是否已存在相同的角色
  11129. $exists = false;
  11130. $global_role_index = -1;
  11131. foreach ($global_roles as $index => $global_role) {
  11132. $global_role_name = getProp($global_role, 'role');
  11133. $global_description = getProp($global_role, 'description');
  11134. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11135. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11136. if ($episode_role_name == $global_role_name
  11137. && $episode_description == $global_description
  11138. && $episode_pic_prompt == $global_pic_prompt) {
  11139. $exists = true;
  11140. $global_role_index = $index;
  11141. break;
  11142. }
  11143. }
  11144. // 如果不存在,则添加到全局
  11145. if (!$exists) {
  11146. $global_roles[] = $episode_role;
  11147. $roles_added = true;
  11148. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11149. 'anime_id' => $anime_id,
  11150. 'role' => $episode_role_name
  11151. ]);
  11152. } else {
  11153. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11154. if (!empty($episode_voice_prompt)) {
  11155. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11156. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11157. if ($global_voice_prompt !== $episode_voice_prompt) {
  11158. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11159. $roles_updated = true;
  11160. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11161. 'anime_id' => $anime_id,
  11162. 'role' => $episode_role_name,
  11163. 'voice_prompt' => $episode_voice_prompt
  11164. ]);
  11165. }
  11166. }
  11167. }
  11168. }
  11169. // 处理场景同步
  11170. foreach ($episode_scenes as $episode_scene) {
  11171. $episode_scene_name = getProp($episode_scene, 'scene');
  11172. $episode_description = getProp($episode_scene, 'description');
  11173. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11174. // 检查全局中是否已存在相同的场景
  11175. $exists = false;
  11176. foreach ($global_scenes as $global_scene) {
  11177. $global_scene_name = getProp($global_scene, 'scene');
  11178. $global_description = getProp($global_scene, 'description');
  11179. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11180. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  11181. if ($episode_scene_name == $global_scene_name
  11182. && $episode_description == $global_description
  11183. && $episode_pic_prompt == $global_pic_prompt) {
  11184. $exists = true;
  11185. break;
  11186. }
  11187. }
  11188. // 如果不存在,则添加到全局
  11189. if (!$exists) {
  11190. $global_scenes[] = $episode_scene;
  11191. $scenes_added = true;
  11192. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  11193. 'anime_id' => $anime_id,
  11194. 'scene' => $episode_scene_name
  11195. ]);
  11196. }
  11197. }
  11198. // 处理道具同步(逻辑与场景一致)
  11199. foreach ($episode_props as $episode_prop) {
  11200. $episode_prop_name = getProp($episode_prop, 'prop');
  11201. $episode_description = getProp($episode_prop, 'description');
  11202. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  11203. // 检查全局中是否已存在相同的道具
  11204. $exists = false;
  11205. foreach ($global_props as $global_prop) {
  11206. $global_prop_name = getProp($global_prop, 'prop');
  11207. $global_description = getProp($global_prop, 'description');
  11208. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  11209. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  11210. if ($episode_prop_name == $global_prop_name
  11211. && $episode_description == $global_description
  11212. && $episode_pic_prompt == $global_pic_prompt) {
  11213. $exists = true;
  11214. break;
  11215. }
  11216. }
  11217. // 如果不存在,则添加到全局
  11218. if (!$exists) {
  11219. $global_props[] = $episode_prop;
  11220. $props_added = true;
  11221. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  11222. 'anime_id' => $anime_id,
  11223. 'prop' => $episode_prop_name
  11224. ]);
  11225. }
  11226. }
  11227. // 如果有新增或更新,则更新全局数据
  11228. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  11229. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11230. if ($roles_added || $roles_updated) {
  11231. $update_data['roles'] = json_encode($global_roles, 256);
  11232. }
  11233. if ($scenes_added) {
  11234. $update_data['scenes'] = json_encode($global_scenes, 256);
  11235. }
  11236. if ($props_added) {
  11237. $update_data['props'] = json_encode($global_props, 256);
  11238. }
  11239. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11240. dLog('deepseek')->info('剧集数据同步到全局完成', [
  11241. 'anime_id' => $anime_id,
  11242. 'roles_added' => $roles_added,
  11243. 'roles_updated' => $roles_updated,
  11244. 'scenes_added' => $scenes_added,
  11245. 'props_added' => $props_added,
  11246. 'global_roles_count' => count($global_roles),
  11247. 'global_scenes_count' => count($global_scenes),
  11248. 'global_props_count' => count($global_props)
  11249. ]);
  11250. }
  11251. return true;
  11252. }
  11253. /**
  11254. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  11255. *
  11256. * @param int $anime_id 动漫对话ID
  11257. * @param int $episode_id 分集ID
  11258. * @return bool
  11259. */
  11260. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  11261. // 获取全局角色和场景数据
  11262. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11263. if (!$anime) {
  11264. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11265. return false;
  11266. }
  11267. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11268. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11269. // 获取指定的分集
  11270. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  11271. if (!$episode) {
  11272. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11273. return false;
  11274. }
  11275. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11276. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11277. $roles_updated = false;
  11278. $scenes_updated = false;
  11279. // 继承角色的task_id、task_status和url
  11280. foreach ($episode_roles as &$episode_role) {
  11281. $episode_role_name = getProp($episode_role, 'role');
  11282. $episode_description = getProp($episode_role, 'description');
  11283. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11284. $episode_url = getProp($episode_role, 'url');
  11285. // 跳过旁白角色
  11286. if ($episode_role_name == '旁白') {
  11287. continue;
  11288. }
  11289. // 如果剧集中已有URL,跳过
  11290. if (!empty($episode_url)) {
  11291. continue;
  11292. }
  11293. // 遍历全局角色数据,查找匹配的角色
  11294. foreach ($global_roles as $global_role) {
  11295. $global_role_name = getProp($global_role, 'role');
  11296. $global_description = getProp($global_role, 'description');
  11297. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11298. $global_url = getProp($global_role, 'url');
  11299. $global_task_id = getProp($global_role, 'task_id');
  11300. $global_task_status = getProp($global_role, 'task_status');
  11301. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11302. if ($episode_role_name == $global_role_name
  11303. && $episode_description == $global_description
  11304. && $episode_pic_prompt == $global_pic_prompt) {
  11305. // 继承 task_id、task_status 和 url
  11306. if (!empty($global_task_id)) {
  11307. $episode_role['task_id'] = $global_task_id;
  11308. $episode_role['task_status'] = $global_task_status;
  11309. $roles_updated = true;
  11310. dLog('deepseek')->info('剧集角色继承全局task_id', [
  11311. 'episode_id' => $episode_id,
  11312. 'role' => $episode_role_name,
  11313. 'task_id' => $global_task_id,
  11314. 'task_status' => $global_task_status
  11315. ]);
  11316. }
  11317. if (!empty($global_url)) {
  11318. $episode_role['url'] = $global_url;
  11319. $roles_updated = true;
  11320. dLog('deepseek')->info('剧集角色继承全局url', [
  11321. 'episode_id' => $episode_id,
  11322. 'role' => $episode_role_name,
  11323. 'url' => $global_url
  11324. ]);
  11325. }
  11326. break;
  11327. }
  11328. }
  11329. }
  11330. // 继承场景的task_id、task_status和url
  11331. foreach ($episode_scenes as &$episode_scene) {
  11332. $episode_scene_name = getProp($episode_scene, 'scene');
  11333. $episode_description = getProp($episode_scene, 'description');
  11334. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11335. $episode_url = getProp($episode_scene, 'url');
  11336. // 如果剧集中已有URL,跳过
  11337. if (!empty($episode_url)) {
  11338. continue;
  11339. }
  11340. // 遍历全局场景数据,查找匹配的场景
  11341. foreach ($global_scenes as $global_scene) {
  11342. $global_scene_name = getProp($global_scene, 'scene');
  11343. $global_description = getProp($global_scene, 'description');
  11344. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11345. $global_url = getProp($global_scene, 'url');
  11346. $global_task_id = getProp($global_scene, 'task_id');
  11347. $global_task_status = getProp($global_scene, 'task_status');
  11348. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11349. if ($episode_scene_name == $global_scene_name
  11350. && $episode_description == $global_description
  11351. && $episode_pic_prompt == $global_pic_prompt) {
  11352. // 继承 task_id、task_status 和 url
  11353. if (!empty($global_task_id)) {
  11354. $episode_scene['task_id'] = $global_task_id;
  11355. $episode_scene['task_status'] = $global_task_status;
  11356. $scenes_updated = true;
  11357. dLog('deepseek')->info('剧集场景继承全局task_id', [
  11358. 'episode_id' => $episode_id,
  11359. 'scene' => $episode_scene_name,
  11360. 'task_id' => $global_task_id,
  11361. 'task_status' => $global_task_status
  11362. ]);
  11363. }
  11364. if (!empty($global_url)) {
  11365. $episode_scene['url'] = $global_url;
  11366. $scenes_updated = true;
  11367. dLog('deepseek')->info('剧集场景继承全局url', [
  11368. 'episode_id' => $episode_id,
  11369. 'scene' => $episode_scene_name,
  11370. 'url' => $global_url
  11371. ]);
  11372. }
  11373. break;
  11374. }
  11375. }
  11376. }
  11377. // 如果有更新,则保存到数据库
  11378. if ($roles_updated || $scenes_updated) {
  11379. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11380. if ($roles_updated) {
  11381. $update_data['roles'] = json_encode($episode_roles, 256);
  11382. }
  11383. if ($scenes_updated) {
  11384. $update_data['scenes'] = json_encode($episode_scenes, 256);
  11385. }
  11386. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  11387. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  11388. 'episode_id' => $episode_id,
  11389. 'roles_updated' => $roles_updated,
  11390. 'scenes_updated' => $scenes_updated
  11391. ]);
  11392. }
  11393. return true;
  11394. }
  11395. public function chatChangeImg($data) {
  11396. $segment = getProp($data, 'segment');
  11397. $segment_content = getProp($segment, 'segment_content');
  11398. $prompt = getProp($data, 'prompt');
  11399. $ref_img = getProp($data, 'ref_img');
  11400. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  11401. // 处理文本模型
  11402. $model = getProp($data, 'model');
  11403. if (!$model) {
  11404. // 用户没有输入,从anime表获取
  11405. $segment_id = getProp($segment, 'segment_id');
  11406. if ($segment_id) {
  11407. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  11408. if ($episode_id) {
  11409. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  11410. if ($anime_id) {
  11411. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  11412. }
  11413. }
  11414. }
  11415. if (!$model) {
  11416. // anime表也没有,使用默认值
  11417. $model = 'doubao-seed-2-0-mini-260215';
  11418. }
  11419. }
  11420. // 验证模型是否在可用模型表中
  11421. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11422. $model = 'doubao-seed-2-0-mini-260215';
  11423. }
  11424. $messages[] =
  11425. [
  11426. 'role' => 'user',
  11427. 'content' => $question
  11428. ];
  11429. $post_data = [
  11430. 'model' => $model,
  11431. 'messages' => $messages,
  11432. // 'max_tokens' => 8192,
  11433. 'temperature' => 0.7,
  11434. 'frequency_penalty' => 0,
  11435. 'presence_penalty' => 0,
  11436. 'response_format' => ['type' => 'text'],
  11437. 'stream' => false // 是否启用流式输出
  11438. ];
  11439. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11440. // DeepSeek 官方模型使用 DeepSeek API
  11441. $chatResult = $this->chatOnly($post_data);
  11442. } else if (in_array($model, $this->gpt_text_models)) {
  11443. // GPT-5.4 模型使用 TokenRouter API
  11444. $chatResult = $this->gpt54ChatOnly($post_data);
  11445. } else {
  11446. // 其他模型使用火山引擎API
  11447. $chatResult = $this->volcEngineChatCompletion($post_data);
  11448. }
  11449. if (is_array($chatResult)) {
  11450. extract($chatResult);
  11451. }else {
  11452. Utils::throwError('20003: 接口调用失败!');
  11453. }
  11454. return [
  11455. 'type' => 'done',
  11456. // 'episode' => $episode,
  11457. 'answer' => $fullContent,
  11458. 'reasoning' => $fullReasoningContent,
  11459. 'usage' => $usage
  11460. ];
  11461. }
  11462. // 仅调用deepseek对话接口
  11463. private function chatOnly($post_data) {
  11464. $post_data['max_tokens'] = 300000;
  11465. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11466. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  11467. $response = $result->getBody()->getContents();
  11468. $response_arr = json_decode($response, true);
  11469. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  11470. $fullContent = '';
  11471. $fullReasoningContent = [];
  11472. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11473. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11474. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11475. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  11476. }
  11477. return [
  11478. 'fullContent' => $fullContent,
  11479. 'fullReasoningContent' => $fullReasoningContent,
  11480. 'usage' => $usage
  11481. ];
  11482. }
  11483. // 仅调用 GPT-5.4 对话接口(非流式)
  11484. private function gpt54ChatOnly($post_data) {
  11485. $apiKey = env('GPT_54_API_KEY');
  11486. if (empty($apiKey)) {
  11487. Utils::throwError('20003:GPT-5.4 API Key未配置');
  11488. }
  11489. // 先探活,服务不可用时自动重试
  11490. $this->ensureGptServiceAvailable();
  11491. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11492. $headers = [
  11493. 'Authorization' => 'Bearer ' . $apiKey,
  11494. 'Content-Type' => 'application/json'
  11495. ];
  11496. // 移除 thinking 参数,GPT-5.4 不支持
  11497. if (isset($post_data['thinking'])) {
  11498. unset($post_data['thinking']);
  11499. }
  11500. if (isset($post_data['reasoning_effort'])) {
  11501. unset($post_data['reasoning_effort']);
  11502. }
  11503. $post_data['max_completion_tokens'] = 100000;
  11504. // 确保 stream 为 false
  11505. $post_data['stream'] = false;
  11506. $maxRetries = $this->gptRetryTimes();
  11507. $interval = $this->gptRetryInterval();
  11508. $attempt = 0;
  11509. while (true) {
  11510. try {
  11511. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  11512. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  11513. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  11514. 'json' => $post_data,
  11515. 'headers' => $headers
  11516. ]);
  11517. $response = $result->getBody()->getContents();
  11518. $response_arr = json_decode($response, true);
  11519. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  11520. $fullContent = '';
  11521. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11522. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11523. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11524. }
  11525. return [
  11526. 'fullContent' => $fullContent,
  11527. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  11528. 'usage' => $usage
  11529. ];
  11530. } catch (\Exception $e) {
  11531. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  11532. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  11533. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  11534. throw $e;
  11535. }
  11536. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  11537. 'retry' => $attempt + 1,
  11538. 'max_retries' => $maxRetries,
  11539. 'error' => $e->getMessage()
  11540. ]);
  11541. sleep($interval);
  11542. $attempt++;
  11543. }
  11544. }
  11545. }
  11546. private function splitContent($content) {
  11547. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  11548. $chapters = [];
  11549. // 匹配章节标题格式:
  11550. // 1. 标题可能独占一行,也可能在正文末尾或中间
  11551. // 2. 格式支持:
  11552. // - **第一集**
  11553. // - 第一集:
  11554. // - ###第1章 重生
  11555. // - ##第2章 相救
  11556. // - 第三章 共处一室
  11557. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  11558. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  11559. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  11560. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  11561. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  11562. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  11563. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  11564. // 先在每个标题前插入换行符(如果前面不是换行的话)
  11565. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  11566. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  11567. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  11568. // 用正则找出所有章节标题的位置
  11569. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  11570. $titleCount = count($matches[0]);
  11571. for ($i = 0; $i < $titleCount; $i++) {
  11572. // 获取当前章节标题
  11573. $titleLine = trim($matches[0][$i][0]);
  11574. // 去除标题开头的特殊符号
  11575. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  11576. // 去除标题结尾的冒号和特殊符号
  11577. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  11578. $cleanTitle = trim($cleanTitle);
  11579. // 获取当前标题的结束位置
  11580. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  11581. // 获取下一个章节标题的开始位置(如果存在)
  11582. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  11583. // 提取章节内容(从标题结束到下一个标题开始)
  11584. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  11585. // 清理内容:去除前后空白和分隔线
  11586. $chapterContent = trim($chapterContent);
  11587. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  11588. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  11589. if (!empty($cleanTitle) && !empty($chapterContent)) {
  11590. $chapters[] = [
  11591. 'title' => $cleanTitle,
  11592. 'content' => $chapterContent
  11593. ];
  11594. }
  11595. }
  11596. } else {
  11597. // 如果没有匹配到章节,返回整个内容
  11598. $chapters[] = [
  11599. 'title' => '',
  11600. 'content' => $content
  11601. ];
  11602. }
  11603. return $chapters;
  11604. }
  11605. public function getContentByBid($bid) {
  11606. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  11607. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  11608. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  11609. $content = '';
  11610. foreach ($chapters as $chapter) {
  11611. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  11612. }
  11613. return $content;
  11614. }
  11615. public function getContentByScriptId($script_id) {
  11616. $content = '';
  11617. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  11618. if ($contents) {
  11619. $content = implode(PHP_EOL, $contents);
  11620. }else {
  11621. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  11622. }
  11623. return $content;
  11624. }
  11625. /**
  11626. * 根据文件类型提取文本内容
  11627. *
  11628. * @param mixed $file 文件对象或文件路径
  11629. * @return string
  11630. */
  11631. public function extractFileContent($file) {
  11632. // 获取文件路径和扩展名
  11633. if (is_string($file)) {
  11634. $filePath = $file;
  11635. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  11636. } else {
  11637. // Laravel UploadedFile 对象
  11638. $filePath = $file->getRealPath();
  11639. $extension = strtolower($file->getClientOriginalExtension());
  11640. }
  11641. $content = '';
  11642. switch ($extension) {
  11643. case 'txt':
  11644. $content = $this->extractTxtContent($filePath);
  11645. break;
  11646. case 'pdf':
  11647. $content = $this->extractPdfContent($filePath);
  11648. break;
  11649. case 'doc':
  11650. case 'docx':
  11651. $content = $this->extractWordContent($filePath);
  11652. break;
  11653. // case 'jpg':
  11654. // case 'jpeg':
  11655. // case 'png':
  11656. // case 'gif':
  11657. // case 'bmp':
  11658. // case 'webp':
  11659. // $content = $this->extractImageContent($filePath);
  11660. // break;
  11661. default:
  11662. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  11663. }
  11664. return $content;
  11665. }
  11666. /**
  11667. * 提取 TXT 文件内容
  11668. */
  11669. private function extractTxtContent($filePath) {
  11670. if (!file_exists($filePath)) {
  11671. Utils::throwError('20003:文件不存在');
  11672. }
  11673. $content = file_get_contents($filePath);
  11674. // 尝试检测并转换编码
  11675. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  11676. if ($encoding && $encoding !== 'UTF-8') {
  11677. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  11678. }
  11679. return trim($content);
  11680. }
  11681. /**
  11682. * 提取 PDF 文件内容
  11683. */
  11684. private function extractPdfContent($filePath) {
  11685. if (!file_exists($filePath)) {
  11686. Utils::throwError('20003:文件不存在');
  11687. }
  11688. try {
  11689. $parser = new PdfParser();
  11690. $pdf = $parser->parseFile($filePath);
  11691. $content = $pdf->getText();
  11692. return trim($content);
  11693. } catch (\Exception $e) {
  11694. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  11695. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  11696. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  11697. }
  11698. }
  11699. /**
  11700. * 提取 Word 文件内容(支持 doc 和 docx)
  11701. */
  11702. private function extractWordContent($filePath) {
  11703. if (!file_exists($filePath)) {
  11704. Utils::throwError('20003:文件不存在');
  11705. }
  11706. try {
  11707. $phpWord = WordIOFactory::load($filePath);
  11708. $content = '';
  11709. foreach ($phpWord->getSections() as $section) {
  11710. foreach ($section->getElements() as $element) {
  11711. $content .= $this->extractWordElementText($element);
  11712. }
  11713. }
  11714. return trim($content);
  11715. } catch (\Exception $e) {
  11716. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  11717. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  11718. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  11719. }
  11720. }
  11721. /**
  11722. * 递归提取 Word 元素中的文本
  11723. */
  11724. private function extractWordElementText($element) {
  11725. $text = '';
  11726. if (method_exists($element, 'getText')) {
  11727. $text .= $element->getText() . "\n";
  11728. } elseif (method_exists($element, 'getElements')) {
  11729. foreach ($element->getElements() as $childElement) {
  11730. $text .= $this->extractWordElementText($childElement);
  11731. }
  11732. }
  11733. return $text;
  11734. }
  11735. /**
  11736. * 提取图片内容(使用火山引擎 OCR)
  11737. */
  11738. private function extractImageContent($filePath) {
  11739. if (!file_exists($filePath)) {
  11740. Utils::throwError('20003:文件不存在');
  11741. }
  11742. try {
  11743. // 读取图片并转换为 base64
  11744. $imageData = file_get_contents($filePath);
  11745. $base64Image = base64_encode($imageData);
  11746. // 调用火山引擎 OCR 服务
  11747. $content = $this->callVolcEngineOCR($base64Image);
  11748. return trim($content);
  11749. } catch (\Exception $e) {
  11750. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  11751. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  11752. Utils::throwError('20003:图片识别失败');
  11753. }
  11754. }
  11755. /**
  11756. * 调用火山引擎 OCR 服务识别图片文字
  11757. *
  11758. * @param string $base64Image base64 编码的图片数据
  11759. * @return string 识别的文字内容
  11760. */
  11761. private function callVolcEngineOCR($base64Image) {
  11762. $method = 'POST';
  11763. $service = 'cv';
  11764. $host = 'visual.volcengineapi.com';
  11765. $region = env('VOLC_REGION', 'cn-north-1');
  11766. $access_key = env('VOLC_AK');
  11767. $secret_key = env('VOLC_SK');
  11768. $action = 'OCRNormal';
  11769. $version = '2020-08-26';
  11770. if (!$access_key || !$secret_key) {
  11771. Utils::throwError('20003:请配置火山引擎 AK/SK');
  11772. }
  11773. // 请求体
  11774. $body = json_encode([
  11775. 'image_base64' => $base64Image
  11776. ]);
  11777. // 生成签名
  11778. $headers = $this->getVolcEngineSignHeaders(
  11779. $method, $service, $host, $region,
  11780. "Action={$action}&Version={$version}",
  11781. $access_key, $secret_key, $body
  11782. );
  11783. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11784. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  11785. 'headers' => $headers,
  11786. 'body' => $body
  11787. ]);
  11788. $response_arr = json_decode($response->getBody()->getContents(), true);
  11789. // 提取识别的文字
  11790. $textLines = [];
  11791. if (isset($response_arr['data']['line_texts'])) {
  11792. $textLines = $response_arr['data']['line_texts'];
  11793. } elseif (isset($response_arr['data']['ocr_infos'])) {
  11794. foreach ($response_arr['data']['ocr_infos'] as $info) {
  11795. if (isset($info['text'])) {
  11796. $textLines[] = $info['text'];
  11797. }
  11798. }
  11799. }
  11800. if (empty($textLines)) {
  11801. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  11802. return '';
  11803. }
  11804. return implode("\n", $textLines);
  11805. }
  11806. /**
  11807. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  11808. */
  11809. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  11810. $contentType = 'application/json';
  11811. $accept = 'application/json';
  11812. // 获取当前UTC时间
  11813. $t = new DateTime('now', new DateTimeZone('UTC'));
  11814. $xDate = $t->format('Ymd\THis\Z');
  11815. $dateStamp = $t->format('Ymd');
  11816. // 计算 body 的 sha256 哈希
  11817. $payloadHash = hash('sha256', $body);
  11818. // 1. 拼接规范请求串
  11819. $canonicalUri = '/';
  11820. $canonicalQueryString = $queryString;
  11821. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  11822. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  11823. $canonicalRequest = implode("\n", [
  11824. $method,
  11825. $canonicalUri,
  11826. $canonicalQueryString,
  11827. $canonicalHeaders,
  11828. $signedHeaders,
  11829. $payloadHash
  11830. ]);
  11831. // 2. 拼接待签名字符串
  11832. $algorithm = 'HMAC-SHA256';
  11833. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  11834. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  11835. $stringToSign = implode("\n", [
  11836. $algorithm,
  11837. $xDate,
  11838. $credentialScope,
  11839. $hashedCanonicalRequest
  11840. ]);
  11841. // 3. 计算签名
  11842. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  11843. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  11844. // 4. 添加签名到请求头
  11845. $authorizationHeader = sprintf(
  11846. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  11847. $algorithm,
  11848. $access_key,
  11849. $credentialScope,
  11850. $signedHeaders,
  11851. $signature
  11852. );
  11853. return [
  11854. 'Accept' => $accept,
  11855. 'Content-Type' => $contentType,
  11856. 'Host' => $host,
  11857. 'X-Date' => $xDate,
  11858. 'X-Content-Sha256'=> $payloadHash,
  11859. 'Authorization' => $authorizationHeader
  11860. ];
  11861. }
  11862. public function generateScriptWords($cid, $model = 'r1') {
  11863. ini_set('max_execution_time', 0);
  11864. if (!$cid) Utils::throwError('20003: 请选择章节!');
  11865. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  11866. // 模型兼容性处理和思考模式设置
  11867. $thinkingMode = 'disabled';
  11868. $reasoningEffort = 'high';
  11869. if ($model == 'r1') {
  11870. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  11871. $thinkingMode = 'enabled';
  11872. } else {
  11873. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  11874. $thinkingMode = 'disabled';
  11875. }
  11876. $messages = [
  11877. [
  11878. 'role' => 'system',
  11879. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  11880. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  11881. 2.非对话部分请全部用旁白角色代替
  11882. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  11883. ],
  11884. [
  11885. 'role' => 'user',
  11886. 'content' => $content
  11887. ]
  11888. ];
  11889. $post_data = [
  11890. 'model' => $model,
  11891. 'messages' => $messages,
  11892. // 'max_tokens' => 8192,
  11893. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11894. 'frequency_penalty' => 0,
  11895. 'presence_penalty' => 0,
  11896. 'thinking' => ['type' => $thinkingMode],
  11897. 'response_format' => [
  11898. 'type' => 'text'
  11899. ],
  11900. 'stream' => false
  11901. ];
  11902. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11903. // 根据模型类型选择调用方法
  11904. $fullContent = '';
  11905. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11906. // DeepSeek 官方模型使用 DeepSeek API
  11907. $chatResult = $this->chatOnly($post_data);
  11908. } else if (in_array($model, $this->gpt_text_models)) {
  11909. // GPT-5.4 模型使用 TokenRouter API
  11910. $chatResult = $this->gpt54ChatOnly($post_data);
  11911. } else {
  11912. // 其他模型使用火山引擎API
  11913. $chatResult = $this->volcEngineChatCompletion($post_data);
  11914. }
  11915. if (is_array($chatResult)) {
  11916. $fullContent = $chatResult['fullContent'];
  11917. }
  11918. return $fullContent;
  11919. }
  11920. /**
  11921. * 智能化解析集数信息
  11922. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11923. *
  11924. * @param string $prompt 用户输入的提示词
  11925. * @return int|null 解析出的集数,如果没有找到则返回null
  11926. */
  11927. private function extractEpisodeNumber($prompt)
  11928. {
  11929. if (empty($prompt)) {
  11930. return null;
  11931. }
  11932. // 定义各种可能的表达模式
  11933. $patterns = [
  11934. // 基本模式:改成N集、调整成N集、修改成N集
  11935. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11936. // 扩展模式:分成N集、拆分成N集、分割成N集
  11937. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11938. // 数量模式:N集、共N集、总共N集
  11939. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11940. // 制作模式:制作N集、生成N集、创建N集
  11941. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11942. // 计划模式:计划N集、预计N集、打算N集
  11943. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11944. // 需要模式:需要N集、要N集
  11945. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11946. // 中文数字模式:改成三集、调整成五集等
  11947. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11948. // 英文数字模式
  11949. '/(?:change\s+to|adjust\s+to|modify\s+to|set\s+to|make\s+it|split\s+into|divide\s+into)\s*(\d+)\s*(?:episodes?|eps?)/i',
  11950. ];
  11951. // 中文数字转阿拉伯数字的映射
  11952. $chineseNumbers = [
  11953. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11954. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11955. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11956. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11957. ];
  11958. // 逐个尝试匹配模式
  11959. foreach ($patterns as $pattern) {
  11960. if (preg_match($pattern, $prompt, $matches)) {
  11961. $number = trim($matches[1]);
  11962. // 如果是中文数字,转换为阿拉伯数字
  11963. if (isset($chineseNumbers[$number])) {
  11964. return $chineseNumbers[$number];
  11965. }
  11966. // 如果是阿拉伯数字,直接返回
  11967. if (is_numeric($number)) {
  11968. $episodeNum = intval($number);
  11969. // 合理性检查:集数应该在1-100之间
  11970. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11971. return $episodeNum;
  11972. }
  11973. }
  11974. }
  11975. }
  11976. return null;
  11977. }
  11978. /**
  11979. * 调用火山引擎对话(Chat) API
  11980. *
  11981. * @param array $params 包含以下参数:
  11982. * - model: 模型ID(必填)
  11983. * - messages: 消息列表(必填)
  11984. * - stream: 是否流式输出(可选,默认false)
  11985. * - max_tokens: 最大输出token数(可选)
  11986. * - temperature: 采样温度(可选,默认1)
  11987. * - top_p: 核采样概率(可选,默认0.7)
  11988. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11989. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11990. * - stop: 停止词(可选)
  11991. * - tools: 工具列表(可选)
  11992. * @return array|Generator 非流式返回数组,流式返回生成器
  11993. */
  11994. public function volcEngineChatCompletion(array $params)
  11995. {
  11996. $apiKey = env('VOLC_AI_API_KEY');
  11997. if (empty($apiKey)) {
  11998. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11999. }
  12000. // 构建请求参数
  12001. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  12002. $requestData = [
  12003. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  12004. 'messages' => $params['messages'] ?? [],
  12005. ];
  12006. if (!in_array($originalModel, $this->valid_text_models)) {
  12007. Utils::throwError('20003:该模型不支持!');
  12008. }
  12009. // 添加可选参数
  12010. if (isset($params['stream'])) {
  12011. $requestData['stream'] = $params['stream'];
  12012. }
  12013. if (isset($params['stream_options'])) {
  12014. $requestData['stream_options'] = $params['stream_options'];
  12015. }
  12016. if (isset($params['max_tokens'])) {
  12017. $requestData['max_tokens'] = $params['max_tokens'];
  12018. }else if (isset($params['max_completion_tokens'])) {
  12019. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  12020. }else {
  12021. $requestData['max_completion_tokens'] = 100000;
  12022. }
  12023. if (isset($params['temperature'])) {
  12024. $requestData['temperature'] = $params['temperature'];
  12025. }
  12026. if (isset($params['top_p'])) {
  12027. $requestData['top_p'] = $params['top_p'];
  12028. }
  12029. if (isset($params['frequency_penalty'])) {
  12030. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  12031. }
  12032. if (isset($params['presence_penalty'])) {
  12033. $requestData['presence_penalty'] = $params['presence_penalty'];
  12034. }
  12035. if (isset($params['stop'])) {
  12036. $requestData['stop'] = $params['stop'];
  12037. }
  12038. if (isset($params['tools'])) {
  12039. $requestData['tools'] = $params['tools'];
  12040. }
  12041. if (isset($params['tool_choice'])) {
  12042. $requestData['tool_choice'] = $params['tool_choice'];
  12043. }
  12044. if (isset($params['response_format'])) {
  12045. $requestData['response_format'] = $params['response_format'];
  12046. }
  12047. if (isset($params['thinking'])) {
  12048. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  12049. if (is_array($params['thinking'])) {
  12050. $requestData['thinking'] = $params['thinking'];
  12051. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  12052. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12053. }
  12054. } else {
  12055. $requestData['thinking'] = ['type' => $params['thinking']];
  12056. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12057. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12058. }
  12059. }
  12060. } else {
  12061. $requestData['thinking'] = ['type' => 'disabled'];
  12062. }
  12063. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12064. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12065. try {
  12066. // 判断是否为流式输出
  12067. $isStream = isset($params['stream']) && $params['stream'] === true;
  12068. if ($isStream) {
  12069. // 流式输出
  12070. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12071. } else {
  12072. // 非流式输出
  12073. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12074. 'headers' => [
  12075. 'Authorization' => 'Bearer ' . $apiKey,
  12076. 'Content-Type' => 'application/json',
  12077. ],
  12078. 'json' => $requestData
  12079. ]);
  12080. $responseData = json_decode($response->getBody(), true);
  12081. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12082. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12083. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12084. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12085. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12086. }
  12087. return [
  12088. 'fullContent' => $fullContent,
  12089. 'fullReasoningContent' => $fullReasoningContent,
  12090. 'usage' => $usage
  12091. ];
  12092. }
  12093. } catch (\Exception $e) {
  12094. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12095. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12096. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12097. }
  12098. }
  12099. /**
  12100. * 火山引擎对话API流式输出
  12101. *
  12102. * @param Client $client HTTP客户端
  12103. * @param string $apiKey API密钥
  12104. * @param array $requestData 请求数据
  12105. * @return Generator
  12106. */
  12107. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12108. {
  12109. try {
  12110. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12111. 'headers' => [
  12112. 'Authorization' => 'Bearer ' . $apiKey,
  12113. 'Content-Type' => 'application/json',
  12114. ],
  12115. 'json' => $requestData,
  12116. 'stream' => true
  12117. ]);
  12118. $body = $response->getBody();
  12119. $buffer = '';
  12120. $fullContent = '';
  12121. $fullReasoningContent = '';
  12122. $usage = [];
  12123. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  12124. // 逐行读取流式响应
  12125. while (!$body->eof()) {
  12126. $chunk = $body->read(1024);
  12127. $buffer .= $chunk;
  12128. // 按行分割
  12129. $lines = explode("\n", $buffer);
  12130. $buffer = array_pop($lines);
  12131. foreach ($lines as $line) {
  12132. $line = trim($line);
  12133. if (empty($line)) {
  12134. continue;
  12135. }
  12136. // 检查是否是SSE数据行
  12137. if (strpos($line, 'data: ') !== 0) {
  12138. continue;
  12139. }
  12140. $data = substr($line, 6);
  12141. if ($data === '[DONE]') {
  12142. dLog('deepseek')->info('收到结束标记');
  12143. break 2;
  12144. }
  12145. try {
  12146. $json = json_decode($data, true);
  12147. if (json_last_error() !== JSON_ERROR_NONE) {
  12148. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  12149. continue;
  12150. }
  12151. if (isset($json['choices'][0]['delta'])) {
  12152. $delta = $json['choices'][0]['delta'];
  12153. // 处理思维链内容
  12154. if (isset($delta['reasoning_content'])) {
  12155. $fullReasoningContent .= $delta['reasoning_content'];
  12156. yield [
  12157. 'type' => 'reasoning',
  12158. 'content' => $delta['reasoning_content'],
  12159. 'full_reasoning' => $fullReasoningContent
  12160. ];
  12161. }
  12162. // 处理回答内容
  12163. if (isset($delta['content'])) {
  12164. $fullContent .= $delta['content'];
  12165. yield [
  12166. 'type' => 'content',
  12167. 'content' => $delta['content'],
  12168. ];
  12169. }
  12170. }
  12171. // 获取使用统计信息
  12172. if (isset($json['usage'])) {
  12173. $usage = $json['usage'];
  12174. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  12175. }
  12176. } catch (\Exception $e) {
  12177. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  12178. continue;
  12179. }
  12180. }
  12181. }
  12182. dLog('deepseek')->info('流式读取完成', [
  12183. 'content_length' => strlen($fullContent),
  12184. 'reasoning_length' => strlen($fullReasoningContent)
  12185. ]);
  12186. yield [
  12187. 'type' => 'done',
  12188. 'full_content' => $fullContent,
  12189. 'full_reasoning' => $fullReasoningContent,
  12190. 'usage' => $usage
  12191. ];
  12192. } catch (\Exception $e) {
  12193. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  12194. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  12195. throw $e;
  12196. }
  12197. }
  12198. /**
  12199. * 检查并创建图片生成任务
  12200. *
  12201. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  12202. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  12203. * @param string $nameKey 资源名称字段('role' 或 'scene')
  12204. * @param string $art_style 美术风格
  12205. * @return array 更新后的资源列表
  12206. */
  12207. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  12208. {
  12209. // 确保参数为数组
  12210. $merged_items = is_array($merged_items) ? $merged_items : [];
  12211. $global_items = is_array($global_items) ? $global_items : [];
  12212. // 构建全局资源映射表,用于快速查找
  12213. $global_map = [];
  12214. foreach ($global_items as $item) {
  12215. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12216. if ($itemKey === '') {
  12217. continue;
  12218. }
  12219. $global_map[$itemKey] = $item;
  12220. }
  12221. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  12222. foreach ($merged_items as &$item) {
  12223. $item_name = getProp($item, $nameKey);
  12224. $item_description = getProp($item, 'description');
  12225. // $item_url = getProp($item, 'url');
  12226. // // 如果已有图片URL,跳过
  12227. // if (!empty($item_url)) {
  12228. // continue;
  12229. // }
  12230. // 如果是旁白角色,跳过
  12231. if ($nameKey === 'role' && $item_name === '旁白') {
  12232. continue;
  12233. }
  12234. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  12235. if ($itemKey === '') {
  12236. continue;
  12237. }
  12238. $need_create_task = false;
  12239. // 条件1:在全局资源中找不到匹配的名称
  12240. if (!isset($global_map[$itemKey])) {
  12241. $need_create_task = true;
  12242. } else {
  12243. // 条件2:名称匹配但描述或 pic_prompt 不一致
  12244. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  12245. $current_description = trim((string)$item_description);
  12246. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  12247. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  12248. // 如果 description 或 pic_prompt 有变化,需要重新生成
  12249. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  12250. $need_create_task = true;
  12251. }
  12252. }
  12253. // 如果需要创建任务,调用图片生成服务
  12254. if ($need_create_task) {
  12255. try {
  12256. // 优先使用 pic_prompt,如果没有则使用 description
  12257. $pic_prompt = getProp($item, 'pic_prompt');
  12258. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  12259. // 添加美术风格前缀
  12260. if ($art_style) {
  12261. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  12262. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  12263. $description = "{$prefix}:{$description}";
  12264. }
  12265. $params = [
  12266. 'prompt' => $description,
  12267. 'ref_img_urls' => []
  12268. ];
  12269. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12270. $task_id = $task->id;
  12271. if ($task_id) {
  12272. $item['task_id'] = $task_id;
  12273. $item['task_status'] = 'processing';
  12274. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12275. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  12276. }
  12277. } catch (\Exception $e) {
  12278. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12279. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  12280. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  12281. // 不抛出异常,继续处理其他资源
  12282. }
  12283. }
  12284. }
  12285. return $merged_items;
  12286. }
  12287. /**
  12288. * 同步新出现的主体和场景到全局
  12289. *
  12290. * @param int $anime_id 动漫ID
  12291. * @param array $merged_roles 合并后的角色列表
  12292. * @param array $merged_scenes 合并后的场景列表
  12293. * @param array $global_roles 全局角色列表
  12294. * @param array $global_scenes 全局场景列表
  12295. * @return void
  12296. */
  12297. private function syncNewResourcesToGlobal(
  12298. int $anime_id,
  12299. array $merged_roles,
  12300. array $merged_scenes,
  12301. array $global_roles,
  12302. array $global_scenes
  12303. ): void {
  12304. // 构建全局角色映射表
  12305. $global_role_map = [];
  12306. foreach ($global_roles as $role) {
  12307. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  12308. if ($roleKey !== '') {
  12309. $global_role_map[$roleKey] = $role;
  12310. }
  12311. }
  12312. // 构建全局场景映射表
  12313. $global_scene_map = [];
  12314. foreach ($global_scenes as $scene) {
  12315. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  12316. if ($sceneKey !== '') {
  12317. $global_scene_map[$sceneKey] = $scene;
  12318. }
  12319. }
  12320. $need_update = false;
  12321. $new_global_roles = $global_roles;
  12322. $new_global_scenes = $global_scenes;
  12323. // 检查并添加新角色到全局
  12324. foreach ($merged_roles as $role) {
  12325. $role_name = getProp($role, 'role');
  12326. // 跳过旁白
  12327. if ($role_name === '旁白') {
  12328. continue;
  12329. }
  12330. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  12331. if ($roleKey === '') {
  12332. continue;
  12333. }
  12334. // 如果全局中不存在该角色,添加到全局
  12335. if (!isset($global_role_map[$roleKey])) {
  12336. $new_global_roles[] = [
  12337. 'role' => $role_name,
  12338. 'description' => getProp($role, 'description', ''),
  12339. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  12340. 'voice_name' => getProp($role, 'voice_name', ''),
  12341. 'voice_type' => getProp($role, 'voice_type', ''),
  12342. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  12343. 'url' => getProp($role, 'url', ''),
  12344. 'task_id' => getProp($role, 'task_id', ''),
  12345. 'task_status' => getProp($role, 'task_status', ''),
  12346. ];
  12347. $global_role_map[$roleKey] = true; // 标记已添加
  12348. $need_update = true;
  12349. dLog('deepseek')->info("新角色同步到全局", [
  12350. 'anime_id' => $anime_id,
  12351. 'role' => $role_name,
  12352. 'task_id' => getProp($role, 'task_id', ''),
  12353. ]);
  12354. }
  12355. // else {
  12356. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12357. // $global_role = $global_role_map[$roleKey];
  12358. // if (is_array($global_role)) {
  12359. // $updated = false;
  12360. // $update_fields = [];
  12361. // // 检查描述是否更新
  12362. // $current_description = trim((string)getProp($role, 'description'));
  12363. // $global_description = trim((string)getProp($global_role, 'description'));
  12364. // if ($current_description !== '' && $current_description !== $global_description) {
  12365. // $updated = true;
  12366. // $update_fields[] = 'description';
  12367. // }
  12368. // // 检查pic_prompt是否更新
  12369. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  12370. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  12371. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12372. // $updated = true;
  12373. // $update_fields[] = 'pic_prompt';
  12374. // }
  12375. // // 检查图片任务信息是否更新
  12376. // $current_task_id = getProp($role, 'task_id');
  12377. // $global_task_id = getProp($global_role, 'task_id');
  12378. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12379. // $updated = true;
  12380. // $update_fields[] = 'task_id';
  12381. // }
  12382. // // 如果有更新,同步到全局
  12383. // if ($updated) {
  12384. // foreach ($new_global_roles as &$global_role_item) {
  12385. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  12386. // if ($global_role_key === $roleKey) {
  12387. // if (in_array('description', $update_fields)) {
  12388. // $global_role_item['description'] = $current_description;
  12389. // }
  12390. // if (in_array('pic_prompt', $update_fields)) {
  12391. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  12392. // }
  12393. // if (in_array('task_id', $update_fields)) {
  12394. // $global_role_item['task_id'] = $current_task_id;
  12395. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  12396. // $global_role_item['url'] = getProp($role, 'url', '');
  12397. // }
  12398. // break;
  12399. // }
  12400. // }
  12401. // $need_update = true;
  12402. // dLog('deepseek')->info("角色信息更新到全局", [
  12403. // 'anime_id' => $anime_id,
  12404. // 'role' => $role_name,
  12405. // 'update_fields' => implode(',', $update_fields),
  12406. // ]);
  12407. // }
  12408. // }
  12409. // }
  12410. }
  12411. // 检查并添加新场景到全局
  12412. foreach ($merged_scenes as $scene) {
  12413. $scene_name = getProp($scene, 'scene');
  12414. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  12415. if ($sceneKey === '') {
  12416. continue;
  12417. }
  12418. // 如果全局中不存在该场景,添加到全局
  12419. if (!isset($global_scene_map[$sceneKey])) {
  12420. $new_global_scenes[] = [
  12421. 'scene' => $scene_name,
  12422. 'description' => getProp($scene, 'description', ''),
  12423. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  12424. 'url' => getProp($scene, 'url', ''),
  12425. 'task_id' => getProp($scene, 'task_id', ''),
  12426. 'task_status' => getProp($scene, 'task_status', ''),
  12427. ];
  12428. $global_scene_map[$sceneKey] = true; // 标记已添加
  12429. $need_update = true;
  12430. dLog('deepseek')->info("新场景同步到全局", [
  12431. 'anime_id' => $anime_id,
  12432. 'scene' => $scene_name,
  12433. 'task_id' => getProp($scene, 'task_id', ''),
  12434. ]);
  12435. }
  12436. // else {
  12437. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12438. // $global_scene = $global_scene_map[$sceneKey];
  12439. // if (is_array($global_scene)) {
  12440. // $updated = false;
  12441. // $update_fields = [];
  12442. // // 检查描述是否更新
  12443. // $current_description = trim((string)getProp($scene, 'description'));
  12444. // $global_description = trim((string)getProp($global_scene, 'description'));
  12445. // if ($current_description !== '' && $current_description !== $global_description) {
  12446. // $updated = true;
  12447. // $update_fields[] = 'description';
  12448. // }
  12449. // // 检查pic_prompt是否更新
  12450. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  12451. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  12452. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12453. // $updated = true;
  12454. // $update_fields[] = 'pic_prompt';
  12455. // }
  12456. // // 检查图片任务信息是否更新
  12457. // $current_task_id = getProp($scene, 'task_id');
  12458. // $global_task_id = getProp($global_scene, 'task_id');
  12459. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12460. // $updated = true;
  12461. // $update_fields[] = 'task_id';
  12462. // }
  12463. // // 如果有更新,同步到全局
  12464. // if ($updated) {
  12465. // foreach ($new_global_scenes as &$global_scene_item) {
  12466. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  12467. // if ($global_scene_key === $sceneKey) {
  12468. // if (in_array('description', $update_fields)) {
  12469. // $global_scene_item['description'] = $current_description;
  12470. // }
  12471. // if (in_array('pic_prompt', $update_fields)) {
  12472. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  12473. // }
  12474. // if (in_array('task_id', $update_fields)) {
  12475. // $global_scene_item['task_id'] = $current_task_id;
  12476. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  12477. // $global_scene_item['url'] = getProp($scene, 'url', '');
  12478. // }
  12479. // break;
  12480. // }
  12481. // }
  12482. // $need_update = true;
  12483. // dLog('deepseek')->info("场景信息更新到全局", [
  12484. // 'anime_id' => $anime_id,
  12485. // 'scene' => $scene_name,
  12486. // 'update_fields' => implode(',', $update_fields),
  12487. // ]);
  12488. // }
  12489. // }
  12490. // }
  12491. }
  12492. // 如果有新增或更新,更新数据库
  12493. if ($need_update) {
  12494. $update_data = [
  12495. 'roles' => json_encode($new_global_roles, 256),
  12496. 'scenes' => json_encode($new_global_scenes, 256),
  12497. 'updated_at' => date('Y-m-d H:i:s'),
  12498. ];
  12499. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12500. if ($result !== false) {
  12501. dLog('deepseek')->info("全局角色和场景更新成功", [
  12502. 'anime_id' => $anime_id,
  12503. 'roles_count' => count($new_global_roles),
  12504. 'scenes_count' => count($new_global_scenes),
  12505. ]);
  12506. } else {
  12507. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  12508. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  12509. }
  12510. }
  12511. }
  12512. }