DeepSeekService.php 856 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780
  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\Models\MpTaskCenter;
  11. use App\Models\MpUserPointsDetail;
  12. use App\Services\AIGeneration\AIImageGenerationService;
  13. use App\Services\PointsService;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. use Smalot\PdfParser\Parser as PdfParser;
  20. use TCPDF;
  21. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  22. use Predis\Command\Traits\Get\Get;
  23. class DeepSeekService
  24. {
  25. private $url;
  26. private $api_key;
  27. private $sys_message;
  28. private $headers;
  29. private $valid_text_models;
  30. private $gpt_text_models;
  31. private $gemini_text_models;
  32. protected $aiImageGenerationService;
  33. protected $pointsService;
  34. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  35. $this->aiImageGenerationService = $aiImageGenerationService;
  36. $this->pointsService = $pointsService;
  37. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  38. $this->api_key = env('DEEPSEEK_API_KEY');
  39. $this->headers = [
  40. 'Authorization' => 'Bearer '.$this->api_key,
  41. 'Content-Type' => 'application/json; charset=UTF-8'
  42. ];
  43. // 火山引擎模型列表
  44. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  45. // GPT文本模型列表
  46. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  47. // Gemini文本模型列表
  48. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  49. $this->sys_message = [
  50. 'role' => 'system',
  51. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  52. 强制要求:\n
  53. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  54. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  55. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  56. 普通要求:\n
  57. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  58. 2.<分集剧本>的要求如下:
  59.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  60.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  61.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  62.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  63. \n\n
  64. 示例如下:\n
  65. ###剧本名:西昆仑
  66. ###故事梗概
  67. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  68. ###剧本亮点
  69. 亮点1:绝境奇药,生死一线
  70. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  71. 亮点2:结拜兄妹,化解尴尬
  72. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  73. 亮点3:纤发夺命,情愫暗涌
  74. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  75. ###人物关系
  76. 阿雪与梁萧之间存在兄妹之情。
  77. ###核心矛盾
  78. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  79. ###主体列表
  80. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  81. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  82. 阴阳球:天地异宝,能化生精气,救人于危难。
  83. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  84. ###美术风格
  85. 基础画风风格词:厚涂古风
  86. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  87. ###场景列表
  88. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  89. ###分集剧本
  90. ##分集01
  91. 第1集: 第一集的标题
  92. 场景描述:地点、时间、场景
  93. 运镜:固定近距离
  94. 出场角色:男主、女主
  95. 台词内容:
  96. 女主: 女主对话
  97. 男主:男主对话
  98. 女主: 女主对话
  99. 男主: 男主对话
  100. ##分集02
  101. 第2集: 第二集的标题
  102. 场景描述:地点、时间、场景
  103. 运镜:固定近距离
  104. 出场角色:男主、女主
  105. 台词内容:
  106. 女主: 女主对话
  107. 男主:男主对话
  108. 女主: 女主对话
  109. 男主: 男主对话"
  110. ];
  111. }
  112. /**
  113. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  114. *
  115. * @param array $data 请求参数
  116. * @return \Generator 返回生成器,用于流式输出
  117. */
  118. public function generateText($data) {
  119. // 获取请求参数
  120. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  121. $messages = getProp($data, 'messages', []);
  122. $systemPrompt = getProp($data, 'system_prompt', '');
  123. $prompt = getProp($data, 'prompt', '');
  124. $images = getProp($data, 'images', []); // 支持多张图片
  125. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  126. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  127. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  128. $isGeminiModel = in_array($model, $this->gemini_text_models);
  129. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  130. Utils::throwError('20003:仅Gemini模型支持视频输入');
  131. }
  132. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  133. $uid = Site::getUid();
  134. $chargeModality = '';
  135. $chargePoints = 0;
  136. $hasImageMedia = !empty($images) || !empty($imageUrls)
  137. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  138. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  139. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  140. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  141. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  142. $pricingModel = $this->geminiMultimodalPricingModel($model);
  143. if ($pricingModel !== '') {
  144. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  145. if ($chargePoints > 0) {
  146. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  147. }
  148. }
  149. }
  150. // 如果没有提供messages,则根据system_prompt、content和images构建
  151. if (empty($messages)) {
  152. $messages = [];
  153. // 添加系统提示词
  154. if (!empty($systemPrompt)) {
  155. $messages[] = [
  156. 'role' => 'system',
  157. 'content' => $systemPrompt
  158. ];
  159. }
  160. // 构建用户消息内容(支持文本+图片)
  161. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  162. $userMessage = [
  163. 'role' => 'user',
  164. 'content' => []
  165. ];
  166. // 添加文本内容
  167. if (!empty($prompt)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'text',
  170. 'text' => $prompt
  171. ];
  172. }
  173. // 处理上传的图片文件
  174. if (!empty($images)) {
  175. if (!is_array($images)) {
  176. $images = [$images];
  177. }
  178. foreach ($images as $image) {
  179. $imageBase64 = $this->processImageToBase64($image);
  180. if ($imageBase64) {
  181. $userMessage['content'][] = [
  182. 'type' => 'image_url',
  183. 'image_url' => [
  184. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  185. ]
  186. ];
  187. }
  188. }
  189. }
  190. // 处理图片URL
  191. if (!empty($imageUrls)) {
  192. if (!is_array($imageUrls)) {
  193. $imageUrls = [$imageUrls];
  194. }
  195. foreach ($imageUrls as $url) {
  196. if (!empty($url)) {
  197. $userMessage['content'][] = [
  198. 'type' => 'image_url',
  199. 'image_url' => [
  200. 'url' => $url
  201. ]
  202. ];
  203. }
  204. }
  205. }
  206. // 处理上传的视频文件(仅 Gemini)
  207. if (!empty($videos) && $isGeminiModel) {
  208. if (!is_array($videos)) {
  209. $videos = [$videos];
  210. }
  211. foreach ($videos as $video) {
  212. $inlineData = $this->processMediaToInlineData($video);
  213. if ($inlineData) {
  214. $userMessage['content'][] = [
  215. 'type' => 'video',
  216. 'inline_data' => $inlineData
  217. ];
  218. }
  219. }
  220. }
  221. // 处理视频URL(仅 Gemini)
  222. if (!empty($videoUrls) && $isGeminiModel) {
  223. if (!is_array($videoUrls)) {
  224. $videoUrls = [$videoUrls];
  225. }
  226. foreach ($videoUrls as $url) {
  227. if (!empty($url)) {
  228. $userMessage['content'][] = [
  229. 'type' => 'video_url',
  230. 'video_url' => ['url' => $url]
  231. ];
  232. }
  233. }
  234. }
  235. // 如果只有文本内容,简化为字符串格式
  236. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  237. $userMessage['content'] = $userMessage['content'][0]['text'];
  238. }
  239. $messages[] = $userMessage;
  240. }
  241. }
  242. // 验证messages不为空
  243. if (empty($messages)) {
  244. Utils::throwError('20003:请提供有效的对话内容');
  245. }
  246. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  247. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  248. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  249. if ($model === 'deepseek-chat') {
  250. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  251. $model = 'deepseek-v4-flash';
  252. $thinkingMode = 'disabled';
  253. } elseif ($model === 'deepseek-reasoner') {
  254. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'enabled';
  257. }
  258. // 构建请求参数
  259. $post_data = [
  260. 'model' => $model,
  261. 'messages' => $messages,
  262. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  263. 'temperature' => getProp($data, 'temperature', 1),
  264. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  265. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  266. 'thinking' => ['type' => $thinkingMode],
  267. 'stream' => true // 启用流式输出
  268. ];
  269. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  270. // 添加可选参数
  271. if (isset($data['top_p'])) {
  272. $post_data['top_p'] = $data['top_p'];
  273. }
  274. if (isset($data['response_format'])) {
  275. $post_data['response_format'] = $data['response_format'];
  276. }
  277. // 根据模型类型选择调用方法
  278. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  279. // DeepSeek 官方模型使用 DeepSeek API
  280. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  281. } else if (in_array($model, $this->gpt_text_models)) {
  282. // GPT 模型使用 TokenRouter API
  283. $streamGenerator = $this->gpt54StreamResponse($post_data);
  284. } else if (in_array($model, $this->gemini_text_models)) {
  285. // Gemini 模型使用 Gemini API
  286. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  287. } else if (in_array($model, $this->valid_text_models)) {
  288. // 火山引擎支持的模型使用火山引擎 API
  289. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  290. } else {
  291. Utils::throwError('20003:不支持的模型: ' . $model);
  292. }
  293. if ($chargePoints > 0) {
  294. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  295. }
  296. // 纯文本(不扣积分):流式生成成功后仅记录 token 使用明细
  297. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  298. }
  299. /**
  300. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  301. *
  302. * @param \Generator $generator
  303. * @param int $uid
  304. * @param string $model
  305. * @return \Generator
  306. */
  307. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  308. {
  309. $recorded = false;
  310. foreach ($generator as $chunk) {
  311. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  312. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  313. 'model' => $model,
  314. 'source' => $source,
  315. ], $model);
  316. $recorded = true;
  317. }
  318. yield $chunk;
  319. }
  320. }
  321. /**
  322. * 流式生成成功后再按 Gemini 多模态规则扣费
  323. *
  324. * @param \Generator $generator
  325. * @param int $uid
  326. * @param string $model
  327. * @param int $points
  328. * @param string $modality
  329. * @return \Generator
  330. */
  331. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  332. {
  333. $charged = false;
  334. foreach ($generator as $chunk) {
  335. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  336. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  337. if ($fullContent !== '') {
  338. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  339. $charged = true;
  340. }
  341. }
  342. yield $chunk;
  343. }
  344. }
  345. /**
  346. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  347. *
  348. * @param int $uid
  349. * @param string $model
  350. * @param int $points
  351. * @param string $modality
  352. * @param mixed $usage
  353. * @return void
  354. */
  355. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  356. {
  357. $result = $this->pointsService->recordChatCharge(
  358. $uid,
  359. $points,
  360. $this->pointsService->getTokensFromUsage($usage),
  361. [
  362. 'model' => $model,
  363. 'modality' => $modality,
  364. 'source' => 'generateText',
  365. ],
  366. '',
  367. $model
  368. );
  369. if (empty($result['charged'])) {
  370. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  371. }
  372. }
  373. /**
  374. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  375. *
  376. * @param string $model
  377. * @return string
  378. */
  379. private function geminiMultimodalPricingModel(string $model): string
  380. {
  381. $map = [
  382. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  383. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  384. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  385. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  386. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  387. ];
  388. return $map[$model] ?? '';
  389. }
  390. /**
  391. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  392. *
  393. * @param array $messages
  394. * @param array $mediaTypes
  395. * @return bool
  396. */
  397. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  398. {
  399. foreach ($messages as $message) {
  400. $content = getProp($message, 'content', '');
  401. if (!is_array($content)) {
  402. continue;
  403. }
  404. foreach ($content as $part) {
  405. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  406. return true;
  407. }
  408. }
  409. }
  410. return false;
  411. }
  412. public function createGenerateText($data) {
  413. $file = getProp($data, 'file');
  414. $episode_num = getProp($data, 'episode_num');
  415. $uid = Site::getUid();
  416. $cpid = Site::getCpid();
  417. if (!$file) {
  418. Utils::throwError('20003:请上传文件');
  419. }
  420. // 提取文件内容
  421. $content = $this->extractFileContent($file);
  422. if (!$content) {
  423. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  424. }
  425. // 拆分章节并校验章节总数、标题连续性
  426. if ($episode_num) {
  427. $this->validateGenerateTextChapters($content, (int)$episode_num);
  428. }
  429. // 获取原始文件名(不含扩展名)作为script_name
  430. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  431. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  432. // 字节安全剥离,不依赖服务器locale设置
  433. $originalName = $file->getClientOriginalName();
  434. $extension = $file->getClientOriginalExtension();
  435. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  436. ? substr($originalName, 0, -strlen($extension) - 1)
  437. : $originalName;
  438. if ($script_name === '') {
  439. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  440. }
  441. // 如果同一用户的剧本名存在则提示
  442. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  443. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  444. }
  445. // 插入数据到mp_scripts表
  446. $script_id = DB::table('mp_scripts')->insertGetId([
  447. 'script_name' => $script_name,
  448. 'user_id' => $uid,
  449. 'cpid' => $cpid,
  450. 'content' => $content,
  451. 'created_at' => date('Y-m-d H:i:s'),
  452. 'updated_at' => date('Y-m-d H:i:s')
  453. ]);
  454. return [
  455. 'script_id' => $script_id,
  456. 'script_name' => $script_name
  457. ];
  458. }
  459. /**
  460. * AI对话调用成功后的积分扣费(返回结果前调用)
  461. *
  462. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  463. *
  464. * @param int $uid
  465. * @param int $tokens
  466. * @param array $chargeInfo
  467. * @return void
  468. */
  469. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  470. {
  471. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  472. $model = (string)getProp($chargeInfo, 'model', '');
  473. $result = $this->pointsService->recordChatCharge(
  474. $uid,
  475. $this->pointsService->getChatChargePoints($model),
  476. $tokens,
  477. $chargeInfo,
  478. '',
  479. $model !== '' ? $model : 'deepseek'
  480. );
  481. if (empty($result['charged'])) {
  482. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  483. }
  484. }
  485. /**
  486. * 安全获取当前登录用户ID
  487. *
  488. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  489. *
  490. * @return int
  491. */
  492. private function getCurrentUid(): int
  493. {
  494. try {
  495. return (int)Site::getUid();
  496. } catch (\Throwable $e) {
  497. return 0;
  498. }
  499. }
  500. /**
  501. * 记录文生文 token 使用明细(仅记录,不扣积分)
  502. *
  503. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  504. *
  505. * @param int $uid 用户ID(0 时跳过)
  506. * @param int $tokens 消耗 token 数
  507. * @param array $chargeInfo 计费/来源信息(model、source 等)
  508. * @param string $apiType API 类型/模型标识
  509. * @return void
  510. */
  511. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  512. {
  513. try {
  514. $this->pointsService->recordTokenOnlyDetail(
  515. $uid,
  516. $tokens,
  517. $chargeInfo,
  518. MpUserPointsDetail::TYPE_CHAT,
  519. $apiType,
  520. ''
  521. );
  522. } catch (\Throwable $e) {
  523. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  524. 'uid' => $uid,
  525. 'source' => $chargeInfo['source'] ?? '',
  526. ]);
  527. }
  528. }
  529. /**
  530. * 拆分剧本内容并校验章节总数与标题连续性
  531. *
  532. * @param string $content
  533. * @param int $episodeNum
  534. * @return void
  535. */
  536. private function validateGenerateTextChapters($content, $episodeNum)
  537. {
  538. $chapters = splitContent($content);
  539. if (count($chapters) !== $episodeNum) {
  540. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  541. }
  542. if (empty($chapters)) {
  543. return;
  544. }
  545. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  546. $numbers = [];
  547. $unparsedIndex = null;
  548. foreach ($chapters as $index => $chapter) {
  549. $num = $this->parseChapterNumber($chapter['title']);
  550. if ($num === null) {
  551. $unparsedIndex = $index;
  552. break;
  553. }
  554. $numbers[] = $num;
  555. }
  556. if ($unparsedIndex === null) {
  557. $expected = 1;
  558. foreach ($numbers as $index => $num) {
  559. if ($num !== $expected) {
  560. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  561. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  562. }
  563. $expected++;
  564. }
  565. return;
  566. }
  567. // 标题格式无法用正则确认时,交给模型分析
  568. $titles = array_column($chapters, 'title');
  569. $aiResult = $this->validateChapterSequenceByAI($titles);
  570. if ($aiResult['valid'] === false) {
  571. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  572. if (isset($chapters[$badIndex - 1])) {
  573. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  574. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  575. }
  576. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  577. }
  578. if ($aiResult['valid'] === null) {
  579. if (isset($chapters[$unparsedIndex])) {
  580. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  581. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  582. }
  583. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  584. }
  585. }
  586. /**
  587. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  588. *
  589. * @param string $title
  590. * @return int|null
  591. */
  592. private function parseChapterNumber($title)
  593. {
  594. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  595. return null;
  596. }
  597. return $this->convertChineseNumber($match[1]);
  598. }
  599. /**
  600. * 中文数字转阿拉伯数字(支持到千)
  601. *
  602. * @param string $numStr
  603. * @return int
  604. */
  605. private function convertChineseNumber($numStr)
  606. {
  607. if (preg_match('/^\d+$/', $numStr)) {
  608. return (int)$numStr;
  609. }
  610. $map = [
  611. '零' => 0,
  612. '一' => 1,
  613. '二' => 2,
  614. '两' => 2,
  615. '三' => 3,
  616. '四' => 4,
  617. '五' => 5,
  618. '六' => 6,
  619. '七' => 7,
  620. '八' => 8,
  621. '九' => 9
  622. ];
  623. $total = 0;
  624. $section = 0;
  625. $length = mb_strlen($numStr);
  626. for ($i = 0; $i < $length; $i++) {
  627. $char = mb_substr($numStr, $i, 1);
  628. if (isset($map[$char])) {
  629. $section = $map[$char];
  630. } elseif ($char === '十') {
  631. $total += $section === 0 ? 10 : $section * 10;
  632. $section = 0;
  633. } elseif ($char === '百') {
  634. $total += $section === 0 ? 100 : $section * 100;
  635. $section = 0;
  636. } elseif ($char === '千') {
  637. $total += $section === 0 ? 1000 : $section * 1000;
  638. $section = 0;
  639. }
  640. }
  641. return $total + $section;
  642. }
  643. /**
  644. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  645. *
  646. * @param array $titles
  647. * @return array{valid: bool|null, invalid_index: int|null}
  648. */
  649. private function validateChapterSequenceByAI($titles)
  650. {
  651. $titleLines = [];
  652. foreach (array_slice($titles, 0, 200) as $index => $title) {
  653. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  654. }
  655. $result = [
  656. 'valid' => null,
  657. 'invalid_index' => null
  658. ];
  659. $post_data = [
  660. 'model' => 'deepseek-v4-flash',
  661. 'messages' => [
  662. [
  663. 'role' => 'system',
  664. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  665. ],
  666. [
  667. 'role' => 'user',
  668. 'content' => implode("\n", $titleLines),
  669. ],
  670. ],
  671. 'temperature' => 0,
  672. 'frequency_penalty' => 0,
  673. 'presence_penalty' => 0,
  674. 'stream' => false,
  675. ];
  676. try {
  677. $result = $this->chatOnly($post_data, 8);
  678. $content = trim((string)($result['fullContent'] ?? ''));
  679. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  680. $result['valid'] = strtolower($match[1]) === 'true';
  681. }
  682. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  683. $result['invalid_index'] = (int)$match[1];
  684. }
  685. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  686. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  687. 'model' => 'deepseek-v4-flash',
  688. 'source' => 'validateChapterSequenceByAI',
  689. ], 'deepseek-v4-flash');
  690. } catch (\Exception $e) {
  691. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  692. }
  693. return $result;
  694. }
  695. /**
  696. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  697. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  698. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  699. *
  700. * @param array $data 请求参数
  701. * @return \Generator
  702. */
  703. public function newGenerateTextStream($data) {
  704. $model = getProp($data, 'model', 'deepseek-v4-pro');
  705. $messages = getProp($data, 'messages', []);
  706. $systemPrompt = getProp($data, 'system_prompt', '');
  707. $prompt = getProp($data, 'prompt', '');
  708. $images = getProp($data, 'images', []);
  709. $imageUrls = getProp($data, 'image_urls', []);
  710. $responseFormat = getProp($data, 'response_format', 'text');
  711. $templateId = getProp($data, 'template_id', 0);
  712. $script_id = getProp($data, 'script_id', 0);
  713. $sequence = getProp($data, 'sequence', 0);
  714. $generateTaskId = 0;
  715. $uid = Site::getUid();
  716. if ($script_id > 0) {
  717. $existingTask = DB::table('mp_script_generate_tasks')
  718. ->where('uid', $uid)
  719. ->where('script_id', $script_id)
  720. ->orderByDesc('id')
  721. ->first();
  722. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  723. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  724. }
  725. }
  726. // 如果提供了script_id,从数据库获取剧本内容作为原文
  727. $originalContent = '';
  728. $hasValidScript = false;
  729. if ($script_id > 0) {
  730. $script = DB::table('mp_scripts')
  731. ->where('id', $script_id)
  732. ->where('is_deleted', 0)
  733. ->first();
  734. if (!$script) {
  735. Utils::throwError('20003:剧本不存在或已删除');
  736. }
  737. $originalContent = $script->content ?? '';
  738. if (empty($originalContent)) {
  739. Utils::throwError('20003:剧本内容为空');
  740. }
  741. $hasValidScript = true;
  742. if (!empty($prompt)) {
  743. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  744. } else {
  745. $prompt = "原文内容:\n" . $originalContent;
  746. }
  747. }
  748. // 如果提供了template_id,从数据库获取template_prompt
  749. if ($templateId > 0) {
  750. $template = DB::table('mp_prompt_templates')
  751. ->where('id', $templateId)
  752. ->where('is_deleted', 0)
  753. ->first();
  754. if (!$template) {
  755. Utils::throwError('20003:模板不存在或已删除');
  756. }
  757. $templatePrompt = $template->template_prompt ?? '';
  758. if (!empty($templatePrompt)) {
  759. if (!empty($prompt)) {
  760. $prompt = $templatePrompt . "\n\n" . $prompt;
  761. } else {
  762. $prompt = $templatePrompt;
  763. }
  764. }
  765. }
  766. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  767. if (empty($messages)) {
  768. $messages = [];
  769. if (!empty($systemPrompt)) {
  770. $messages[] = [
  771. 'role' => 'system',
  772. 'content' => $systemPrompt
  773. ];
  774. }
  775. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  776. $userMessage = [
  777. 'role' => 'user',
  778. 'content' => []
  779. ];
  780. if (!empty($prompt)) {
  781. $userMessage['content'][] = [
  782. 'type' => 'text',
  783. 'text' => $prompt
  784. ];
  785. }
  786. if (!empty($images)) {
  787. if (!is_array($images)) {
  788. $images = [$images];
  789. }
  790. foreach ($images as $image) {
  791. $imageBase64 = $this->processImageToBase64($image);
  792. if ($imageBase64) {
  793. $userMessage['content'][] = [
  794. 'type' => 'image_url',
  795. 'image_url' => [
  796. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  797. ]
  798. ];
  799. }
  800. }
  801. }
  802. if (!empty($imageUrls)) {
  803. if (!is_array($imageUrls)) {
  804. $imageUrls = [$imageUrls];
  805. }
  806. foreach ($imageUrls as $url) {
  807. if (!empty($url)) {
  808. $userMessage['content'][] = [
  809. 'type' => 'image_url',
  810. 'image_url' => [
  811. 'url' => $url
  812. ]
  813. ];
  814. }
  815. }
  816. }
  817. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  818. $userMessage['content'] = $userMessage['content'][0]['text'];
  819. }
  820. $messages[] = $userMessage;
  821. }
  822. }
  823. if (empty($messages)) {
  824. Utils::throwError('20003:请提供有效的对话内容');
  825. }
  826. // 模型兼容性处理
  827. $thinkingMode = getProp($data, 'thinking', 'disabled');
  828. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  829. if ($model === 'deepseek-chat') {
  830. $model = 'deepseek-v4-flash';
  831. $thinkingMode = 'disabled';
  832. } elseif ($model === 'deepseek-reasoner') {
  833. $model = 'deepseek-v4-flash';
  834. $thinkingMode = 'enabled';
  835. }
  836. // 构建请求参数(流式)
  837. $post_data = [
  838. 'model' => $model,
  839. 'messages' => $messages,
  840. 'temperature' => getProp($data, 'temperature', 1),
  841. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  842. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  843. 'thinking' => ['type' => $thinkingMode],
  844. 'stream' => true
  845. ];
  846. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  847. if (isset($data['top_p'])) {
  848. $post_data['top_p'] = $data['top_p'];
  849. }
  850. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  851. if ($responseFormat === 'json') {
  852. $hasJsonKeyword = false;
  853. foreach ($post_data['messages'] as $message) {
  854. if (isset($message['content'])) {
  855. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  856. if (stripos($content, 'json') !== false) {
  857. $hasJsonKeyword = true;
  858. break;
  859. }
  860. }
  861. }
  862. if (!$hasJsonKeyword) {
  863. $lastMessageIndex = count($post_data['messages']) - 1;
  864. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  865. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  866. if (is_string($lastContent)) {
  867. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  868. } elseif (is_array($lastContent)) {
  869. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  870. if ($contentPart['type'] === 'text') {
  871. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  872. break;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. $post_data['response_format'] = ['type' => 'json_object'];
  879. }
  880. // 如果提供了script_id,创建剧本资产生成任务
  881. if ($script_id > 0) {
  882. $uid = Site::getUid();
  883. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  884. 'uid' => $uid,
  885. 'script_id' => $script_id,
  886. 'sequence' => $sequence,
  887. 'status' => 'processing',
  888. 'prompt' => getProp($data, 'prompt', ''),
  889. 'started_at' => date('Y-m-d H:i:s'),
  890. 'created_at' => date('Y-m-d H:i:s'),
  891. 'updated_at' => date('Y-m-d H:i:s')
  892. ]);
  893. }
  894. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  895. if ($hasValidScript) {
  896. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  897. }
  898. // 根据模型类型选择流式调用方法
  899. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  900. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  901. } elseif (in_array($model, $this->gpt_text_models)) {
  902. $streamGenerator = $this->gpt54StreamResponse($post_data);
  903. } elseif (in_array($model, $this->gemini_text_models)) {
  904. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  905. } elseif (in_array($model, $this->valid_text_models)) {
  906. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  907. } else {
  908. Utils::throwError('20003:不支持的模型: ' . $model);
  909. }
  910. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  911. return $this->wrapNewGenerateTextStream($streamGenerator, [
  912. 'uid' => $uid,
  913. 'model' => $model,
  914. 'generate_task_id' => $generateTaskId,
  915. 'has_valid_script' => $hasValidScript,
  916. 'script_id' => $script_id,
  917. 'sequence' => $sequence,
  918. 'original_prompt' => getProp($data, 'prompt', ''),
  919. 'response_format' => $responseFormat,
  920. ]);
  921. }
  922. /**
  923. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  924. *
  925. * @param \Generator $generator
  926. * @param array $ctx
  927. * @return \Generator
  928. */
  929. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  930. {
  931. $fullContent = '';
  932. $usage = [];
  933. $finished = false;
  934. try {
  935. foreach ($generator as $chunk) {
  936. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  937. $fullContent .= (string)getProp($chunk, 'content', '');
  938. }
  939. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  940. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  941. $usage = getProp($chunk, 'usage', []);
  942. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  943. if (($ctx['response_format'] ?? 'text') === 'json') {
  944. $fullContent = $this->extractJsonContent($fullContent);
  945. }
  946. $finished = true;
  947. }
  948. yield $chunk;
  949. }
  950. if ($finished) {
  951. if (!empty($ctx['generate_task_id'])) {
  952. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  953. 'status' => 'success',
  954. 'result' => $fullContent,
  955. 'completed_at' => date('Y-m-d H:i:s'),
  956. 'updated_at' => date('Y-m-d H:i:s'),
  957. ]);
  958. }
  959. if ($ctx['has_valid_script'] && $fullContent !== '') {
  960. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  961. 'model' => $ctx['model'],
  962. 'script_id' => $ctx['script_id'],
  963. 'sequence' => $ctx['sequence'],
  964. 'source' => 'newGenerateText',
  965. ]);
  966. }
  967. if (!empty($ctx['script_id'])) {
  968. $now = now();
  969. DB::table('mp_script_records')->insert([
  970. [
  971. 'uid' => $ctx['uid'],
  972. 'script_id' => $ctx['script_id'],
  973. 'sequence' => $ctx['sequence'],
  974. 'role' => 'user',
  975. 'content' => $ctx['original_prompt'],
  976. 'created_at' => $now,
  977. 'updated_at' => $now,
  978. ],
  979. [
  980. 'uid' => $ctx['uid'],
  981. 'script_id' => $ctx['script_id'],
  982. 'sequence' => $ctx['sequence'],
  983. 'role' => 'assistant',
  984. 'content' => $fullContent,
  985. 'created_at' => $now,
  986. 'updated_at' => $now,
  987. ],
  988. ]);
  989. }
  990. }
  991. } catch (\Throwable $e) {
  992. if (!empty($ctx['generate_task_id'])) {
  993. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  994. 'status' => 'failed',
  995. 'error_message' => $e->getMessage(),
  996. 'completed_at' => date('Y-m-d H:i:s'),
  997. 'updated_at' => date('Y-m-d H:i:s'),
  998. ]);
  999. }
  1000. yield [
  1001. 'type' => 'error',
  1002. 'message' => $e->getMessage(),
  1003. ];
  1004. }
  1005. }
  1006. /**
  1007. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1008. *
  1009. * @param string $content
  1010. * @return string
  1011. */
  1012. private function extractJsonContent(string $content): string
  1013. {
  1014. $content = trim($content);
  1015. if ($content === '') {
  1016. return $content;
  1017. }
  1018. // 剥离 ```json ... ``` 代码块
  1019. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1020. $content = trim($m[1]);
  1021. }
  1022. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1023. $first = strpos($content, '{');
  1024. $last = strrpos($content, '}');
  1025. if ($first !== false && $last !== false && $last > $first) {
  1026. $content = substr($content, $first, $last - $first + 1);
  1027. }
  1028. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1029. json_decode($content, true);
  1030. if (json_last_error() !== JSON_ERROR_NONE) {
  1031. return trim($content);
  1032. }
  1033. return $content;
  1034. }
  1035. /**
  1036. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1037. *
  1038. * @param array $data 请求参数
  1039. * @return array 返回结果数组
  1040. */
  1041. public function newGenerateText($data) {
  1042. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1043. if ((int)getProp($data, 'stream', 0) === 1) {
  1044. return $this->newGenerateTextStream($data);
  1045. }
  1046. // 获取请求参数
  1047. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1048. $messages = getProp($data, 'messages', []);
  1049. $systemPrompt = getProp($data, 'system_prompt', '');
  1050. $prompt = getProp($data, 'prompt', '');
  1051. $images = getProp($data, 'images', []); // 支持多张图片
  1052. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1053. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1054. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1055. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1056. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1057. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1058. $generateTaskId = 0;
  1059. $uid = Site::getUid();
  1060. if ($script_id > 0) {
  1061. $existingTask = DB::table('mp_script_generate_tasks')
  1062. ->where('uid', $uid)
  1063. ->where('script_id', $script_id)
  1064. ->orderByDesc('id')
  1065. ->first();
  1066. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1067. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1068. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1069. }
  1070. }
  1071. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1072. $originalContent = '';
  1073. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1074. if ($script_id > 0) {
  1075. $script = DB::table('mp_scripts')
  1076. ->where('id', $script_id)
  1077. ->where('is_deleted', 0)
  1078. ->first();
  1079. if (!$script) {
  1080. Utils::throwError('20003:剧本不存在或已删除');
  1081. }
  1082. $originalContent = $script->content ?? '';
  1083. if (empty($originalContent)) {
  1084. Utils::throwError('20003:剧本内容为空');
  1085. }
  1086. $hasValidScript = true;
  1087. // 将剧本内容添加到提示词前面
  1088. if (!empty($originalContent)) {
  1089. if (!empty($prompt)) {
  1090. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1091. } else {
  1092. $prompt = "原文内容:\n" . $originalContent;
  1093. }
  1094. }
  1095. }
  1096. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1097. if ($templateId > 0) {
  1098. $template = DB::table('mp_prompt_templates')
  1099. ->where('id', $templateId)
  1100. ->where('is_deleted', 0)
  1101. ->first();
  1102. if (!$template) {
  1103. Utils::throwError('20003:模板不存在或已删除');
  1104. }
  1105. $templatePrompt = $template->template_prompt ?? '';
  1106. // 将模板提示词和用户输入的prompt组合
  1107. // 模板为准,用户输入作为补充要求
  1108. if (!empty($templatePrompt)) {
  1109. if (!empty($prompt)) {
  1110. $prompt = $templatePrompt . "\n\n" . $prompt;
  1111. } else {
  1112. $prompt = $templatePrompt;
  1113. }
  1114. }
  1115. }
  1116. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1117. if (empty($messages)) {
  1118. $messages = [];
  1119. // 添加系统提示词
  1120. if (!empty($systemPrompt)) {
  1121. $messages[] = [
  1122. 'role' => 'system',
  1123. 'content' => $systemPrompt
  1124. ];
  1125. }
  1126. // 构建用户消息内容(支持文本+图片)
  1127. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1128. $userMessage = [
  1129. 'role' => 'user',
  1130. 'content' => []
  1131. ];
  1132. // 添加文本内容
  1133. if (!empty($prompt)) {
  1134. $userMessage['content'][] = [
  1135. 'type' => 'text',
  1136. 'text' => $prompt
  1137. ];
  1138. }
  1139. // 处理上传的图片文件
  1140. if (!empty($images)) {
  1141. if (!is_array($images)) {
  1142. $images = [$images];
  1143. }
  1144. foreach ($images as $image) {
  1145. $imageBase64 = $this->processImageToBase64($image);
  1146. if ($imageBase64) {
  1147. $userMessage['content'][] = [
  1148. 'type' => 'image_url',
  1149. 'image_url' => [
  1150. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1151. ]
  1152. ];
  1153. }
  1154. }
  1155. }
  1156. // 处理图片URL
  1157. if (!empty($imageUrls)) {
  1158. if (!is_array($imageUrls)) {
  1159. $imageUrls = [$imageUrls];
  1160. }
  1161. foreach ($imageUrls as $url) {
  1162. if (!empty($url)) {
  1163. $userMessage['content'][] = [
  1164. 'type' => 'image_url',
  1165. 'image_url' => [
  1166. 'url' => $url
  1167. ]
  1168. ];
  1169. }
  1170. }
  1171. }
  1172. // 如果只有文本内容,简化为字符串格式
  1173. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1174. $userMessage['content'] = $userMessage['content'][0]['text'];
  1175. }
  1176. $messages[] = $userMessage;
  1177. }
  1178. }
  1179. // 验证messages不为空
  1180. if (empty($messages)) {
  1181. Utils::throwError('20003:请提供有效的对话内容');
  1182. }
  1183. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1184. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1185. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1186. if ($model === 'deepseek-chat') {
  1187. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1188. $model = 'deepseek-v4-flash';
  1189. $thinkingMode = 'disabled';
  1190. } elseif ($model === 'deepseek-reasoner') {
  1191. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1192. $model = 'deepseek-v4-flash';
  1193. $thinkingMode = 'enabled';
  1194. }
  1195. // 构建请求参数(非流式)
  1196. $post_data = [
  1197. 'model' => $model,
  1198. 'messages' => $messages,
  1199. 'temperature' => getProp($data, 'temperature', 1),
  1200. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1201. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1202. 'thinking' => ['type' => $thinkingMode],
  1203. 'stream' => false // 非流式输出
  1204. ];
  1205. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1206. // 添加可选参数
  1207. if (isset($data['top_p'])) {
  1208. $post_data['top_p'] = $data['top_p'];
  1209. }
  1210. // 新增: 根据response_format设置响应格式
  1211. if ($responseFormat === 'json') {
  1212. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1213. $hasJsonKeyword = false;
  1214. foreach ($post_data['messages'] as $message) {
  1215. if (isset($message['content'])) {
  1216. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1217. if (stripos($content, 'json') !== false) {
  1218. $hasJsonKeyword = true;
  1219. break;
  1220. }
  1221. }
  1222. }
  1223. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1224. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1225. if (!$hasJsonKeyword) {
  1226. $lastMessageIndex = count($post_data['messages']) - 1;
  1227. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1228. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1229. // 如果content是字符串,直接追加
  1230. if (is_string($lastContent)) {
  1231. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1232. }
  1233. // 如果content是数组(包含文本和图片),在文本部分追加
  1234. else if (is_array($lastContent)) {
  1235. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1236. if ($contentPart['type'] === 'text') {
  1237. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1238. break;
  1239. }
  1240. }
  1241. }
  1242. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1243. }
  1244. }
  1245. // 设置response_format参数(所有支持的模型)
  1246. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1247. // DeepSeek模型
  1248. $post_data['response_format'] = ['type' => 'json_object'];
  1249. } else if (in_array($model, $this->gpt_text_models)) {
  1250. // GPT模型
  1251. $post_data['response_format'] = ['type' => 'json_object'];
  1252. } else if (in_array($model, $this->valid_text_models)) {
  1253. // 火山引擎模型
  1254. $post_data['response_format'] = ['type' => 'json_object'];
  1255. }
  1256. }
  1257. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1258. if ($script_id > 0) {
  1259. $uid = Site::getUid();
  1260. // 创建新的生成任务
  1261. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1262. 'uid' => $uid,
  1263. 'script_id' => $script_id,
  1264. 'sequence' => $sequence,
  1265. 'status' => 'processing',
  1266. 'prompt' => getProp($data, 'prompt', ''),
  1267. 'started_at' => date('Y-m-d H:i:s'),
  1268. 'created_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s')
  1270. ]);
  1271. }
  1272. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1273. if ($hasValidScript) {
  1274. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1275. }
  1276. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  1277. try {
  1278. $aiResult = null;
  1279. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1280. // DeepSeek 官方模型使用现有的 chatOnly 方法
  1281. $result = $this->chatOnly($post_data);
  1282. // 记录实际使用的模型
  1283. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  1284. $aiResult = [
  1285. 'content' => $result['fullContent'],
  1286. 'reasoning_content' => $result['fullReasoningContent'],
  1287. 'usage' => $result['usage'],
  1288. 'model' => $model,
  1289. 'finish_reason' => 'stop'
  1290. ];
  1291. } else if (in_array($model, $this->gpt_text_models)) {
  1292. // GPT 模型使用现有的 gpt54ChatOnly 方法
  1293. $result = $this->gpt54ChatOnly($post_data);
  1294. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  1295. $aiResult = [
  1296. 'content' => $result['fullContent'],
  1297. 'reasoning_content' => '',
  1298. 'usage' => $result['usage'],
  1299. 'model' => $model,
  1300. 'finish_reason' => 'stop'
  1301. ];
  1302. } else if (in_array($model, $this->gemini_text_models)) {
  1303. // Gemini 模型使用 Gemini API(非流式)
  1304. $result = $this->geminiChatOnly($post_data, $model);
  1305. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  1306. $aiResult = [
  1307. 'content' => $result['fullContent'],
  1308. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  1309. 'usage' => $result['usage'],
  1310. 'model' => $model,
  1311. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1312. ];
  1313. } else if (in_array($model, $this->valid_text_models)) {
  1314. // 火山引擎支持的模型使用火山引擎 API(非流式)
  1315. $post_data['stream'] = false;
  1316. $result = $this->volcEngineChatCompletion($post_data);
  1317. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  1318. 'requested_model' => $model,
  1319. 'result_keys' => array_keys($result),
  1320. 'has_fullContent' => isset($result['fullContent']),
  1321. 'has_content' => isset($result['content'])
  1322. ]);
  1323. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  1324. $aiResult = [
  1325. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1326. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1327. 'usage' => $result['usage'] ?? [],
  1328. 'model' => $model,
  1329. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1330. ];
  1331. } else {
  1332. Utils::throwError('20003:不支持的模型: ' . $model);
  1333. }
  1334. } catch (\Exception $e) {
  1335. // 生成失败,更新任务状态
  1336. if ($generateTaskId) {
  1337. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1338. 'status' => 'failed',
  1339. 'error_message' => $e->getMessage(),
  1340. 'completed_at' => date('Y-m-d H:i:s'),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. }
  1344. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1345. }
  1346. // 生成成功,更新任务状态
  1347. if ($generateTaskId && $aiResult) {
  1348. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1349. 'status' => 'success',
  1350. 'result' => getProp($aiResult, 'content', ''),
  1351. 'completed_at' => date('Y-m-d H:i:s'),
  1352. 'updated_at' => date('Y-m-d H:i:s')
  1353. ]);
  1354. $aiResult['generate_task_id'] = $generateTaskId;
  1355. }
  1356. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1357. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1358. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1359. 'model' => $model,
  1360. 'script_id' => $script_id,
  1361. 'sequence' => $sequence,
  1362. 'source' => 'newGenerateText',
  1363. ]);
  1364. }
  1365. // 新增: 如果提供了script_id,保存对话记录
  1366. if ($script_id > 0 && $aiResult) {
  1367. try {
  1368. $uid = Site::getUid();
  1369. $now = now();
  1370. // 获取用户原始的prompt(不包含剧本内容)
  1371. $originalPrompt = getProp($data, 'prompt', '');
  1372. $recordsToInsert = [
  1373. [
  1374. 'uid' => $uid,
  1375. 'script_id' => $script_id,
  1376. 'sequence' => $sequence,
  1377. 'role' => 'user',
  1378. 'content' => $originalPrompt,
  1379. 'created_at' => $now,
  1380. 'updated_at' => $now,
  1381. ],
  1382. [
  1383. 'uid' => $uid,
  1384. 'script_id' => $script_id,
  1385. 'sequence' => $sequence,
  1386. 'role' => 'assistant',
  1387. 'content' => $aiResult['content'],
  1388. 'created_at' => $now,
  1389. 'updated_at' => $now,
  1390. ]
  1391. ];
  1392. DB::table('mp_script_records')->insert($recordsToInsert);
  1393. // 获取刚插入的记录ID(假设按插入顺序返回)
  1394. $insertedRecords = DB::table('mp_script_records')
  1395. ->where('uid', $uid)
  1396. ->where('script_id', $script_id)
  1397. ->where('sequence', $sequence)
  1398. ->orderBy('id', 'desc')
  1399. ->limit(2)
  1400. ->get()
  1401. ->map(function ($record) {
  1402. return [
  1403. 'rid' => $record->id,
  1404. 'script_id' => $record->script_id,
  1405. 'sequence' => $record->sequence,
  1406. 'role' => $record->role,
  1407. 'content' => $record->content,
  1408. 'created_at' => $record->created_at,
  1409. ];
  1410. })
  1411. ->reverse()
  1412. ->values()
  1413. ->toArray();
  1414. // 将记录信息添加到返回结果中
  1415. $aiResult['records'] = $insertedRecords;
  1416. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1417. } catch (\Exception $e) {
  1418. // 记录错误但不影响主流程
  1419. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1420. }
  1421. }
  1422. return $aiResult;
  1423. }
  1424. /**
  1425. * 通用 Gemini 文生文方法(支持流式和非流式)
  1426. *
  1427. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1428. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1429. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1430. * system_prompt 系统提示词(可选)
  1431. * prompt 用户提示词(可选)
  1432. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1433. * image_urls 图片/视频URL列表(可选,同上)
  1434. * temperature 温度(可选,默认 1)
  1435. * top_p 核采样(可选)
  1436. * max_tokens 最大输出 token(可选,默认 8192)
  1437. * response_format text/json(可选)
  1438. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1439. * thinking_budget 思考预算(可选,默认 20)
  1440. * stream 是否流式(可选,默认 false)
  1441. *
  1442. * @param array $data 请求参数
  1443. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1444. */
  1445. public function geminiGenerateText($data) {
  1446. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1447. $isStream = (bool)getProp($data, 'stream', false);
  1448. if (!in_array($model, $this->gemini_text_models)) {
  1449. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1450. }
  1451. $requestData = $this->buildGeminiRequestBody($data, $model);
  1452. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1453. if ($isStream) {
  1454. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1455. return $this->wrapGenerateTextTokenRecord(
  1456. $this->geminiStreamResponse($requestData, $model),
  1457. $this->getCurrentUid(),
  1458. $model,
  1459. 'geminiGenerateText'
  1460. );
  1461. }
  1462. // 非流式:成功后记录 token 使用明细(不扣积分)
  1463. $result = $this->geminiChatOnly($requestData, $model);
  1464. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1465. 'model' => $model,
  1466. 'source' => 'geminiGenerateText',
  1467. ], $model);
  1468. return $result;
  1469. }
  1470. /**
  1471. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1472. */
  1473. private function geminiMediaMaxBytes() {
  1474. return 14 * 1024 * 1024;
  1475. }
  1476. /**
  1477. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1478. */
  1479. private function buildGeminiRequestBody($data, $model) {
  1480. $messages = getProp($data, 'messages', []);
  1481. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1482. if (empty($messages)) {
  1483. $systemPrompt = getProp($data, 'system_prompt', '');
  1484. $prompt = getProp($data, 'prompt', '');
  1485. $images = getProp($data, 'images', []);
  1486. $imageUrls = getProp($data, 'image_urls', []);
  1487. $messages = [];
  1488. if (!empty($systemPrompt)) {
  1489. $messages[] = [
  1490. 'role' => 'system',
  1491. 'content' => $systemPrompt
  1492. ];
  1493. }
  1494. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1495. $userMessage = ['role' => 'user', 'content' => []];
  1496. if (!empty($prompt)) {
  1497. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1498. }
  1499. if (!empty($images)) {
  1500. if (!is_array($images)) {
  1501. $images = [$images];
  1502. }
  1503. foreach ($images as $image) {
  1504. $inlineData = $this->processMediaToInlineData($image);
  1505. if ($inlineData) {
  1506. $userMessage['content'][] = [
  1507. 'type' => 'image',
  1508. 'inline_data' => $inlineData
  1509. ];
  1510. }
  1511. }
  1512. }
  1513. if (!empty($imageUrls)) {
  1514. if (!is_array($imageUrls)) {
  1515. $imageUrls = [$imageUrls];
  1516. }
  1517. foreach ($imageUrls as $url) {
  1518. if (!empty($url)) {
  1519. $inlineData = $this->processMediaToInlineData($url);
  1520. if ($inlineData) {
  1521. $userMessage['content'][] = [
  1522. 'type' => 'image',
  1523. 'inline_data' => $inlineData
  1524. ];
  1525. }
  1526. }
  1527. }
  1528. }
  1529. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1530. $userMessage['content'] = $userMessage['content'][0]['text'];
  1531. }
  1532. $messages[] = $userMessage;
  1533. }
  1534. }
  1535. if (empty($messages)) {
  1536. Utils::throwError('20003:请提供有效的对话内容');
  1537. }
  1538. // 转换为 Gemini contents 格式
  1539. $systemInstruction = '';
  1540. $contents = [];
  1541. foreach ($messages as $message) {
  1542. $role = getProp($message, 'role', 'user');
  1543. $content = getProp($message, 'content', '');
  1544. if ($role === 'system') {
  1545. if (is_array($content)) {
  1546. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1547. } else {
  1548. $systemInstruction = (string)$content;
  1549. }
  1550. continue;
  1551. }
  1552. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1553. $parts = [];
  1554. if (is_array($content)) {
  1555. foreach ($content as $part) {
  1556. $partType = getProp($part, 'type', 'text');
  1557. if ($partType === 'text') {
  1558. $text = (string)getProp($part, 'text', '');
  1559. if ($text !== '') {
  1560. $parts[] = ['text' => $text];
  1561. }
  1562. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1563. if (in_array($partType, ['image_url', 'video_url'])) {
  1564. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1565. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1566. } elseif (isset($part['inline_data'])) {
  1567. // 已处理过的 inline_data 直接使用
  1568. $parts[] = ['inline_data' => $part['inline_data']];
  1569. continue;
  1570. } else {
  1571. $url = '';
  1572. }
  1573. $inlineData = $this->processMediaToInlineData($url);
  1574. if ($inlineData) {
  1575. $parts[] = ['inline_data' => $inlineData];
  1576. }
  1577. }
  1578. }
  1579. } else {
  1580. $text = (string)$content;
  1581. if ($text !== '') {
  1582. $parts[] = ['text' => $text];
  1583. }
  1584. }
  1585. if (!empty($parts)) {
  1586. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1587. }
  1588. }
  1589. if (empty($contents)) {
  1590. Utils::throwError('20003:请提供有效的对话内容');
  1591. }
  1592. // 构建生成配置
  1593. $generationConfig = [];
  1594. if (getProp($data, 'temperature', null) !== null) {
  1595. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1596. }
  1597. if (getProp($data, 'top_p', null) !== null) {
  1598. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1599. }
  1600. if (getProp($data, 'frequency_penalty', null) !== null) {
  1601. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1602. }
  1603. if (getProp($data, 'presence_penalty', null) !== null) {
  1604. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1605. }
  1606. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1607. if ($maxOutputTokens <= 0) {
  1608. $maxOutputTokens = 8192;
  1609. }
  1610. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1611. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1612. $maxOutputTokens = 32768;
  1613. }
  1614. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1615. // response_format 映射:text -> text/plain,json -> application/json
  1616. $responseFormat = getProp($data, 'response_format', 'text');
  1617. if (is_array($responseFormat)) {
  1618. $responseFormat = getProp($responseFormat, 'type', 'text');
  1619. }
  1620. if (in_array($responseFormat, ['json', 'json_object'])) {
  1621. $generationConfig['responseMimeType'] = 'application/json';
  1622. } else {
  1623. $generationConfig['responseMimeType'] = 'text/plain';
  1624. }
  1625. $requestData = [
  1626. 'contents' => $contents,
  1627. 'generationConfig' => $generationConfig,
  1628. ];
  1629. if ($systemInstruction !== '') {
  1630. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1631. }
  1632. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1633. $thinkingMode = getProp($data, 'thinking', null);
  1634. if (is_array($thinkingMode)) {
  1635. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1636. }
  1637. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1638. if ($thinkingMode === null) {
  1639. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1640. }
  1641. if ($thinkingMode === 'enabled') {
  1642. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1643. if ($thinkingBudget <= 0) {
  1644. $thinkingBudget = 20;
  1645. }
  1646. $requestData['generationConfig']['thinkingConfig'] = [
  1647. 'thinkingBudget' => $thinkingBudget
  1648. ];
  1649. } elseif ($defaultThinking) {
  1650. // 该模型仅支持思考模式,传 0 会返回 400
  1651. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1652. } else {
  1653. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1654. }
  1655. return $requestData;
  1656. }
  1657. /**
  1658. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1659. *
  1660. * 模型名 -> env 变量名映射:
  1661. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1662. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1663. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1664. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1665. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1666. */
  1667. private function getGeminiApiKey($model) {
  1668. $map = [
  1669. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1670. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1671. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1672. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1673. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1674. ];
  1675. if (isset($map[$model])) {
  1676. $key = env($map[$model]);
  1677. if (!empty($key)) {
  1678. return $key;
  1679. }
  1680. }
  1681. return env('GEMINI_API_KEY', '');
  1682. }
  1683. /**
  1684. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1685. */
  1686. private function geminiChatOnly($requestData, $model) {
  1687. $apiKey = $this->getGeminiApiKey($model);
  1688. if (empty($apiKey)) {
  1689. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1690. }
  1691. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1692. if (isset($requestData['messages'])) {
  1693. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1694. }
  1695. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1696. . '/models/' . $model . ':generateContent';
  1697. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1698. $headers = [
  1699. 'Authorization' => 'Bearer ' . $apiKey,
  1700. 'Content-Type' => 'application/json'
  1701. ];
  1702. $maxRetries = $this->gptRetryTimes();
  1703. $interval = $this->gptRetryInterval();
  1704. $attempt = 0;
  1705. while (true) {
  1706. try {
  1707. $response = $client->post($url, [
  1708. 'json' => $requestData,
  1709. 'headers' => $headers
  1710. ]);
  1711. $responseArr = json_decode($response->getBody()->getContents(), true);
  1712. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1713. $fullContent = $this->extractGeminiContent($responseArr);
  1714. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1715. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1716. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1717. ? $responseArr['candidates'][0]['finishReason']
  1718. : '';
  1719. return [
  1720. 'fullContent' => $fullContent,
  1721. 'fullReasoningContent' => $fullReasoningContent,
  1722. 'usage' => $usage,
  1723. 'finish_reason' => $finishReason
  1724. ];
  1725. } catch (\Exception $e) {
  1726. $retryable = true;
  1727. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1728. $status = $e->getResponse()->getStatusCode();
  1729. $retryable = $status >= 500 || $status == 429;
  1730. }
  1731. if (!$retryable || $attempt >= $maxRetries) {
  1732. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1733. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1734. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1735. }
  1736. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1737. 'retry' => $attempt + 1,
  1738. 'max_retries' => $maxRetries,
  1739. 'error' => $e->getMessage()
  1740. ]);
  1741. sleep($interval);
  1742. $attempt++;
  1743. }
  1744. }
  1745. }
  1746. /**
  1747. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1748. */
  1749. private function geminiStreamResponse($requestData, $model) {
  1750. $apiKey = $this->getGeminiApiKey($model);
  1751. if (empty($apiKey)) {
  1752. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1753. }
  1754. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1755. if (isset($requestData['messages'])) {
  1756. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1757. }
  1758. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1759. . '/models/' . $model . ':generateContent?alt=sse';
  1760. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1761. $headers = [
  1762. 'Authorization' => 'Bearer ' . $apiKey,
  1763. 'Content-Type' => 'application/json'
  1764. ];
  1765. try {
  1766. $response = $client->post($url, [
  1767. 'json' => $requestData,
  1768. 'headers' => $headers,
  1769. 'stream' => true
  1770. ]);
  1771. $body = $response->getBody();
  1772. $fullContent = '';
  1773. $fullReasoningContent = '';
  1774. $usage = [];
  1775. $buffer = '';
  1776. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1777. while (!$body->eof()) {
  1778. $chunk = $body->read(1024);
  1779. $buffer .= $chunk;
  1780. $lines = explode("\n", $buffer);
  1781. $buffer = array_pop($lines);
  1782. foreach ($lines as $line) {
  1783. $line = trim($line);
  1784. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1785. continue;
  1786. }
  1787. $data = substr($line, 6);
  1788. if ($data === '[DONE]') {
  1789. break 2;
  1790. }
  1791. try {
  1792. $json = json_decode($data, true);
  1793. if (json_last_error() !== JSON_ERROR_NONE) {
  1794. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1795. continue;
  1796. }
  1797. // 思考内容(thoughts)
  1798. $thoughts = $this->extractGeminiThoughts($json);
  1799. if ($thoughts !== '') {
  1800. $fullReasoningContent .= $thoughts;
  1801. yield [
  1802. 'type' => 'reasoning',
  1803. 'content' => $thoughts,
  1804. 'full_reasoning' => $fullReasoningContent
  1805. ];
  1806. }
  1807. // 回答内容
  1808. $partText = $this->extractGeminiContent($json);
  1809. if ($partText !== '') {
  1810. $fullContent .= $partText;
  1811. yield [
  1812. 'type' => 'content',
  1813. 'content' => $partText,
  1814. ];
  1815. }
  1816. // 使用统计
  1817. if (isset($json['usageMetadata'])) {
  1818. $usage = $json['usageMetadata'];
  1819. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1820. }
  1821. } catch (\Exception $e) {
  1822. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1823. continue;
  1824. }
  1825. }
  1826. }
  1827. dLog('deepseek')->info('Gemini流式读取完成', [
  1828. 'content_length' => strlen($fullContent),
  1829. 'reasoning_length' => strlen($fullReasoningContent)
  1830. ]);
  1831. yield [
  1832. 'type' => 'done',
  1833. 'full_content' => $fullContent,
  1834. 'full_reasoning' => $fullReasoningContent,
  1835. 'usage' => $usage
  1836. ];
  1837. } catch (\Exception $e) {
  1838. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1839. yield [
  1840. 'type' => 'error',
  1841. 'msg' => $e->getMessage(),
  1842. 'code' => $e->getCode()
  1843. ];
  1844. }
  1845. }
  1846. /**
  1847. * 从 Gemini 响应中提取回答文本
  1848. */
  1849. private function extractGeminiContent($responseArr) {
  1850. $text = '';
  1851. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1852. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1853. if (isset($part['text'])) {
  1854. $text .= $part['text'];
  1855. }
  1856. }
  1857. }
  1858. return $text;
  1859. }
  1860. /**
  1861. * 从 Gemini 响应中提取思考内容
  1862. */
  1863. private function extractGeminiReasoningContent($responseArr) {
  1864. $reasoning = '';
  1865. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1866. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1867. if (isset($thought['text'])) {
  1868. $reasoning .= $thought['text'];
  1869. }
  1870. }
  1871. }
  1872. return $reasoning;
  1873. }
  1874. /**
  1875. * 从 Gemini 流式响应中提取本次增量思考内容
  1876. */
  1877. private function extractGeminiThoughts($responseArr) {
  1878. $thoughts = '';
  1879. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1880. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1881. if (isset($thought['text'])) {
  1882. $thoughts .= $thought['text'];
  1883. }
  1884. }
  1885. }
  1886. return $thoughts;
  1887. }
  1888. /**
  1889. * 提取消息数组中的纯文本
  1890. */
  1891. private function extractGeminiTextFromParts($parts) {
  1892. $text = '';
  1893. if (is_array($parts)) {
  1894. foreach ($parts as $part) {
  1895. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1896. $text .= (string)getProp($part, 'text', '');
  1897. }
  1898. }
  1899. }
  1900. return $text;
  1901. }
  1902. /**
  1903. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1904. *
  1905. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1906. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1907. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1908. *
  1909. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1910. * @return array|null ['mime_type' => string, 'data' => string]
  1911. */
  1912. private function processMediaToInlineData($media) {
  1913. if (empty($media)) {
  1914. return null;
  1915. }
  1916. $localPath = null;
  1917. $isTempFile = false;
  1918. try {
  1919. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1920. if (is_string($media) && strpos($media, 'data:') === 0) {
  1921. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1922. return [
  1923. 'mime_type' => $matches[1],
  1924. 'data' => $matches[2]
  1925. ];
  1926. }
  1927. return null;
  1928. }
  1929. // 2. 获取本地文件路径
  1930. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1931. $localPath = $this->downloadMediaToTemp($media);
  1932. $isTempFile = true;
  1933. } elseif (is_string($media)) {
  1934. $localPath = $media;
  1935. } else {
  1936. // Laravel UploadedFile 对象
  1937. $localPath = $media->getRealPath();
  1938. }
  1939. if (!$localPath || !file_exists($localPath)) {
  1940. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1941. return null;
  1942. }
  1943. $fileSize = filesize($localPath);
  1944. $maxBytes = $this->geminiMediaMaxBytes();
  1945. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1946. $mimeType = $this->detectMediaMime($localPath);
  1947. $isVideo = strpos($mimeType, 'video/') === 0;
  1948. $needCompress = $fileSize > $maxBytes;
  1949. $duration = 0;
  1950. if ($isVideo) {
  1951. $duration = $this->getMediaDuration($localPath);
  1952. if ($duration > 300) {
  1953. $needCompress = true;
  1954. }
  1955. }
  1956. $finalPath = $localPath;
  1957. $compressedPath = null;
  1958. if ($needCompress && $this->ffmpegAvailable()) {
  1959. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1960. if ($compressed && file_exists($compressed)) {
  1961. $compressedPath = $compressed;
  1962. if (filesize($compressed) < $fileSize || $isVideo) {
  1963. $finalPath = $compressed;
  1964. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1965. } else {
  1966. @unlink($compressed);
  1967. $compressedPath = null;
  1968. }
  1969. }
  1970. }
  1971. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1972. $finalSize = filesize($finalPath);
  1973. if ($finalSize > $maxBytes) {
  1974. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1975. 'path' => $localPath,
  1976. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1977. 'limit_mb' => 14
  1978. ]);
  1979. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1980. }
  1981. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1982. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1983. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1984. }
  1985. $data = base64_encode(file_get_contents($finalPath));
  1986. return [
  1987. 'mime_type' => $mimeType,
  1988. 'data' => $data
  1989. ];
  1990. } catch (\App\Exceptions\ApiException $e) {
  1991. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1992. throw $e;
  1993. } catch (\Exception $e) {
  1994. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1995. return null;
  1996. } finally {
  1997. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1998. @unlink($compressedPath);
  1999. }
  2000. if ($isTempFile && $localPath && file_exists($localPath)) {
  2001. @unlink($localPath);
  2002. }
  2003. }
  2004. }
  2005. /**
  2006. * 下载远程多媒体到临时目录
  2007. *
  2008. * @return string|null 本地临时文件路径
  2009. */
  2010. private function downloadMediaToTemp($url) {
  2011. try {
  2012. $tempDir = storage_path('app/temp/gemini');
  2013. if (!is_dir($tempDir)) {
  2014. mkdir($tempDir, 0775, true);
  2015. }
  2016. $extension = 'tmp';
  2017. $pathInfo = parse_url($url, PHP_URL_PATH);
  2018. if ($pathInfo) {
  2019. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2020. if ($ext && strlen($ext) <= 10) {
  2021. $extension = strtolower($ext);
  2022. }
  2023. }
  2024. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2025. $client = new Client(['timeout' => 300, 'verify' => false]);
  2026. $response = $client->get($url, ['sink' => $tmpFile]);
  2027. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2028. @unlink($tmpFile);
  2029. return null;
  2030. }
  2031. return $tmpFile;
  2032. } catch (\Exception $e) {
  2033. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2034. return null;
  2035. }
  2036. }
  2037. /**
  2038. * 检测多媒体文件 MIME 类型
  2039. */
  2040. private function detectMediaMime($filePath) {
  2041. $imageInfo = @getimagesize($filePath);
  2042. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2043. return $imageInfo['mime'];
  2044. }
  2045. // 视频按扩展名粗略判断
  2046. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2047. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2048. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2049. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2050. if (isset($videoExts[$ext])) {
  2051. return $videoExts[$ext];
  2052. }
  2053. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2054. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2055. if (isset($imageExts[$ext])) {
  2056. return $imageExts[$ext];
  2057. }
  2058. return 'application/octet-stream';
  2059. }
  2060. /**
  2061. * 获取多媒体时长(秒),非视频或失败返回 0
  2062. */
  2063. private function getMediaDuration($filePath) {
  2064. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2065. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2066. $output = trim((string)shell_exec($cmd));
  2067. $duration = (float)$output;
  2068. return $duration > 0 ? $duration : 0;
  2069. }
  2070. /**
  2071. * 检查 ffmpeg 是否可用
  2072. */
  2073. private function ffmpegAvailable() {
  2074. static $available = null;
  2075. if ($available !== null) {
  2076. return $available;
  2077. }
  2078. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2079. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2080. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2081. $available = false;
  2082. return $available;
  2083. }
  2084. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2085. $output = shell_exec($cmd);
  2086. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2087. return $available;
  2088. }
  2089. /**
  2090. * 使用 ffmpeg 压缩多媒体文件
  2091. *
  2092. * @param string $inputFile 输入文件路径
  2093. * @param bool $isVideo 是否为视频
  2094. * @param float $duration 视频时长(秒),非视频传 0
  2095. * @return string|null 压缩后的文件路径,失败返回 null
  2096. */
  2097. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2098. try {
  2099. $tempDir = storage_path('app/temp/gemini');
  2100. if (!is_dir($tempDir)) {
  2101. mkdir($tempDir, 0775, true);
  2102. }
  2103. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2104. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2105. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2106. if ($isVideo) {
  2107. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2108. $speedFactor = 1.0;
  2109. if ($duration > 300) {
  2110. $speedFactor = $duration / 300;
  2111. }
  2112. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2113. $finalDuration = $duration / max(1.0, $speedFactor);
  2114. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2115. $targetBitrate = max(300, min(6000, $targetBitrate));
  2116. $filters = [];
  2117. $filters[] = 'scale=min(1280,iw):-2';
  2118. $filters[] = 'fps=24';
  2119. if ($speedFactor > 1.0) {
  2120. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2121. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2122. $fullCount = (int)ceil($speedFactor / 2.0);
  2123. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2124. if ($lastTempo < 0.5) {
  2125. $fullCount++;
  2126. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2127. }
  2128. for ($i = 0; $i < $fullCount; $i++) {
  2129. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2130. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2131. }
  2132. }
  2133. $filterStr = implode(',', $filters);
  2134. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2135. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2136. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2137. } else {
  2138. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2139. $imageInfo = @getimagesize($inputFile);
  2140. $scaleW = 2048;
  2141. $scaleH = 2048;
  2142. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2143. if ($imageInfo[0] >= $imageInfo[1]) {
  2144. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2145. $scaleW = 2048;
  2146. } else {
  2147. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2148. $scaleH = 2048;
  2149. }
  2150. }
  2151. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2152. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2153. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2154. }
  2155. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2156. $output = shell_exec($cmd);
  2157. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2158. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2159. 'input' => $inputFile,
  2160. 'output' => $output
  2161. ]);
  2162. @unlink($outputFile);
  2163. return null;
  2164. }
  2165. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2166. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2167. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2168. ]);
  2169. return $outputFile;
  2170. } catch (\Exception $e) {
  2171. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2172. return null;
  2173. }
  2174. }
  2175. /**
  2176. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2177. *
  2178. * @param array $data
  2179. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2180. */
  2181. public function getScriptGenerateTasks($data) {
  2182. $uid = Site::getUid();
  2183. return DB::table('mp_script_generate_tasks as t')
  2184. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2185. ->where('t.uid', $uid)
  2186. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2187. ->orderByDesc('t.id')
  2188. ->paginate(15);
  2189. }
  2190. public function saveScriptChatHistory($data) {
  2191. $uid = Site::getUid();
  2192. $rid = getProp($data, 'rid');
  2193. $script_id = getProp($data, 'script_id');
  2194. $sequence = getProp($data, 'sequence', 0);
  2195. $content = getProp($data, 'content');
  2196. if (!$rid) {
  2197. Utils::throwError('20003:请选择对话记录ID');
  2198. }
  2199. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2200. if (!$record) {
  2201. Utils::throwError('20003:对话记录不存在');
  2202. }
  2203. if (!$script_id) {
  2204. Utils::throwError('20003:请选择剧本');
  2205. }
  2206. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2207. if (!$script) {
  2208. Utils::throwError('20003:剧本不存在');
  2209. }
  2210. // 批量插入数据
  2211. return DB::table('mp_script_records')->where('id', $rid)->update([
  2212. 'content' => $content,
  2213. 'updated_at' => date('Y-m-d H:i:s')
  2214. ]);
  2215. }
  2216. /**
  2217. * 获取剧本的历史对话记录
  2218. *
  2219. * @param array $data 请求参数
  2220. * @return array 返回历史记录数组
  2221. */
  2222. public function getScriptChatHistory($data) {
  2223. $uid = Site::getUid();
  2224. $script_id = getProp($data, 'script_id');
  2225. $rid = getProp($data, 'rid');
  2226. $sequence = getProp($data, 'sequence', null);
  2227. if (!$script_id) {
  2228. Utils::throwError('20003:请提供剧本ID');
  2229. }
  2230. // 验证剧本是否存在
  2231. $script = DB::table('mp_scripts')
  2232. ->where('id', $script_id)
  2233. ->where('is_deleted', 0)
  2234. ->first();
  2235. if (!$script) {
  2236. Utils::throwError('20003:剧本不存在');
  2237. }
  2238. // 构建查询
  2239. $query = DB::table('mp_script_records')
  2240. ->where('script_id', $script_id);
  2241. // ->where('uid', $uid);
  2242. // 如果提供了 sequence,则过滤指定剧集
  2243. if ($sequence !== null) {
  2244. $query->where('sequence', $sequence);
  2245. }
  2246. // 记录ID筛选
  2247. if ($rid) {
  2248. $query->where('id', $rid);
  2249. }
  2250. // 查询记录并按 id 正序排序
  2251. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2252. ->orderBy('created_at', 'asc')
  2253. ->orderBy('id', 'asc')
  2254. ->get()
  2255. ->map(function ($record) {
  2256. return [
  2257. 'rid' => $record->id,
  2258. 'script_id' => $record->script_id,
  2259. 'sequence' => $record->sequence,
  2260. 'role' => $record->role,
  2261. 'content' => $record->content,
  2262. 'products' => $record->products ? json_decode($record->products) : [],
  2263. 'created_at' => $record->created_at,
  2264. ];
  2265. })
  2266. ->toArray();
  2267. return $records;
  2268. }
  2269. /**
  2270. * 处理图片转换为base64
  2271. *
  2272. * @param mixed $image 图片文件对象或文件路径
  2273. * @return string|null base64编码的图片数据
  2274. */
  2275. private function processImageToBase64($image) {
  2276. try {
  2277. // 获取文件路径
  2278. if (is_string($image)) {
  2279. $filePath = $image;
  2280. } else {
  2281. // Laravel UploadedFile 对象
  2282. $filePath = $image->getRealPath();
  2283. }
  2284. if (!file_exists($filePath)) {
  2285. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2286. return null;
  2287. }
  2288. // 验证是否为图片文件
  2289. $imageInfo = @getimagesize($filePath);
  2290. if ($imageInfo === false) {
  2291. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2292. return null;
  2293. }
  2294. // 读取图片并转换为base64
  2295. $imageData = file_get_contents($filePath);
  2296. $base64Image = base64_encode($imageData);
  2297. dLog('deepseek')->info('图片转换成功', [
  2298. 'size' => strlen($imageData),
  2299. 'type' => $imageInfo['mime']
  2300. ]);
  2301. return $base64Image;
  2302. } catch (\Exception $e) {
  2303. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2304. return null;
  2305. }
  2306. }
  2307. private function getArtStylePromptMappings($art_style='')
  2308. {
  2309. $arr = [
  2310. '唯美真人风格' => [
  2311. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2312. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2313. ],
  2314. '真人古风风格' => [
  2315. 'aliases' => ['真人古风风格', '真人古风'],
  2316. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2317. ],
  2318. '日系动漫风格' => [
  2319. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2320. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2321. ],
  2322. '国漫风格' => [
  2323. 'aliases' => ['国漫风格', '国漫'],
  2324. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2325. ],
  2326. 'Q版卡通风格' => [
  2327. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2328. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2329. ],
  2330. '简约扁平风格' => [
  2331. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2332. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2333. ],
  2334. '武侠风格' => [
  2335. 'aliases' => ['武侠风格', '武侠'],
  2336. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2337. ],
  2338. '古风仙侠风格' => [
  2339. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2340. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2341. ],
  2342. '新中式水墨风格' => [
  2343. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2344. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2345. ],
  2346. '写实插画风格' => [
  2347. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2348. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2349. ],
  2350. '3D卡通风格' => [
  2351. 'aliases' => ['3D卡通风格', '3D卡通'],
  2352. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2353. ],
  2354. '条漫风格' => [
  2355. 'aliases' => ['条漫风格', '条漫'],
  2356. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2357. ],
  2358. '赛博朋克风格' => [
  2359. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2360. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2361. ],
  2362. '暗黑悬疑风格' => [
  2363. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2364. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2365. ],
  2366. '治愈清新风格' => [
  2367. 'aliases' => ['治愈清新风格', '治愈清新'],
  2368. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2369. ],
  2370. '3D真人风格' => [
  2371. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2372. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2373. ],
  2374. ];
  2375. if($art_style) {
  2376. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2377. }
  2378. return $arr;
  2379. $arr = [
  2380. '唯美真人风格' => [
  2381. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2382. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2383. 2. 色彩色调
  2384. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2385. 3. 画质精度
  2386. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2387. 4. 画面观感
  2388. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2389. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2390. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2391. ],
  2392. '真人古风风格' => [
  2393. 'aliases' => ['真人古风风格', '真人古风'],
  2394. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2395. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2396. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2397. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2398. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2399. ],
  2400. '日系动漫风格' => [
  2401. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2402. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2403. 正向提示词(中文)
  2404. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2405. 必须遵守规则
  2406. • 全程保持日系动漫风格,不混入其他画风
  2407. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2408. • 画面适配所选画面比例,构图居中,主体突出
  2409. • 线条干净、色彩统一,不杂乱、不突兀
  2410. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2411. ],
  2412. '国漫风格' => [
  2413. 'aliases' => ['国漫风格', '国漫'],
  2414. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2415. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2416. 必须遵守规则
  2417. • 严格保持国漫画风,不串风格、不混画风
  2418. • 角色形象统一,不随意改变五官、身材、服饰
  2419. • 画面构图稳定,适合漫剧叙事展示
  2420. • 色调统一,不出现脏色、杂色
  2421. 禁止/避免词汇
  2422. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2423. ],
  2424. 'Q版卡通风格' => [
  2425. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2426. 'prompt' => "风格说明
  2427. 头大身小,造型可爱圆润,简约干净
  2428. 正向提示词(中文)
  2429. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2430. 必须遵守规则
  2431. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2432. • 角色造型统一,表情可爱,不诡异
  2433. • 画面简洁清爽,无多余复杂元素
  2434. • 色彩明亮柔和,不刺眼
  2435. 禁止/避免词汇
  2436. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2437. ],
  2438. '简约扁平风格' => [
  2439. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2440. 'prompt' => "风格说明
  2441. 色块简洁、无复杂渐变,现代极简风
  2442. 正向提示词(中文)
  2443. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2444. 必须遵守规则
  2445. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2446. • 构图简洁,主体突出,无多余装饰
  2447. • 色彩统一、干净,不杂乱
  2448. 禁止/避免词汇
  2449. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2450. ],
  2451. '武侠风格' => [
  2452. 'aliases' => ['武侠风格', '武侠'],
  2453. 'prompt' => "风格说明
  2454. 江湖气息,线条硬朗,动作感强
  2455. 正向提示词(中文)
  2456. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2457. 必须遵守规则
  2458. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2459. • 角色形象、服饰、身材比例统一
  2460. • 画面动作自然,不扭曲、不畸形
  2461. 禁止/避免词汇
  2462. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2463. ],
  2464. '古风仙侠风格' => [
  2465. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2466. 'prompt' => "风格说明
  2467. 飘逸汉服、云雾仙气、唯美空灵
  2468. 正向提示词(中文)
  2469. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2470. 必须遵守规则
  2471. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2472. • 角色服饰、发型、形象前后一致
  2473. • 场景仙气飘逸,色调清雅统一
  2474. • 画面唯美柔和,不阴暗、不诡异
  2475. 禁止/避免词汇
  2476. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2477. ],
  2478. '新中式水墨风格' => [
  2479. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2480. 'prompt' => "风格说明
  2481. 淡墨渲染,毛笔笔触,留白意境
  2482. 正向提示词(中文)
  2483. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2484. 必须遵守规则
  2485. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2486. • 色调淡雅统一,不浓艳杂乱
  2487. • 画面干净有意境,不堆砌元素
  2488. 禁止/避免词汇
  2489. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2490. ],
  2491. '写实插画风格' => [
  2492. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2493. 'prompt' => "风格说明
  2494. 接近真人比例,光影真实,质感细腻
  2495. 正向提示词(中文)
  2496. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2497. 必须遵守规则
  2498. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2499. • 角色五官、身材、服饰高度统一
  2500. • 画面清晰、光影自然、不扭曲
  2501. 禁止/避免词汇
  2502. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2503. ],
  2504. '3D卡通风格' => [
  2505. 'aliases' => ['3D卡通风格', '3D卡通'],
  2506. 'prompt' => "风格说明
  2507. 3D建模质感,柔和渲染,圆润可爱
  2508. 正向提示词(中文)
  2509. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2510. 必须遵守规则
  2511. • 保持3D卡通统一质感,不出现2D杂乱线条
  2512. • 角色模型、比例、形象前后一致
  2513. • 画面干净,不模糊、不穿模
  2514. 禁止/避免词汇
  2515. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2516. ],
  2517. '条漫风格' => [
  2518. 'aliases' => ['条漫风格', '条漫'],
  2519. 'prompt' => "风格说明
  2520. 纵向分镜,上下滑动阅读,轻量化
  2521. 正向提示词(中文)
  2522. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2523. 必须遵守规则
  2524. • 保持条漫纵向阅读逻辑,构图简洁
  2525. • 画风统一,不混写实、3D、水墨
  2526. • 画面干净,不杂乱
  2527. 禁止/避免词汇
  2528. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2529. ],
  2530. '赛博朋克风格' => [
  2531. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2532. 'prompt' => "风格说明
  2533. 霓虹灯光、未来都市、暗色调、科技机械
  2534. 正向提示词(中文)
  2535. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2536. 必须遵守规则
  2537. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2538. • 色调以暗调+霓虹为主,色彩统一
  2539. • 画面科技感强,不杂乱
  2540. 禁止/避免词汇
  2541. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2542. ],
  2543. '暗黑悬疑风格' => [
  2544. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2545. 'prompt' => "风格说明
  2546. 低饱和、冷色调、阴影重、神秘压抑
  2547. 正向提示词(中文)
  2548. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2549. 必须遵守规则
  2550. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2551. • 画面氛围压抑神秘,但不低俗、不血腥
  2552. • 角色形象统一,不崩坏
  2553. 禁止/避免词汇
  2554. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2555. ],
  2556. '治愈清新风格' => [
  2557. 'aliases' => ['治愈清新风格', '治愈清新'],
  2558. 'prompt' => "风格说明
  2559. 马卡龙色系、柔光、温暖干净
  2560. 正向提示词(中文)
  2561. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2562. 必须遵守规则
  2563. • 保持治愈清新统一色调,不阴暗、不诡异
  2564. • 画面柔和干净,无杂乱元素
  2565. • 角色形象柔和可爱,不狰狞
  2566. 禁止/避免词汇
  2567. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2568. ],
  2569. ];
  2570. return $arr;
  2571. }
  2572. public function getArtStylePromptByInput($inputArtStyle): string
  2573. {
  2574. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2575. if ($normalizedInput === '') {
  2576. return '';
  2577. }
  2578. return $this->getArtStylePromptMappings($normalizedInput);
  2579. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2580. // foreach ($mapping['aliases'] as $alias) {
  2581. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2582. // if ($normalizedAlias === '') {
  2583. // continue;
  2584. // }
  2585. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2586. // return $mapping['prompt'];
  2587. // }
  2588. // }
  2589. // }
  2590. return '';
  2591. }
  2592. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2593. $stylePrefixes = [
  2594. '唯美真人风格' => [
  2595. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2596. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2597. ],
  2598. '真人古风风格' => [
  2599. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2600. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2601. ],
  2602. '日系动漫风格' => [
  2603. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2604. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2605. ],
  2606. '国漫风格' => [
  2607. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2608. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2609. ],
  2610. 'Q版卡通风格' => [
  2611. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2612. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2613. ],
  2614. '简约扁平风格' => [
  2615. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2616. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2617. ],
  2618. '武侠风格' => [
  2619. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2620. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2621. ],
  2622. '古风仙侠风格' => [
  2623. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2624. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2625. ],
  2626. '新中式水墨风格' => [
  2627. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2628. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2629. ],
  2630. '写实插画风格' => [
  2631. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2632. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2633. ],
  2634. '3D卡通风格' => [
  2635. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2636. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2637. ],
  2638. '条漫风格' => [
  2639. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2640. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2641. ],
  2642. '赛博朋克风格' => [
  2643. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2644. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2645. ],
  2646. '暗黑悬疑风格' => [
  2647. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2648. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2649. ],
  2650. '治愈清新风格' => [
  2651. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2652. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2653. ]
  2654. ];
  2655. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2656. }
  2657. private function normalizeArtStyleInput($value): string
  2658. {
  2659. $value = trim((string)$value);
  2660. if ($value === '') {
  2661. return '';
  2662. }
  2663. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2664. return mb_strtolower($value, 'UTF-8');
  2665. }
  2666. private function replaceArtStyleSection(string $content, string $artStyle): string
  2667. {
  2668. if ($content === '' || $artStyle === '') {
  2669. return $content;
  2670. }
  2671. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2672. if (!preg_match($pattern, $content)) {
  2673. return $content;
  2674. }
  2675. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2676. }
  2677. /**
  2678. * DeepSeek流式输出处理方法
  2679. *
  2680. * @param array $post_data DeepSeek API请求参数
  2681. * @return \Generator 返回生成器,用于流式输出
  2682. */
  2683. private function unwrapJsonWrappedContent($content) {
  2684. $trimmed = ltrim((string)$content);
  2685. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2686. return $content;
  2687. }
  2688. $decoded = json_decode($trimmed, true);
  2689. if (!is_array($decoded)) {
  2690. return $content;
  2691. }
  2692. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2693. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2694. return $decoded[$key];
  2695. }
  2696. }
  2697. return $content;
  2698. }
  2699. private function deepSeekStreamResponse($post_data) {
  2700. // 设置最大输出tokens
  2701. $post_data['max_tokens'] = 300000;
  2702. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2703. $post_data['stream_options'] = ['include_usage' => true];
  2704. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2705. $response = $client->post($this->url, [
  2706. 'json' => $post_data,
  2707. 'headers' => $this->headers,
  2708. 'stream' => true // 启用流式响应
  2709. ]);
  2710. $body = $response->getBody();
  2711. $fullContent = '';
  2712. $fullReasoningContent = '';
  2713. $usage = [];
  2714. $buffer = '';
  2715. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2716. // 逐行读取流式响应
  2717. while (!$body->eof()) {
  2718. $chunk = $body->read(1024); // 每次读取 1KB
  2719. $buffer .= $chunk;
  2720. // 按行分割
  2721. $lines = explode("\n", $buffer);
  2722. // 保留最后一个不完整的行
  2723. $buffer = array_pop($lines);
  2724. foreach ($lines as $line) {
  2725. $line = trim($line);
  2726. // 跳过空行
  2727. if (empty($line)) {
  2728. continue;
  2729. }
  2730. // 检查是否是 SSE 数据行
  2731. if (strpos($line, 'data: ') !== 0) {
  2732. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2733. continue;
  2734. }
  2735. $data = substr($line, 6); // 移除 "data: " 前缀
  2736. if ($data === '[DONE]') {
  2737. dLog('deepseek')->info('收到结束标记');
  2738. break 2; // 跳出两层循环
  2739. }
  2740. try {
  2741. $json = json_decode($data, true);
  2742. if (json_last_error() !== JSON_ERROR_NONE) {
  2743. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2744. continue;
  2745. }
  2746. if (isset($json['choices'][0]['delta'])) {
  2747. $delta = $json['choices'][0]['delta'];
  2748. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2749. if (isset($delta['reasoning_content'])) {
  2750. $fullReasoningContent .= $delta['reasoning_content'];
  2751. yield [
  2752. 'type' => 'reasoning',
  2753. 'content' => $delta['reasoning_content'],
  2754. 'full_reasoning' => $fullReasoningContent
  2755. ];
  2756. }
  2757. // 处理最终回答内容
  2758. if (isset($delta['content'])) {
  2759. $fullContent .= $delta['content'];
  2760. yield [
  2761. 'type' => 'content',
  2762. 'content' => $delta['content'],
  2763. ];
  2764. }
  2765. }
  2766. // 获取使用统计信息
  2767. if (isset($json['usage'])) {
  2768. $usage = $json['usage'];
  2769. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2770. }
  2771. } catch (\Exception $e) {
  2772. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2773. continue;
  2774. }
  2775. }
  2776. }
  2777. dLog('deepseek')->info('流式读取完成', [
  2778. 'content_length' => strlen($fullContent),
  2779. 'reasoning_length' => strlen($fullReasoningContent)
  2780. ]);
  2781. yield [
  2782. 'type' => 'done',
  2783. 'full_content' => $fullContent,
  2784. 'full_reasoning' => $fullReasoningContent,
  2785. 'usage' => $usage
  2786. ];
  2787. }
  2788. /**
  2789. * GPT 重试次数(env 可配置,默认 5 次)
  2790. */
  2791. private function gptRetryTimes()
  2792. {
  2793. return (int)env('GPT_RETRY_TIMES', 5);
  2794. }
  2795. /**
  2796. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2797. */
  2798. private function gptRetryInterval()
  2799. {
  2800. return (int)env('GPT_RETRY_INTERVAL', 10);
  2801. }
  2802. /**
  2803. * 判断 GPT 请求异常是否可重试
  2804. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2805. */
  2806. private function isGptRetryableException(\Exception $e)
  2807. {
  2808. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2809. return false;
  2810. }
  2811. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2812. $status = $e->getResponse()->getStatusCode();
  2813. return $status >= 500 || $status == 429;
  2814. }
  2815. return true;
  2816. }
  2817. /**
  2818. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2819. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2820. */
  2821. private function checkGptServiceAvailable($apiKey = null)
  2822. {
  2823. if ($apiKey === null) {
  2824. $apiKey = env('GPT_54_API_KEY');
  2825. }
  2826. if (empty($apiKey)) {
  2827. return false;
  2828. }
  2829. try {
  2830. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2831. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2832. 'headers' => [
  2833. 'Authorization' => 'Bearer ' . $apiKey,
  2834. 'Content-Type' => 'application/json'
  2835. ]
  2836. ]);
  2837. $status = $response->getStatusCode();
  2838. return $status < 500 && $status != 429;
  2839. } catch (\Exception $e) {
  2840. return false;
  2841. }
  2842. }
  2843. /**
  2844. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2845. * 全部失败抛出友好错误
  2846. */
  2847. private function ensureGptServiceAvailable($apiKey = null)
  2848. {
  2849. $maxRetries = $this->gptRetryTimes();
  2850. $interval = $this->gptRetryInterval();
  2851. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2852. if ($this->checkGptServiceAvailable($apiKey)) {
  2853. return;
  2854. }
  2855. if ($attempt < $maxRetries) {
  2856. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2857. 'retry' => $attempt + 1,
  2858. 'max_retries' => $maxRetries
  2859. ]);
  2860. sleep($interval);
  2861. }
  2862. }
  2863. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2864. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2865. 'max_retries' => $maxRetries,
  2866. 'interval' => $interval
  2867. ]);
  2868. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2869. }
  2870. /**
  2871. * GPT 流式输出处理方法
  2872. *
  2873. * @param array $post_data GPT API请求参数
  2874. * @return \Generator 返回生成器,用于流式输出
  2875. */
  2876. private function gpt54StreamResponse($post_data) {
  2877. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  2878. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  2879. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  2880. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  2881. $usedLunaFallback = false;
  2882. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  2883. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  2884. if (empty($apiKey)) {
  2885. Utils::throwError('20003:GPT API Key未配置');
  2886. }
  2887. // 先探活,服务不可用时自动重试
  2888. $this->ensureGptServiceAvailable($apiKey);
  2889. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  2890. // 移除 thinking 参数,GPT-5.4 不支持
  2891. if (isset($post_data['thinking'])) {
  2892. unset($post_data['thinking']);
  2893. }
  2894. if (isset($post_data['reasoning_effort'])) {
  2895. unset($post_data['reasoning_effort']);
  2896. }
  2897. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  2898. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  2899. $post_data['max_completion_tokens'] = 100000;
  2900. $post_data['max_tokens'] = 100000;
  2901. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2902. $post_data['stream_options'] = ['include_usage' => true];
  2903. $maxRetries = $this->gptRetryTimes();
  2904. $interval = $this->gptRetryInterval();
  2905. $attempt = 0;
  2906. while (true) {
  2907. $fullContent = '';
  2908. $usage = [];
  2909. $buffer = '';
  2910. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  2911. $isJsonRequest = isset($post_data['response_format'])
  2912. && is_array($post_data['response_format'])
  2913. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  2914. $suspectJsonWrap = false;
  2915. $pendingContent = '';
  2916. $requestStartedAt = microtime(true);
  2917. $headers = [
  2918. 'Authorization' => 'Bearer ' . $apiKey,
  2919. 'Content-Type' => 'application/json',
  2920. 'Accept' => 'text/event-stream'
  2921. ];
  2922. try {
  2923. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2924. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2925. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2926. 'json' => $post_data,
  2927. 'headers' => $headers,
  2928. 'stream' => true // 启用流式响应
  2929. ]);
  2930. $body = $response->getBody();
  2931. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2932. // 逐行读取流式响应
  2933. while (!$body->eof()) {
  2934. // 长时间没有任何内容返回时,切换备用 Key 重试
  2935. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  2936. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  2937. }
  2938. $chunk = $body->read(1024); // 每次读取 1KB
  2939. $buffer .= $chunk;
  2940. // 按行分割
  2941. $lines = explode("\n", $buffer);
  2942. // 保留最后一个不完整的行
  2943. $buffer = array_pop($lines);
  2944. foreach ($lines as $line) {
  2945. $line = trim($line);
  2946. // 跳过空行
  2947. if (empty($line)) {
  2948. continue;
  2949. }
  2950. // 检查是否是 SSE 数据行
  2951. if (strpos($line, 'data: ') !== 0) {
  2952. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2953. continue;
  2954. }
  2955. $data = substr($line, 6); // 移除 "data: " 前缀
  2956. if ($data === '[DONE]') {
  2957. dLog('deepseek')->info('收到结束标记');
  2958. break 2; // 跳出 foreach 和流读取循环
  2959. }
  2960. try {
  2961. $json = json_decode($data, true);
  2962. if (json_last_error() !== JSON_ERROR_NONE) {
  2963. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2964. continue;
  2965. }
  2966. if (isset($json['choices'][0]['delta'])) {
  2967. $delta = $json['choices'][0]['delta'];
  2968. // 处理回答内容
  2969. if (isset($delta['content'])) {
  2970. $fullContent .= $delta['content'];
  2971. $trimmed = ltrim($fullContent);
  2972. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2973. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2974. $suspectJsonWrap = true;
  2975. }
  2976. if (!$suspectJsonWrap) {
  2977. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2978. $chunkSize = 256;
  2979. $chunkLength = mb_strlen($delta['content']);
  2980. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2981. yield [
  2982. 'type' => 'content',
  2983. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2984. ];
  2985. }
  2986. } else {
  2987. $pendingContent .= $delta['content'];
  2988. }
  2989. }
  2990. }
  2991. // 获取使用统计信息
  2992. if (isset($json['usage'])) {
  2993. $usage = $json['usage'];
  2994. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2995. }
  2996. } catch (\Exception $e) {
  2997. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2998. continue;
  2999. }
  3000. }
  3001. }
  3002. dLog('deepseek')->info('流式读取完成', [
  3003. 'content_length' => strlen($fullContent)
  3004. ]);
  3005. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3006. if ($suspectJsonWrap) {
  3007. $decoded = json_decode(trim($fullContent), true);
  3008. $unwrapped = null;
  3009. if (is_array($decoded)) {
  3010. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3011. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3012. $unwrapped = $decoded[$key];
  3013. break;
  3014. }
  3015. }
  3016. }
  3017. if ($unwrapped !== null) {
  3018. $fullContent = $unwrapped;
  3019. $chunkSize = 256;
  3020. $contentLength = mb_strlen($fullContent);
  3021. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3022. yield [
  3023. 'type' => 'content',
  3024. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3025. ];
  3026. }
  3027. } elseif ($pendingContent !== '') {
  3028. // 误判:补发暂缓内容,避免内容丢失
  3029. yield [
  3030. 'type' => 'content',
  3031. 'content' => $pendingContent,
  3032. ];
  3033. }
  3034. }
  3035. yield [
  3036. 'type' => 'done',
  3037. 'full_content' => $fullContent,
  3038. 'full_reasoning' => '',
  3039. 'usage' => $usage
  3040. ];
  3041. return;
  3042. } catch (\Exception $e) {
  3043. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3044. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3045. $usedLunaFallback = true;
  3046. $apiKey = $lunaApiKey;
  3047. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3048. continue;
  3049. }
  3050. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3051. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3052. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3053. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3054. throw $e;
  3055. }
  3056. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3057. 'retry' => $attempt + 1,
  3058. 'max_retries' => $maxRetries,
  3059. 'error' => $e->getMessage()
  3060. ]);
  3061. sleep($interval);
  3062. $attempt++;
  3063. }
  3064. }
  3065. }
  3066. // 与推理模型对话
  3067. public function chatWithReasoner($data) {
  3068. $content = getProp($data, 'content');
  3069. $model = getProp($data, 'model', 'r1');
  3070. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3071. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3072. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3073. if ($model == 'r1') {
  3074. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3075. $thinkingMode = 'disabled';
  3076. } else {
  3077. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3078. $thinkingMode = 'disabled';
  3079. }
  3080. // 获取可选情感(根据音色可支持情感选)
  3081. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3082. $emotion_list = [];
  3083. foreach ($timbre_emotion as $emotion) {
  3084. $tmp = explode(',', $emotion);
  3085. $emotion_list = array_merge($emotion_list, $tmp);
  3086. }
  3087. $emotion_list = array_unique($emotion_list);
  3088. $emotion_str = implode('、', $emotion_list);
  3089. // // 获取可选情感
  3090. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3091. // $emotion_str = implode('、', $emotion_list);
  3092. // 是否启用情感
  3093. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3094. if ($enable_emotion) {
  3095. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3096. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3097. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3098. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3099. }else {
  3100. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3101. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3102. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3103. }
  3104. $messages = [
  3105. [
  3106. 'role' => 'system',
  3107. 'content' => $sys_content
  3108. ],
  3109. [
  3110. 'role' => 'user',
  3111. 'content' => $content
  3112. ]
  3113. ];
  3114. $post_data = [
  3115. 'model' => $model,
  3116. 'messages' => $messages,
  3117. // 'max_tokens' => 8192,
  3118. 'temperature' => 1,
  3119. 'frequency_penalty' => 0,
  3120. 'presence_penalty' => 0,
  3121. 'thinking' => ['type' => $thinkingMode],
  3122. 'response_format' => [
  3123. 'type' => 'text'
  3124. ],
  3125. 'stream' => false
  3126. ];
  3127. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3128. // 根据模型类型选择调用方法
  3129. $fullContent = '';
  3130. $usage = [];
  3131. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3132. // DeepSeek 官方模型使用 DeepSeek API
  3133. $chatResult = $this->chatOnly($post_data);
  3134. } else if (in_array($model, $this->gpt_text_models)) {
  3135. // GPT-5.4 模型使用 TokenRouter API
  3136. $chatResult = $this->gpt54ChatOnly($post_data);
  3137. } else {
  3138. // 其他模型使用火山引擎API
  3139. $chatResult = $this->volcEngineChatCompletion($post_data);
  3140. }
  3141. if (is_array($chatResult)) {
  3142. $fullContent = $chatResult['fullContent'];
  3143. $usage = $chatResult['usage'];
  3144. }
  3145. // 处理获取到的剧本数据
  3146. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3147. $result = [
  3148. 'origin_content' => $fullContent,
  3149. 'roles' => getProp($script_content, 'roles'),
  3150. 'words' => getProp($script_content, 'words'),
  3151. ];
  3152. // 仅记录 token 使用明细(不扣积分)
  3153. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3154. 'model' => $model,
  3155. 'source' => 'chatWithReasoner',
  3156. ], $model);
  3157. return $result;
  3158. }
  3159. public function resetParagraphAudio($data) {
  3160. $bid = getProp($data, 'bid');
  3161. $cid = getProp($data, 'cid');
  3162. $version_id = getProp($data, 'version_id');
  3163. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3164. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3165. 'generate_status' => '待制作',
  3166. 'updated_at' => date('Y-m-d H:i:s')
  3167. ]);
  3168. }
  3169. public function saveParagraphAudio($data) {
  3170. $bid = getProp($data, 'bid');
  3171. $cid = getProp($data, 'cid');
  3172. $version_id = getProp($data, 'version_id');
  3173. $sequence = getProp($data, 'sequence');
  3174. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3175. // 获取所有情感
  3176. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3177. $emotion_list = array_flip($emotion_list);
  3178. // 获取音色支持情感
  3179. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3180. $timbre_emotion = explode(',', $timbre_emotion);
  3181. $emotion = getProp($data, 'emotion');
  3182. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3183. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3184. $list = [
  3185. 'bid' => $bid,
  3186. 'cid' => $cid,
  3187. 'version_id' => $version_id,
  3188. 'sequence' => $sequence,
  3189. 'role' => getProp($data, 'role'),
  3190. 'gender' => getProp($data, 'gender'),
  3191. 'text' => trim(getProp($data, 'text')),
  3192. 'emotion' => $emotion,
  3193. 'emotion_type' => $emotion_type,
  3194. 'voice_type' => getProp($data, 'voice_type'),
  3195. 'voice_name' => getProp($data, 'voice_name'),
  3196. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3197. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3198. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3199. 'pitch' => getProp($data, 'pitch', 0),
  3200. // 'paragraph_audio_url' => '',
  3201. 'generate_status' => '制作中',
  3202. 'error_msg' => '',
  3203. 'updated_at' => date('Y-m-d H:i:s')
  3204. ];
  3205. $continue = false;
  3206. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3207. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3208. $list['generate_status'] = '制作成功';
  3209. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3210. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3211. $continue = true;
  3212. }
  3213. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3214. if ($id) {
  3215. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3216. }else {
  3217. $list['created_at'] = date('Y-m-d H:i:s');
  3218. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3219. $boolen = $id ? true : false;
  3220. }
  3221. // 如果更新成功则加入查询队列
  3222. if ($boolen) {
  3223. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3224. Redis::sadd($redis_key, $id);
  3225. }
  3226. if ($boolen && !$continue) {
  3227. $boolen = false;
  3228. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3229. // 根据ID通过API通知合成音频
  3230. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3231. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3232. $response = $result->getBody()->getContents();
  3233. $response_arr = json_decode($response, true);
  3234. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3235. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3236. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3237. Utils::throwError('20003:通知火山生成段落音频失败');
  3238. }
  3239. $boolen = true;
  3240. }
  3241. return $boolen;
  3242. }
  3243. public function insertAudioEffect($data) {
  3244. $audio_id = getProp($data, 'audio_id');
  3245. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3246. $bid = getProp($chapter_audio, 'bid');
  3247. $version_id = getProp($chapter_audio, 'version_id');
  3248. $cid = getProp($chapter_audio, 'cid');
  3249. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3250. $audio_effect_json = getProp($data, 'audio_effect_json');
  3251. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3252. try {
  3253. DB::beginTransaction();
  3254. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3255. if (!$count) {
  3256. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3257. }else {
  3258. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3259. }
  3260. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3261. 'audio_effect_status' => '添加中',
  3262. 'audio_effect_json' => $audio_effect_json,
  3263. 'updated_at' => date('Y-m-d H:i:s')
  3264. ]);
  3265. if (!$boolen1) {
  3266. DB::rollBack();
  3267. Utils::throwError('20003:更新生成数据失败');
  3268. }
  3269. $id = DB::table('mp_audio_tasks')->insertGetId([
  3270. 'audio_id' => $audio_id,
  3271. 'generate_status' => '执行中',
  3272. 'generate_json' => json_encode([], 256),
  3273. 'bid' => $bid,
  3274. 'book_name' => getProp($chapter_audio, 'book_name'),
  3275. 'version_id' => $version_id,
  3276. 'version_name' => getProp($chapter_audio, 'version_name'),
  3277. 'cid' => $cid,
  3278. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3279. 'task_name' => $task_name,
  3280. 'created_at' => date('Y-m-d H:i:s'),
  3281. 'updated_at' => date('Y-m-d H:i:s')
  3282. ]);
  3283. if (!$id) {
  3284. DB::rollBack();
  3285. Utils::throwError('20003:创建任务失败');
  3286. }
  3287. }catch (\Exception $e) {
  3288. DB::rollBack();
  3289. Utils::throwError('20003:'.$e->getMessage());
  3290. }
  3291. DB::commit();
  3292. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3293. // 根据ID通过API通知合成音频
  3294. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3295. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3296. $response = $result->getBody()->getContents();
  3297. $response_arr = json_decode($response, true);
  3298. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3299. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3300. Log::info('通知火山插入音效失败: '.$error_msg);
  3301. Utils::throwError('20003:通知火山插入音效失败');
  3302. }
  3303. return true;
  3304. }
  3305. public function insertBgm($data) {
  3306. $audio_id = getProp($data, 'audio_id');
  3307. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3308. $bid = getProp($chapter_audio, 'bid');
  3309. $version_id = getProp($chapter_audio, 'version_id');
  3310. $cid = getProp($chapter_audio, 'cid');
  3311. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3312. $bgm_json = getProp($data, 'bgm_json');
  3313. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3314. if (!$bgm_json) {
  3315. $bgm_json = getProp($data, 'audio_effect_json');
  3316. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3317. }
  3318. try {
  3319. DB::beginTransaction();
  3320. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3321. if (!$count) {
  3322. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3323. }else {
  3324. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3325. }
  3326. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3327. 'bgm_status' => '添加中',
  3328. 'bgm_json' => $bgm_json,
  3329. 'updated_at' => date('Y-m-d H:i:s')
  3330. ]);
  3331. if (!$boolen1) {
  3332. DB::rollBack();
  3333. Utils::throwError('20003:更新生成数据失败');
  3334. }
  3335. $id = DB::table('mp_audio_tasks')->insertGetId([
  3336. 'audio_id' => $audio_id,
  3337. 'generate_status' => '执行中',
  3338. 'generate_json' => json_encode([], 256),
  3339. 'bid' => $bid,
  3340. 'book_name' => getProp($chapter_audio, 'book_name'),
  3341. 'version_id' => $version_id,
  3342. 'version_name' => getProp($chapter_audio, 'version_name'),
  3343. 'cid' => $cid,
  3344. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3345. 'task_name' => $task_name,
  3346. 'created_at' => date('Y-m-d H:i:s'),
  3347. 'updated_at' => date('Y-m-d H:i:s')
  3348. ]);
  3349. if (!$id) {
  3350. DB::rollBack();
  3351. Utils::throwError('20003:创建任务失败');
  3352. }
  3353. }catch (\Exception $e) {
  3354. DB::rollBack();
  3355. Utils::throwError('20003:'.$e->getMessage());
  3356. }
  3357. DB::commit();
  3358. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3359. // 根据ID通过API通知合成音频
  3360. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3361. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3362. $response = $result->getBody()->getContents();
  3363. $response_arr = json_decode($response, true);
  3364. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3365. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3366. Log::info('通知火山插入bgm失败: '.$error_msg);
  3367. Utils::throwError('20003:通知火山插入bgm失败');
  3368. }
  3369. return true;
  3370. }
  3371. public function getParagraphAudios($data) {
  3372. $bid = getProp($data, 'bid');
  3373. $cid = getProp($data, 'cid');
  3374. $version_id = getProp($data, 'version_id');
  3375. $sequence = getProp($data, 'sequence');
  3376. // 获取已生成的音频
  3377. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3378. if ($sequence) $query->where('sequence', $sequence);
  3379. $paragraph_audios = $query->orderBy('sequence')->get();
  3380. $result = [];
  3381. foreach($paragraph_audios as $item) {
  3382. $result[] = [
  3383. 'sequence' => getProp($item, 'sequence'),
  3384. 'role' => getProp($item, 'role'),
  3385. 'gender' => getProp($item, 'gender'),
  3386. 'text' => trim(getProp($item, 'text')),
  3387. 'emotion' => getProp($item, 'emotion'),
  3388. 'emotion_type' => getProp($item, 'emotion_type'),
  3389. 'voice_type' => getProp($item, 'voice_type'),
  3390. 'voice_name' => getProp($item, 'voice_name'),
  3391. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3392. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3393. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3394. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3395. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3396. ];
  3397. }
  3398. return $result;
  3399. }
  3400. // 新增合成任务
  3401. public function addGenerateTask($data) {
  3402. $bid = getProp($data, 'bid');
  3403. $cid = getProp($data, 'cid');
  3404. $version_id = getProp($data, 'version_id');
  3405. $generate_json = getProp($data, 'generate_json');
  3406. // 获取已生成的音频
  3407. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3408. $paragraph_list = [];
  3409. foreach($paragraph_audios as $item) {
  3410. $paragraph_list[getProp($item, 'sequence')] = [
  3411. 'role' => getProp($item, 'role'),
  3412. 'gender' => getProp($item, 'gender'),
  3413. 'text' => trim(getProp($item, 'text')),
  3414. 'emotion' => getProp($item, 'emotion'),
  3415. 'emotion_type' => getProp($item, 'emotion_type'),
  3416. 'voice_type' => getProp($item, 'voice_type'),
  3417. 'voice_name' => getProp($item, 'voice_name'),
  3418. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3419. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3420. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3421. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3422. ];
  3423. }
  3424. // 更新角色-音色信息
  3425. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3426. $existed_role_info = json_decode($existed_role_info, true);
  3427. if (!$existed_role_info) $existed_role_info = [];
  3428. // 获取情感信息
  3429. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3430. $emotion_list = array_flip($emotion_list);
  3431. // 获取音色对应情感组
  3432. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3433. $timbre_emotion_list = [];
  3434. foreach($timbre_emotions as $item) {
  3435. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3436. }
  3437. // 构造生成音频的json
  3438. $words = json_decode($generate_json, true);
  3439. // 最终合成前的参数组
  3440. $mp_chapter_paragraph_audios = [];
  3441. $sequence = 1;
  3442. $complete_paragraph_sequences = [];
  3443. foreach($words as &$word) {
  3444. 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:参数格式有误');
  3445. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3446. $role = getProp($word, 'role');
  3447. $word['gender'] = (int)$word['gender'];
  3448. // 判断音色对应情感是否支持,不支持则调整为中性
  3449. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3450. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3451. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3452. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3453. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3454. }else {
  3455. $word['emotion'] = '中性';
  3456. $word['emotion_type'] = 'neutral';
  3457. }
  3458. $existed_role_info[$role] = [
  3459. 'timbre_type' => $word['voice_type'],
  3460. 'timbre_name' => $word['voice_name'],
  3461. 'emotion' => $word['emotion'],
  3462. 'emotion_type' => $word['emotion_type'],
  3463. 'speed_ratio' => $word['speed_ratio'],
  3464. 'loudness_ratio'=> $word['loudness_ratio'],
  3465. 'emotion_scale' => $word['emotion_scale'],
  3466. 'pitch' => $word['pitch']
  3467. ];
  3468. $word['paragraph_audio_url'] = '';
  3469. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3470. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3471. // 如果音频存在并且参数都未改变则使用已生成的音频
  3472. if (getProp($paragraph, 'paragraph_audio_url')) {
  3473. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3474. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3475. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3476. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3477. // {
  3478. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3479. // }
  3480. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3481. }
  3482. $tmp = $word;
  3483. // 组装章节分句音频数据
  3484. // $tmp['sequence'] = getProp($word, 'sequence');
  3485. // $tmp['text'] = getProp($word, 'text');
  3486. // $tmp['emotion'] = getProp($word, 'emotion');
  3487. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3488. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3489. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3490. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3491. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3492. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3493. $tmp['bid'] = $bid;
  3494. $tmp['version_id'] = $version_id;
  3495. $tmp['cid'] = $cid;
  3496. $tmp['sequence'] = $sequence;
  3497. $tmp['created_at'] = date('Y-m-d H:i:s');
  3498. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3499. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3500. $mp_chapter_paragraph_audios[] = $tmp;
  3501. $complete_paragraph_sequences[] = $sequence;
  3502. $sequence++;
  3503. }
  3504. $generate_json = json_encode($words, 256);
  3505. // 判断是否有未生成字幕的段落
  3506. $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();
  3507. if ($no_subtitle_sequences) {
  3508. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3509. }
  3510. try {
  3511. DB::beginTransaction();
  3512. $role_info = json_encode($existed_role_info, 256);
  3513. $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')]);
  3514. if (!$boolen) {
  3515. DB::rollBack();
  3516. Utils::throwError('20003:更新角色信息失败');
  3517. }
  3518. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3519. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3520. if (!$count) {
  3521. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3522. }else {
  3523. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3524. }
  3525. $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')]);
  3526. if (!$boolen1) {
  3527. DB::rollBack();
  3528. Utils::throwError('20003:更新生成数据失败');
  3529. }
  3530. $id = DB::table('mp_audio_tasks')->insertGetId([
  3531. 'audio_id' => getProp($chapter_audio, 'id'),
  3532. 'generate_status' => '执行中',
  3533. 'generate_json' => $generate_json,
  3534. 'bid' => $bid,
  3535. 'book_name' => getProp($chapter_audio, 'book_name'),
  3536. 'version_id' => $version_id,
  3537. 'version_name' => getProp($chapter_audio, 'version_name'),
  3538. 'cid' => $cid,
  3539. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3540. 'task_name' => $task_name,
  3541. 'created_at' => date('Y-m-d H:i:s'),
  3542. 'updated_at' => date('Y-m-d H:i:s')
  3543. ]);
  3544. if (!$id) {
  3545. DB::rollBack();
  3546. Utils::throwError('20003:创建任务失败');
  3547. }
  3548. // 删除不在段落序号范围内的其他数据
  3549. if ($complete_paragraph_sequences) {
  3550. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3551. }
  3552. // // 删除章节分句音频数据并重新插入
  3553. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3554. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3555. // if (!$boolen3) {
  3556. // DB::rollBack();
  3557. // Utils::throwError('20003:更新章节分句音频失败');
  3558. // }
  3559. } catch (\Exception $e) {
  3560. DB::rollBack();
  3561. Utils::throwError('20003:'.$e->getMessage());
  3562. }
  3563. DB::commit();
  3564. // 通知火山生成音频
  3565. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3566. // 根据ID通过API通知合成音频
  3567. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3568. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3569. $response = $result->getBody()->getContents();
  3570. $response_arr = json_decode($response, true);
  3571. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3572. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3573. Log::info('通知火山生成音频失败: '.$error_msg);
  3574. Utils::throwError('20003:通知火山生成音频失败');
  3575. }
  3576. return true;
  3577. }
  3578. public function timbreList($data) {
  3579. $gender = getProp($data, 'gender');
  3580. $timbre_name = getProp($data, 'voice_name');
  3581. $category_id = getProp($data, 'category_id');
  3582. $age_stage = getProp($data, 'age_stage');
  3583. $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');
  3584. if ($gender) {
  3585. $query->where('gender', $gender);
  3586. }
  3587. if ($timbre_name) {
  3588. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3589. }
  3590. if ($category_id) {
  3591. $query->where(function ($query) use ($category_id) {
  3592. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3593. });
  3594. }
  3595. if ($age_stage) {
  3596. $query->where('age_stage', $age_stage);
  3597. }
  3598. $list = $query->get()->map(function ($value) {
  3599. $value = (array)$value;
  3600. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3601. return $value;
  3602. })->toArray();
  3603. return $list;
  3604. }
  3605. // 生成火山临时token
  3606. public function setStsToken() {
  3607. // ************* 配置参数 *************
  3608. $method = 'GET';
  3609. $service = 'sts';
  3610. $host = 'open.volcengineapi.com';
  3611. $region = env('VOLC_REGION');
  3612. $endpoint = 'https://open.volcengineapi.com';
  3613. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3614. $access_key = env('VOLC_AK');
  3615. $secret_key = env('VOLC_SK');
  3616. // 获取缓存中的token,如果没有则请求接口
  3617. $token = Redis::get('volc_sts_token');
  3618. if (!$token) {
  3619. // 查询参数
  3620. $query_parameters = [
  3621. 'Action' => 'AssumeRole',
  3622. 'RoleSessionName' => 'user@zw',
  3623. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3624. 'Version' => '2018-01-01'
  3625. ];
  3626. // 生成URL编码的查询字符串
  3627. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3628. // 获取签名头信息
  3629. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3630. // 构建完整URL
  3631. $request_url = $endpoint . '?' . $request_parameters;
  3632. $client = new Client(['verify' => false]);
  3633. $response = $client->get($request_url, ['headers' => $headers]);
  3634. $response_arr = json_decode($response->getBody()->getContents(), true);
  3635. $result = [
  3636. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3637. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3638. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3639. 'Region' => env('VOLC_REGION'),
  3640. 'Endpoint' => env('VOLC_END_POINT'),
  3641. 'Bucket' => env('VOLC_BUCKET'),
  3642. ];
  3643. // 缓存token
  3644. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3645. return $result;
  3646. } else {
  3647. return json_decode($token, true);
  3648. }
  3649. // $response = $response['Response'];
  3650. // $access_key = $response['Credentials']['AccessKeyId'];
  3651. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3652. // $security_token = $response['Credentials']['SecurityToken'];
  3653. // $expiration = $response['Credentials']['Expiration'];
  3654. // dd($response_arr);
  3655. }
  3656. public function emotionGroups($data) {
  3657. $id = getProp($data, 'group_id');
  3658. $group_name = getProp($data, 'group_name');
  3659. $voice_type = getProp($data, 'voice_type');
  3660. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3661. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3662. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3663. if ($group_name) {
  3664. $query->where('group_name', 'like', "%{$group_name}%");
  3665. }
  3666. if ($id) {
  3667. $query->where('id', $id);
  3668. }
  3669. if ($voice_type) {
  3670. $query->where('voice_type', $voice_type);
  3671. }
  3672. return $query->orderBy('id')->get()->map(function ($value) {
  3673. return (array)$value;
  3674. })->toArray();
  3675. }
  3676. private function sign($key, $msg) {
  3677. return hash_hmac('sha256', $msg, $key, true);
  3678. }
  3679. // 生成签名密钥
  3680. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3681. $kDate = $this->sign($key, $dateStamp);
  3682. $kRegion = $this->sign($kDate, $regionName);
  3683. $kService = $this->sign($kRegion, $serviceName);
  3684. $kSigning = $this->sign($kService, 'request');
  3685. return $kSigning;
  3686. }
  3687. // 获取签名头信息
  3688. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3689. $contenttype = 'application/x-www-form-urlencoded';
  3690. $accept = 'application/json';
  3691. // 获取当前UTC时间
  3692. $t = new DateTime('now', new DateTimeZone('UTC'));
  3693. $xdate = $t->format('Ymd\THis\Z');
  3694. $datestamp = $t->format('Ymd');
  3695. // 1. 拼接规范请求串
  3696. $canonical_uri = '/';
  3697. $canonical_querystring = $request_parameters;
  3698. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3699. $signed_headers = 'content-type;host;x-date';
  3700. // 空请求体的SHA256哈希
  3701. $payload_hash = hash('sha256', '');
  3702. $canonical_request = implode("\n", [
  3703. $method,
  3704. $canonical_uri,
  3705. $canonical_querystring,
  3706. $canonical_headers,
  3707. $signed_headers,
  3708. $payload_hash
  3709. ]);
  3710. // 2. 拼接待签名字符串
  3711. $algorithm = 'HMAC-SHA256';
  3712. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3713. $hashed_canonical_request = hash('sha256', $canonical_request);
  3714. $string_to_sign = implode("\n", [
  3715. $algorithm,
  3716. $xdate,
  3717. $credential_scope,
  3718. $hashed_canonical_request
  3719. ]);
  3720. // 3. 计算签名
  3721. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3722. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3723. // 4. 添加签名到请求头
  3724. $authorization_header = sprintf(
  3725. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3726. $algorithm,
  3727. $access_key,
  3728. $credential_scope,
  3729. $signed_headers,
  3730. $signature
  3731. );
  3732. return [
  3733. 'Accept' => $accept,
  3734. 'Content-Type' => $contenttype,
  3735. 'X-Date' => $xdate,
  3736. 'Authorization' => $authorization_header
  3737. ];
  3738. }
  3739. // 文字合成语音(火山引擎)
  3740. public function tts($data) {
  3741. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3742. $headers = [
  3743. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3744. 'Content-Type' => 'application/json; charset=UTF-8'
  3745. ];
  3746. $post_data = [
  3747. 'app' => [
  3748. 'appid' => env('VOLC_APPID'),
  3749. 'token' => env('VOLC_TOKEN'),
  3750. 'cluster' => 'volcano_tts'
  3751. ],
  3752. 'user' => [
  3753. 'uid' => 'mp_audio'
  3754. ],
  3755. // 'audio' => [
  3756. // 'voice_type' =>
  3757. // ],
  3758. ];
  3759. }
  3760. public function scriptList($data) {
  3761. $uid = Site::getUid();
  3762. $script_id = getProp($data, 'script_id');
  3763. $script_name = getProp($data, 'script_name');
  3764. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3765. if ($script_id) {
  3766. $query->where('id', $script_id);
  3767. }
  3768. if ($script_name) {
  3769. $query->where('script_name', 'like', "%{$script_name}%");
  3770. }
  3771. return $query->orderBy('created_at', 'desc')->paginate(12);
  3772. }
  3773. public function scripts($data) {
  3774. $uid = Site::getUid();
  3775. $script_id = getProp($data, 'script_id');
  3776. $script_name = getProp($data, 'script_name');
  3777. $is_products = getProp($data, 'is_products');
  3778. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3779. if ($script_id) {
  3780. $query->where('id', $script_id);
  3781. }
  3782. if ($is_products !== '') {
  3783. $query->where('is_products', $is_products);
  3784. }
  3785. if ($script_name) {
  3786. $query->where('script_name', 'like', "%{$script_name}%");
  3787. }
  3788. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3789. return (array)$value;
  3790. })->toArray();
  3791. }
  3792. public function scriptInfo($data) {
  3793. $uid = Site::getUid();
  3794. $script_id = getProp($data, 'script_id');
  3795. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3796. // ->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();
  3797. ->selectRaw('id as script_id, script_name')->first();
  3798. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3799. $script = (array)$script;
  3800. // 获取分集组信息
  3801. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3802. ->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')
  3803. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3804. $value = (array)$value;
  3805. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3806. return (array)$value;
  3807. })->toArray();
  3808. $script['group'] = $groups;
  3809. return $script;
  3810. }
  3811. public function createScript($data) {
  3812. $script_name = getProp($data, 'script_name');
  3813. $uid = Site::getUid(); // 获取当前用户ID
  3814. $cpid = Site::getCpid(); // 获取当前公司组ID
  3815. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3816. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3817. $script_name .= '_'.date('YmdHis');
  3818. }
  3819. return DB::table('mp_scripts')->insertGetId([
  3820. 'script_name' => $script_name,
  3821. 'user_id' => $uid,
  3822. 'cpid' => $cpid,
  3823. 'created_at' => date('Y-m-d H:i:s'),
  3824. 'updated_at' => date('Y-m-d H:i:s')
  3825. ]);
  3826. }
  3827. public function editScript($data) {
  3828. $script_id = getProp($data, 'script_id');
  3829. $script_name = getProp($data, 'script_name');
  3830. $uid = Site::getUid(); // 获取当前用户ID
  3831. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3832. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3833. if ($id && (int)$id !== (int)$script_id) {
  3834. $script_name .= '_'.date('YmdHis');
  3835. }
  3836. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3837. 'script_name' => $script_name,
  3838. 'updated_at' => date('Y-m-d H:i:s')
  3839. ]);
  3840. }
  3841. public function delScript($data) {
  3842. $script_id = getProp($data, 'script_id');
  3843. $uid = Site::getUid(); // 获取当前用户ID
  3844. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3845. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3846. 'is_deleted' => 1,
  3847. 'updated_at' => date('Y-m-d H:i:s')
  3848. ]);
  3849. }
  3850. public function createEpisode($data) {
  3851. $script_id = getProp($data, 'script_id');
  3852. $group_name = getProp($data, 'group_name');
  3853. $remark = getProp($data, 'remark');
  3854. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3855. $uid = Site::getUid(); // 获取当前用户ID
  3856. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3857. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3858. $group_name .= '_'.date('YmdHis');
  3859. }
  3860. return DB::table('mp_script_episode_group')->insertGetId([
  3861. 'script_id' => $script_id,
  3862. 'group_name' => $group_name,
  3863. 'user_id' => $uid,
  3864. 'remark' => $remark,
  3865. 'created_at' => date('Y-m-d H:i:s'),
  3866. 'updated_at' => date('Y-m-d H:i:s')
  3867. ]);
  3868. }
  3869. public function editEpisode($data) {
  3870. $group_id = getProp($data, 'group_id');
  3871. $start_episode_number = getProp($data, 'start_episode_number');
  3872. $end_episode_number = getProp($data, 'end_episode_number');
  3873. $group_name = getProp($data, 'group_name');
  3874. $uid = Site::getUid(); // 获取当前用户ID
  3875. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3876. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3877. if ($id && (int)$id !== (int)$group_id) {
  3878. $group_name .= '_'.date('YmdHis');
  3879. }
  3880. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3881. 'group_name' => $group_name,
  3882. 'start_episode_number' => $start_episode_number,
  3883. 'end_episode_number' => $end_episode_number,
  3884. 'updated_at' => date('Y-m-d H:i:s')
  3885. ]);
  3886. }
  3887. public function delEpisode($data) {
  3888. $group_id = getProp($data, 'group_id');
  3889. $uid = Site::getUid(); // 获取当前用户ID
  3890. if (!$group_id) Utils::throwError('20003:请选择分集');
  3891. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3892. 'is_deleted' => 1,
  3893. 'updated_at' => date('Y-m-d H:i:s')
  3894. ]);
  3895. }
  3896. /**
  3897. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3898. *
  3899. * @param array $data 包含以下参数:
  3900. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3901. * - question: 用户问题(可选)
  3902. * - model: 使用的模型(r1 或 v3,默认 v3)
  3903. * @return \Generator 返回生成器,用于流式输出
  3904. */
  3905. public function generateEpisodes($data) {
  3906. $script_id = getProp($data, 'script_id');
  3907. $group_id = getProp($data, 'group_id');
  3908. // $file = getProp($data, 'file');
  3909. $file = '';
  3910. $content = getProp($data, 'content', '');
  3911. // $bid = getProp($data, 'bid', 0);
  3912. $bid = 0;
  3913. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3914. if (!$group) {
  3915. Utils::throwError('20003:剧本分集不存在');
  3916. }
  3917. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3918. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3919. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3920. $prompt = getProp($data, 'prompt');
  3921. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3922. $model = getProp($data, 'model');
  3923. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3924. Utils::throwError('20003:该模型不存在!');
  3925. }
  3926. // 检查是否存在重叠的剧集序号范围
  3927. $exists_groups = DB::table('mp_script_episode_group')
  3928. ->where('script_id', $script_id)
  3929. ->where('id', '<>', $group_id) // 排除当前组
  3930. ->where('is_deleted', 0)
  3931. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3932. // 检查新范围是否与现有范围重叠
  3933. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3934. // 新范围的开始在现有范围内
  3935. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3936. ->where('end_episode_number', '>=', $start_episode_sequence);
  3937. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3938. // 新范围的结束在现有范围内
  3939. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3940. ->where('end_episode_number', '>=', $end_episode_sequence);
  3941. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3942. // 新范围完全包含现有范围
  3943. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3944. ->where('end_episode_number', '<=', $end_episode_sequence);
  3945. });
  3946. })
  3947. ->select('start_episode_number', 'end_episode_number')
  3948. ->get();
  3949. if ($exists_groups->isNotEmpty()) {
  3950. $conflict_ranges = [];
  3951. foreach ($exists_groups as $group) {
  3952. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3953. }
  3954. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3955. }
  3956. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3957. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3958. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3959. if ($model === 'deepseek-chat') {
  3960. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3961. $model = 'deepseek-v4-flash';
  3962. $thinkingMode = 'disabled';
  3963. } elseif ($model === 'deepseek-reasoner') {
  3964. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3965. $model = 'deepseek-v4-flash';
  3966. $thinkingMode = 'enabled';
  3967. }
  3968. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3969. if (!$script) {
  3970. Utils::throwError('20003:剧本不存在');
  3971. }
  3972. $content = getProp($group, 'content');
  3973. if (!$file && !$content && !$bid) {
  3974. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3975. }
  3976. // 提取文件内容
  3977. if ($file) {
  3978. $content = $this->extractFileContent($file);
  3979. if (!$content) {
  3980. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3981. }
  3982. } elseif ($bid) {
  3983. $content = $this->getContentByBid($bid);
  3984. if (!$content) {
  3985. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3986. }
  3987. } elseif ($content) {
  3988. $content = filterContent($content);
  3989. } elseif ($prompt) {
  3990. $content = filterContent($prompt);
  3991. } else {
  3992. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3993. }
  3994. // 构建消息
  3995. $messages = [
  3996. $this->sys_message,
  3997. [
  3998. 'role' => 'user',
  3999. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4000. ]
  4001. ];
  4002. $post_data = [
  4003. 'model' => $model,
  4004. 'messages' => $messages,
  4005. // 'max_tokens' => 8192,
  4006. 'temperature' => 0.7,
  4007. 'frequency_penalty' => 0,
  4008. 'presence_penalty' => 0,
  4009. 'thinking' => ['type' => $thinkingMode],
  4010. 'response_format' => ['type' => 'text'],
  4011. 'stream' => true
  4012. ];
  4013. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4014. // 根据模型类型选择调用方法
  4015. $fullContent = '';
  4016. $fullReasoningContent = '';
  4017. $usage = [];
  4018. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4019. // DeepSeek 官方模型使用 DeepSeek API
  4020. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4021. } else if (in_array($model, $this->gpt_text_models)) {
  4022. // GPT-5.4 模型使用 TokenRouter API
  4023. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4024. } else if (in_array($model, $this->gemini_text_models)) {
  4025. // Gemini 模型使用 Gemini API
  4026. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4027. } else {
  4028. // 其他模型使用火山引擎API
  4029. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4030. }
  4031. // 处理流式输出
  4032. foreach ($streamGenerator as $chunk) {
  4033. if (isset($chunk['type'])) {
  4034. if ($chunk['type'] === 'done') {
  4035. // 最终结果
  4036. $fullContent = $chunk['full_content'];
  4037. $fullReasoningContent = $chunk['full_reasoning'];
  4038. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4039. } else {
  4040. // 逐块yield数据
  4041. yield $chunk;
  4042. }
  4043. }
  4044. }
  4045. dLog('deepseek')->info('完整内容: '.$fullContent);
  4046. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4047. // 处理完整内容并返回最终结果
  4048. $script_arr = [];
  4049. if ($fullContent) {
  4050. $script_arr = extractScriptContent($fullContent);
  4051. }
  4052. logDB('deepseek', 'info', '解析内容', $script_arr);
  4053. if (!$script_arr['episodes']) {
  4054. Utils::throwError('20003:未生成剧本相关信息');
  4055. // yield [
  4056. // 'type' => 'done',
  4057. // 'script' => $script_arr,
  4058. // 'msg' => '未生成剧本相关信息',
  4059. // 'answer' => $fullContent,
  4060. // 'reasoning' => $fullReasoningContent,
  4061. // 'usage' => $usage
  4062. // ];
  4063. // return ;
  4064. }
  4065. try {
  4066. DB::beginTransaction();
  4067. // // 返回前保存剧本内容
  4068. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4069. // 'content' => $content,
  4070. // 'updated_at' => date('Y-m-d H:i:s')
  4071. // ]);
  4072. // if (!$boolen) {
  4073. // Utils::throwError('20003:保存剧本内容失败');
  4074. // }
  4075. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4076. // 'start_episode_number' => $start_episode_sequence,
  4077. // 'end_episode_number' => $end_episode_sequence,
  4078. // 'updated_at' => date('Y-m-d H:i:s')
  4079. // ]);
  4080. // if (!$boolen1) {
  4081. // Utils::throwError('20003:保存分集失败');
  4082. // }
  4083. $episode_content = '';
  4084. $episodes = [];
  4085. foreach ($script_arr['episodes'] as $item) {
  4086. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4087. // $episodes[] = [
  4088. // 'script_id' => $script_id,
  4089. // 'episode_number' => $item['episode_number'],
  4090. // 'episode_name' => $item['episode_name'],
  4091. // 'episode_content' => $item['episode_content'],
  4092. // 'created_at' => date('Y-m-d H:i:s'),
  4093. // 'updated_at' => date('Y-m-d H:i:s'),
  4094. // ];
  4095. }
  4096. if ($episode_content) {
  4097. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4098. 'episode_content' => $episode_content,
  4099. 'updated_at' => date('Y-m-d H:i:s')
  4100. ]);
  4101. if (!$boolen2) {
  4102. Utils::throwError('20003:保存分集内容失败');
  4103. }
  4104. }else {
  4105. Utils::throwError('20003:分集剧本解析失败');
  4106. }
  4107. }catch (\Exception $e) {
  4108. DB::rollBack();
  4109. Utils::throwError('20003:'.$e->getMessage());
  4110. }
  4111. DB::commit();
  4112. // 仅记录 token 使用明细(不扣积分)
  4113. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4114. 'model' => $model,
  4115. 'script_id' => $script_id,
  4116. 'group_id' => $group_id,
  4117. 'source' => 'generateEpisodes',
  4118. ], $model);
  4119. yield [
  4120. 'type' => 'done',
  4121. 'script' => $script_arr,
  4122. 'episode_content' => $episode_content,
  4123. 'answer' => $fullContent,
  4124. 'reasoning' => $fullReasoningContent,
  4125. 'usage' => $usage
  4126. ];
  4127. }
  4128. public function chatWithFileStream($data) {
  4129. $script_id = getProp($data, 'script_id');
  4130. $group_id = getProp($data, 'group_id');
  4131. $file = getProp($data, 'file');
  4132. $content = getProp($data, 'content', '');
  4133. $bid = getProp($data, 'bid', 0);
  4134. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4135. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4136. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4137. $prompt = getProp($data, 'prompt');
  4138. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4139. if (!empty($prompt)) {
  4140. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4141. }
  4142. $question = getProp($data, 'question', $baseQuestion);
  4143. $model = getProp($data, 'model');
  4144. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4145. Utils::throwError('20003:该模型不存在!');
  4146. }
  4147. // 检查是否存在重叠的剧集序号范围
  4148. $exists_groups = DB::table('mp_script_episode_group')
  4149. ->where('script_id', $script_id)
  4150. ->where('id', '<>', $group_id)
  4151. ->where('is_deleted', 0)
  4152. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4153. // 检查新范围是否与现有范围重叠
  4154. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4155. // 新范围的开始在现有范围内
  4156. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4157. ->where('end_episode_number', '>=', $start_episode_sequence);
  4158. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4159. // 新范围的结束在现有范围内
  4160. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4161. ->where('end_episode_number', '>=', $end_episode_sequence);
  4162. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4163. // 新范围完全包含现有范围
  4164. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4165. ->where('end_episode_number', '<=', $end_episode_sequence);
  4166. });
  4167. })
  4168. ->select('start_episode_number', 'end_episode_number')
  4169. ->get();
  4170. if ($exists_groups->isNotEmpty()) {
  4171. $conflict_ranges = [];
  4172. foreach ($exists_groups as $group) {
  4173. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4174. }
  4175. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4176. }
  4177. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4178. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4179. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4180. if ($model === 'deepseek-chat') {
  4181. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4182. $model = 'deepseek-v4-flash';
  4183. $thinkingMode = 'disabled';
  4184. } elseif ($model === 'deepseek-reasoner') {
  4185. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4186. $model = 'deepseek-v4-flash';
  4187. $thinkingMode = 'enabled';
  4188. }
  4189. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4190. if (!$script) {
  4191. Utils::throwError('20003:剧本不存在');
  4192. }
  4193. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4194. if (!$group) {
  4195. Utils::throwError('20003:剧本分集不存在');
  4196. }
  4197. if (!$file && !$content && !$bid) {
  4198. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4199. }
  4200. // 提取文件内容
  4201. if ($file) {
  4202. $content = $this->extractFileContent($file);
  4203. if (!$content) {
  4204. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4205. }
  4206. } elseif ($bid) {
  4207. $content = $this->getContentByBid($bid);
  4208. if (!$content) {
  4209. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4210. }
  4211. } elseif ($content) {
  4212. $content = filterContent($content);
  4213. } elseif ($prompt) {
  4214. $content = filterContent($prompt);
  4215. } else {
  4216. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4217. }
  4218. // 构建消息
  4219. $messages = [
  4220. [
  4221. 'role' => 'system',
  4222. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4223. 强制要求:\n
  4224. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4225. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4226. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4227. 普通要求:\n
  4228. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4229. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4230. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4231. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4232. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4233. 示例如下:\n
  4234. ###剧本名:西昆仑
  4235. ###故事梗概
  4236. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4237. ###剧本亮点
  4238. 亮点1:绝境奇药,生死一线
  4239. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4240. 亮点2:结拜兄妹,化解尴尬
  4241. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4242. 亮点3:纤发夺命,情愫暗涌
  4243. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4244. ###人物关系
  4245. 阿雪与梁萧之间存在兄妹之情。
  4246. ###核心矛盾
  4247. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4248. ###主体列表
  4249. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4250. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4251. 阴阳球:天地异宝,能化生精气,救人于危难。
  4252. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4253. ###美术风格
  4254. 基础画风风格词:厚涂古风
  4255. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4256. ###场景列表
  4257. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4258. [
  4259. 'role' => 'user',
  4260. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4261. ]
  4262. ];
  4263. $post_data = [
  4264. 'model' => $model,
  4265. 'messages' => $messages,
  4266. // 'max_tokens' => 8192,
  4267. 'temperature' => 0.7,
  4268. 'frequency_penalty' => 0,
  4269. 'presence_penalty' => 0,
  4270. 'thinking' => ['type' => $thinkingMode],
  4271. 'response_format' => ['type' => 'text'],
  4272. 'stream' => true
  4273. ];
  4274. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4275. // 根据模型类型选择调用方法
  4276. $fullContent = '';
  4277. $fullReasoningContent = '';
  4278. $usage = [];
  4279. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4280. // DeepSeek 官方模型使用 DeepSeek API
  4281. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4282. } else if (in_array($model, $this->gpt_text_models)) {
  4283. // GPT-5.4 模型使用 TokenRouter API
  4284. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4285. } else if (in_array($model, $this->gemini_text_models)) {
  4286. // Gemini 模型使用 Gemini API
  4287. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4288. } else {
  4289. // 其他模型使用火山引擎API
  4290. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4291. }
  4292. // 处理流式输出
  4293. foreach ($streamGenerator as $chunk) {
  4294. if (isset($chunk['type'])) {
  4295. if ($chunk['type'] === 'done') {
  4296. // 最终结果
  4297. $fullContent = $chunk['full_content'];
  4298. $fullReasoningContent = $chunk['full_reasoning'];
  4299. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4300. } else {
  4301. // 逐块yield数据
  4302. yield $chunk;
  4303. }
  4304. }
  4305. }
  4306. dLog('deepseek')->info('完整内容: '.$fullContent);
  4307. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4308. // 处理完整内容并返回最终结果
  4309. $script_arr = [];
  4310. if ($fullContent) {
  4311. $script_arr = extractScriptContent($fullContent);
  4312. }
  4313. logDB('deepseek', 'info', '解析内容', $script_arr);
  4314. if (!$script_arr['roles']) {
  4315. Utils::throwError('20003:未生成剧本相关信息');
  4316. // yield [
  4317. // 'type' => 'done',
  4318. // 'script' => $script_arr,
  4319. // 'msg' => '未生成剧本相关信息',
  4320. // 'answer' => $fullContent,
  4321. // 'reasoning' => $fullReasoningContent,
  4322. // 'usage' => $usage
  4323. // ];
  4324. }
  4325. try {
  4326. DB::beginTransaction();
  4327. // // 返回前保存剧本内容
  4328. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4329. // 'content' => $content,
  4330. // 'status' => '解析完成',
  4331. // 'updated_at' => date('Y-m-d H:i:s')
  4332. // ]);
  4333. // if (!$boolen) {
  4334. // Utils::throwError('20003:保存剧本内容失败');
  4335. // }
  4336. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4337. 'start_episode_number' => $start_episode_sequence,
  4338. 'end_episode_number' => $end_episode_sequence,
  4339. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4340. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4341. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4342. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4343. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4344. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4345. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4346. 'status' => '解析完成',
  4347. 'content' => $content,
  4348. 'updated_at' => date('Y-m-d H:i:s')
  4349. ]);
  4350. if (!$boolen1) {
  4351. Utils::throwError('20003:保存分集失败');
  4352. }
  4353. // $episodes = [];
  4354. // foreach ($script_arr['episodes'] as $item) {
  4355. // $episodes[] = [
  4356. // 'script_id' => $script_id,
  4357. // 'episode_number' => $item['episode_number'],
  4358. // 'episode_name' => $item['episode_name'],
  4359. // 'episode_content' => $item['episode_content'],
  4360. // 'created_at' => date('Y-m-d H:i:s'),
  4361. // 'updated_at' => date('Y-m-d H:i:s'),
  4362. // ];
  4363. // }
  4364. // if ($episodes) {
  4365. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4366. // if (!$boolen2) {
  4367. // Utils::throwError('20003:保存分集内容失败');
  4368. // }
  4369. // }else {
  4370. // Utils::throwError('20003:分集剧本解析失败');
  4371. // }
  4372. }catch (\Exception $e) {
  4373. DB::rollBack();
  4374. Utils::throwError('20003:'.$e->getMessage());
  4375. }
  4376. DB::commit();
  4377. // 仅记录 token 使用明细(不扣积分)
  4378. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4379. 'model' => $model,
  4380. 'script_id' => $script_id,
  4381. 'group_id' => $group_id,
  4382. 'source' => 'chatWithFileStream',
  4383. ], $model);
  4384. yield [
  4385. 'type' => 'done',
  4386. 'script' => $script_arr,
  4387. 'answer' => $fullContent,
  4388. 'reasoning' => $fullReasoningContent,
  4389. 'usage' => $usage
  4390. ];
  4391. }
  4392. /**
  4393. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4394. *
  4395. * @param array $data 包含以下参数:
  4396. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4397. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4398. * - model: 使用的模型(r1 或 v3,默认 v3)
  4399. * @return array
  4400. */
  4401. public function chatWithFile($data) {
  4402. $script_id = getProp($data, 'script_id');
  4403. $file = getProp($data, 'file');
  4404. $content = getProp($data, 'content', '');
  4405. $bid = getProp($data, 'bid', 0);
  4406. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4407. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4408. $prompt = getProp($data, 'prompt');
  4409. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4410. if (!empty($prompt)) {
  4411. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4412. }
  4413. $question = getProp($data, 'question', $baseQuestion);
  4414. // 处理文本模型
  4415. $model = getProp($data, 'model');
  4416. if (!$model) {
  4417. // 用户没有输入,使用默认值
  4418. $model = 'doubao-seed-2-0-mini-260215';
  4419. }
  4420. // 验证模型是否在可用模型表中
  4421. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4422. $model = 'doubao-seed-2-0-mini-260215';
  4423. }
  4424. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4425. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4426. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4427. if ($model === 'deepseek-chat') {
  4428. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4429. $model = 'deepseek-v4-flash';
  4430. $thinkingMode = 'disabled';
  4431. } elseif ($model === 'deepseek-reasoner') {
  4432. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4433. $model = 'deepseek-v4-flash';
  4434. $thinkingMode = 'enabled';
  4435. }
  4436. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4437. if (!$script) {
  4438. Utils::throwError('20003:剧本不存在');
  4439. }
  4440. if (!$file && !$content && !$bid) {
  4441. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4442. }
  4443. // 提取文件内容
  4444. if ($file) {
  4445. $content = $this->extractFileContent($file);
  4446. if (!$content) {
  4447. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4448. }
  4449. } elseif ($bid) {
  4450. $content = $this->getContentByBid($bid);
  4451. if (!$content) {
  4452. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4453. }
  4454. } elseif ($content) {
  4455. $content = filterContent($content);
  4456. } elseif ($prompt) {
  4457. $content = filterContent($prompt);
  4458. } else {
  4459. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4460. }
  4461. // 构建消息
  4462. $messages = [
  4463. $this->sys_message,
  4464. [
  4465. 'role' => 'user',
  4466. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4467. ]
  4468. ];
  4469. $post_data = [
  4470. 'model' => $model,
  4471. 'messages' => $messages,
  4472. // 'max_tokens' => 8192,
  4473. 'temperature' => 0.7,
  4474. 'frequency_penalty' => 0,
  4475. 'presence_penalty' => 0,
  4476. 'thinking' => ['type' => $thinkingMode],
  4477. 'response_format' => ['type' => 'text'],
  4478. 'stream' => false
  4479. ];
  4480. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4481. // 根据模型类型选择调用方法
  4482. $fullContent = '';
  4483. $usage = [];
  4484. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4485. // DeepSeek 官方模型使用 DeepSeek API
  4486. $chatResult = $this->chatOnly($post_data);
  4487. } else if (in_array($model, $this->gpt_text_models)) {
  4488. // GPT-5.4 模型使用 TokenRouter API
  4489. $chatResult = $this->gpt54ChatOnly($post_data);
  4490. } else {
  4491. // 其他模型使用火山引擎API
  4492. $chatResult = $this->volcEngineChatCompletion($post_data);
  4493. }
  4494. if (is_array($chatResult)) {
  4495. $fullContent = $chatResult['fullContent'];
  4496. $usage = $chatResult['usage'];
  4497. }
  4498. $script_arr = [];
  4499. // 处理结果
  4500. if ($fullContent) {
  4501. $script_arr = extractScriptContent($fullContent);
  4502. }
  4503. // 返回前保存剧本内容
  4504. DB::table('mp_scripts')->where('id', $script_id)->update([
  4505. 'content' => $content,
  4506. 'updated_at' => date('Y-m-d H:i:s')
  4507. ]);
  4508. // 仅记录 token 使用明细(不扣积分)
  4509. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4510. 'model' => $model,
  4511. 'script_id' => $script_id,
  4512. 'source' => 'chatWithFile',
  4513. ], $model);
  4514. return [
  4515. 'script' => $script_arr,
  4516. 'answer' => $fullContent,
  4517. 'usage' => $usage
  4518. ];
  4519. }
  4520. public function getEpisodeContent($data) {
  4521. $group_id = getProp($data, 'group_id');
  4522. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4523. }
  4524. public function saveEpisodeContent($data) {
  4525. $script_id = getProp($data, 'script_id');
  4526. $group_id = getProp($data, 'group_id');
  4527. $start_episode_sequence = getProp($data, 'start_episode_number');
  4528. $end_episode_sequence = getProp($data, 'end_episode_number');
  4529. // 检查是否存在重叠的剧集序号范围
  4530. $exists_groups = DB::table('mp_script_episode_group')
  4531. ->where('script_id', $script_id)
  4532. ->where('id', '<>', $group_id) // 排除当前组
  4533. ->where('is_deleted', 0)
  4534. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4535. // 检查新范围是否与现有范围重叠
  4536. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4537. // 新范围的开始在现有范围内
  4538. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4539. ->where('end_episode_number', '>=', $start_episode_sequence);
  4540. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4541. // 新范围的结束在现有范围内
  4542. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4543. ->where('end_episode_number', '>=', $end_episode_sequence);
  4544. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4545. // 新范围完全包含现有范围
  4546. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4547. ->where('end_episode_number', '<=', $end_episode_sequence);
  4548. });
  4549. })
  4550. ->select('start_episode_number', 'end_episode_number')
  4551. ->get();
  4552. if ($exists_groups->isNotEmpty()) {
  4553. $conflict_ranges = [];
  4554. foreach ($exists_groups as $group) {
  4555. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4556. }
  4557. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4558. }
  4559. $episode_content = getProp($data, 'episode_content');
  4560. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4561. 'content' => $episode_content,
  4562. 'start_episode_number' => $start_episode_sequence,
  4563. 'end_episode_number' => $end_episode_sequence,
  4564. 'updated_at' => date('Y-m-d H:i:s')
  4565. ]);
  4566. $script_arr =getProp($data, 'script', []);
  4567. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4568. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4569. $script_id = getProp($data, 'script_id');
  4570. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4571. try {
  4572. DB::beginTransaction();
  4573. $update_data = [
  4574. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4575. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4576. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4577. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4578. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4579. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4580. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4581. 'status' => 3,
  4582. 'start_episode_sequence' => $start_episode_sequence,
  4583. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4584. 'episode_num' => count($script_arr['episodes']),
  4585. 'updated_at' => date('Y-m-d H:i:s')
  4586. ];
  4587. // 保存剧本内容
  4588. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4589. if (!$boolen) {
  4590. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4591. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4592. Utils::throwError('20003:剧本内容保存失败');
  4593. }
  4594. // 保存分集内容
  4595. // 删除历史分集内容
  4596. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4597. $episodes = [];
  4598. $sequence = 1;
  4599. foreach ($script_arr['episodes'] as $episode) {
  4600. $segment_number = 1;
  4601. foreach($episode['segments'] as $segment) {
  4602. $episodes[] = [
  4603. 'script_id' => $script_id,
  4604. 'episode_number' => $episode['episode_number'],
  4605. 'title' => $episode['title'],
  4606. // 'content' => $episode['content'],
  4607. 'content' => '',
  4608. 'segment_number' => $segment_number,
  4609. 'segment_content' => $segment['segment_content'],
  4610. 'sequence' => $sequence,
  4611. 'created_at' => date('Y-m-d H:i:s'),
  4612. 'updated_at' => date('Y-m-d H:i:s')
  4613. ];
  4614. $sequence++;
  4615. $segment_number++;
  4616. }
  4617. }
  4618. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4619. if (!$boolen2) {
  4620. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4621. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4622. Utils::throwError('20003:分集内容保存失败');
  4623. }
  4624. } catch (\Exception $e) {
  4625. DB::rollBack();
  4626. Utils::throwError('20003:'.$e->getMessage());
  4627. }
  4628. DB::commit();
  4629. return true;
  4630. }
  4631. public function getBookContent($data) {
  4632. $bid = getProp($data, 'bid');
  4633. $start_sequence = getProp($data, 'start_sequence');
  4634. $end_sequence = getProp($data, 'end_sequence');
  4635. $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])
  4636. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4637. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4638. return $return_content;
  4639. }
  4640. public function exportScript($data) {
  4641. $filename = getProp($data, 'filename');
  4642. $script_id = getProp($data, 'script_id');
  4643. $group_id = getProp($data, 'group_id');
  4644. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4645. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4646. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4647. $script = (array)$script;
  4648. // 获取分集组信息
  4649. if ($group_id) {
  4650. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4651. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4652. ->get()->map(function($value) {
  4653. return (array)$value;
  4654. })->toArray();
  4655. }else {
  4656. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4657. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4658. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4659. return (array)$value;
  4660. })->toArray();
  4661. }
  4662. if (!$groups) Utils::throwError('20003:分集不存在');
  4663. $script['group'] = $groups;
  4664. $export_type = getProp($data, 'export_type', 'txt');
  4665. // 生成文件名
  4666. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4667. // 根据导出类型生成不同格式的文件
  4668. switch ($export_type) {
  4669. case 'txt':
  4670. return $this->exportScriptAsTxt($script, $filename);
  4671. case 'pdf':
  4672. return $this->exportScriptAsPdf($script, $filename);
  4673. default:
  4674. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4675. }
  4676. }
  4677. /**
  4678. * 导出剧本为TXT格式
  4679. */
  4680. private function exportScriptAsTxt($script, $filename) {
  4681. // 构建TXT内容
  4682. $content = $this->buildScriptContent($script);
  4683. // 设置响应头,直接下载
  4684. header('Content-Type: text/plain; charset=utf-8');
  4685. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4686. header('Content-Length: ' . strlen($content));
  4687. // 输出内容并结束
  4688. echo $content;
  4689. exit();
  4690. }
  4691. /**
  4692. * 导出剧本为PDF格式
  4693. */
  4694. private function exportScriptAsPdf($script, $filename) {
  4695. // 使用HTML转PDF的方式来更好地支持中文
  4696. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4697. // 创建PDF实例
  4698. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4699. // 设置文档信息
  4700. $pdf->SetCreator('剧本导出系统');
  4701. $pdf->SetAuthor('系统');
  4702. $pdf->SetTitle($script['script_name']);
  4703. $pdf->SetSubject('剧本导出');
  4704. // 设置边距
  4705. $pdf->SetMargins(15, 15, 15);
  4706. $pdf->SetAutoPageBreak(TRUE, 15);
  4707. // 添加页面
  4708. $pdf->AddPage();
  4709. // 注册并使用 simsun.ttf 字体
  4710. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4711. // 使用HTML内容生成PDF
  4712. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4713. // 直接输出PDF文件供下载
  4714. header('Content-Type: application/pdf');
  4715. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4716. // 直接输出PDF内容
  4717. $pdf->Output($filename . '.pdf', 'D');
  4718. exit();
  4719. }
  4720. /**
  4721. * 构建用于PDF的HTML内容
  4722. */
  4723. private function buildScriptHtmlForPdf($script) {
  4724. $html = '<style>
  4725. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4726. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4727. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4728. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4729. .info { margin-bottom: 8px; }
  4730. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4731. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4732. .segment { margin-bottom: 10px; margin-left: 20px; }
  4733. .episode-content { white-space: pre-wrap; }
  4734. </style>';
  4735. // 标题
  4736. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4737. // 处理分组数据
  4738. if (!empty($script['group']) && is_array($script['group'])) {
  4739. $groups = (array)$script['group'];
  4740. foreach ($groups as $group) {
  4741. $html .= '<div class="group">';
  4742. // 分组标题
  4743. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4744. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4745. // 故事梗概
  4746. if (!empty($group['intro'])) {
  4747. $html .= '<h3>故事梗概</h3>';
  4748. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4749. }
  4750. // 剧本亮点
  4751. if (!empty($group['highlights'])) {
  4752. $html .= '<h3>剧本亮点</h3>';
  4753. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4754. }
  4755. // 人物关系
  4756. if (!empty($group['role_relationship'])) {
  4757. $html .= '<h3>人物关系</h3>';
  4758. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4759. }
  4760. // 核心矛盾
  4761. if (!empty($group['core_contradiction'])) {
  4762. $html .= '<h3>核心矛盾</h3>';
  4763. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4764. }
  4765. // 主体列表
  4766. if (!empty($group['roles']) && is_array($group['roles'])) {
  4767. $html .= '<h3>主体列表</h3>';
  4768. $html .= '<ul>';
  4769. foreach ($group['roles'] as $role) {
  4770. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4771. }
  4772. $html .= '</ul>';
  4773. }
  4774. // 美术风格
  4775. if (!empty($group['art_style'])) {
  4776. $html .= '<h3>美术风格</h3>';
  4777. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4778. }
  4779. // 场景列表
  4780. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4781. $html .= '<h3>场景列表</h3>';
  4782. $html .= '<ul>';
  4783. foreach ($group['scenes'] as $scene) {
  4784. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4785. }
  4786. $html .= '</ul>';
  4787. }
  4788. // 分集剧本
  4789. if (!empty($group['episode_content'])) {
  4790. $html .= '<h3>分集剧本</h3>';
  4791. // 去除零宽字符和其他不可见字符
  4792. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4793. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4794. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4795. }
  4796. $html .= '</div>';
  4797. }
  4798. }
  4799. return $html;
  4800. }
  4801. /**
  4802. * 构建PDF内容
  4803. */
  4804. private function buildPdfContent($pdf, $script) {
  4805. // 标题
  4806. $pdf->SetFont('dejavusans', 'B', 18);
  4807. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4808. $pdf->Ln(5);
  4809. // 基本信息
  4810. $pdf->SetFont('dejavusans', '', 12);
  4811. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4812. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4813. $pdf->Ln(5);
  4814. // 剧本简介
  4815. if (!empty($script['intro'])) {
  4816. $pdf->SetFont('dejavusans', 'B', 14);
  4817. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4818. $pdf->SetFont('dejavusans', '', 12);
  4819. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4820. $pdf->Ln(3);
  4821. }
  4822. // 亮点
  4823. if (!empty($script['highlights'])) {
  4824. $pdf->SetFont('dejavusans', 'B', 14);
  4825. $pdf->Cell(0, 10, '亮点', 0, 1);
  4826. $pdf->SetFont('dejavusans', '', 12);
  4827. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4828. $pdf->Ln(3);
  4829. }
  4830. // 核心矛盾
  4831. if (!empty($script['core_contradiction'])) {
  4832. $pdf->SetFont('dejavusans', 'B', 14);
  4833. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4834. $pdf->SetFont('dejavusans', '', 12);
  4835. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4836. $pdf->Ln(3);
  4837. }
  4838. // 艺术风格
  4839. if (!empty($script['art_style'])) {
  4840. $pdf->SetFont('dejavusans', 'B', 14);
  4841. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4842. $pdf->SetFont('dejavusans', '', 12);
  4843. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4844. $pdf->Ln(3);
  4845. }
  4846. // 备注
  4847. if (!empty($script['remark'])) {
  4848. $pdf->SetFont('dejavusans', 'B', 14);
  4849. $pdf->Cell(0, 10, '备注', 0, 1);
  4850. $pdf->SetFont('dejavusans', '', 12);
  4851. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4852. $pdf->Ln(3);
  4853. }
  4854. // 角色列表
  4855. if (!empty($script['roles']) && is_array($script['roles'])) {
  4856. $pdf->SetFont('dejavusans', 'B', 14);
  4857. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4858. $pdf->SetFont('dejavusans', '', 12);
  4859. foreach ($script['roles'] as $index => $role) {
  4860. if (is_array($role) || is_object($role)) {
  4861. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4862. } else {
  4863. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4864. }
  4865. }
  4866. $pdf->Ln(3);
  4867. }
  4868. // 角色关系
  4869. if (!empty($script['role_relationship'])) {
  4870. $pdf->SetFont('dejavusans', 'B', 14);
  4871. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4872. $pdf->SetFont('dejavusans', '', 12);
  4873. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4874. $pdf->Ln(3);
  4875. }
  4876. // 场景列表
  4877. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4878. $pdf->SetFont('dejavusans', 'B', 14);
  4879. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4880. $pdf->SetFont('dejavusans', '', 12);
  4881. foreach ($script['scenes'] as $index => $scene) {
  4882. if (is_array($scene) || is_object($scene)) {
  4883. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4884. } else {
  4885. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4886. }
  4887. }
  4888. $pdf->Ln(5);
  4889. }
  4890. // 分集内容
  4891. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4892. $pdf->SetFont('dejavusans', 'B', 16);
  4893. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4894. $pdf->Ln(3);
  4895. foreach ($script['episodes'] as $episode) {
  4896. // 检查是否需要新页面
  4897. if ($pdf->GetY() > 250) {
  4898. $pdf->AddPage();
  4899. }
  4900. $pdf->SetFont('dejavusans', 'B', 14);
  4901. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4902. if (!empty($episode['title'])) {
  4903. $episodeTitle .= ':' . $episode['title'];
  4904. }
  4905. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4906. // 处理分段内容
  4907. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4908. $pdf->SetFont('dejavusans', '', 12);
  4909. foreach ($episode['segments'] as $segment) {
  4910. if (!empty($segment['segment_content'])) {
  4911. // 如果有分段编号,显示分段标题
  4912. if (!empty($segment['segment_number'])) {
  4913. $pdf->SetFont('dejavusans', 'B', 12);
  4914. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4915. $pdf->SetFont('dejavusans', '', 12);
  4916. }
  4917. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4918. $pdf->Ln(2);
  4919. }
  4920. }
  4921. }
  4922. $pdf->Ln(5);
  4923. }
  4924. }
  4925. }
  4926. /**
  4927. * 构建剧本文本内容
  4928. */
  4929. private function buildScriptContent($script) {
  4930. $content = '';
  4931. $groups = $script['group'];
  4932. $groups = (array)$groups;
  4933. foreach ($groups as $group) {
  4934. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4935. // 剧本基本信息
  4936. if (!empty($group['intro'])) {
  4937. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4938. }
  4939. if (!empty($group['highlights'])) {
  4940. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4941. }
  4942. if (!empty($group['role_relationship'])) {
  4943. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4944. }
  4945. if (!empty($group['core_contradiction'])) {
  4946. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4947. }
  4948. if (!empty($group['roles']) && is_array($group['roles'])) {
  4949. $content .= "###主体列表\n";
  4950. foreach ($group['roles'] as $role) {
  4951. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4952. }
  4953. $content .= "\n\n";
  4954. }
  4955. if (!empty($group['art_style'])) {
  4956. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4957. }
  4958. // 场景信息
  4959. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4960. $content .= "###场景列表\n";
  4961. foreach ($group['scenes'] as $scene) {
  4962. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4963. }
  4964. $content .= "\n\n";
  4965. }
  4966. // 分集内容
  4967. if (!empty($group['episode_content'])) {
  4968. $content .= "###分集剧本\n";
  4969. $content .= $group['episode_content'];
  4970. // foreach ($script['episodes'] as $episode) {
  4971. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4972. // // if (!empty($episode['episode_name'])) {
  4973. // // $content .= ":" . $episode['episode_name'];
  4974. // // }
  4975. // // $content .= "\n";
  4976. // $content .= $episode['episode_content'] . "\n\n";
  4977. // }
  4978. }
  4979. }
  4980. return $content;
  4981. }
  4982. /**
  4983. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4984. *
  4985. * @param array $data 包含以下参数:
  4986. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4987. * - question: 用户问题(可选)
  4988. * - model: 使用的模型(r1 或 v3,默认 v3)
  4989. * @return \Generator 返回生成器,用于流式输出
  4990. */
  4991. public function addChat($data) {
  4992. $uid = Site::getUid();
  4993. $anime_id = getProp($data, 'anime_id');
  4994. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4995. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4996. if (!$anime) Utils::throwError('20003:对话不存在');
  4997. $file = getProp($data, 'file');
  4998. $content = getProp($data, 'content', '');
  4999. $bid = getProp($data, 'bid', 0);
  5000. $script_id = getProp($data, 'script_id', 0);
  5001. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5002. $prompt = getProp($data, 'prompt');
  5003. $user_anime_name = getProp($anime, 'anime_name');
  5004. // 处理文本模型
  5005. $model = getProp($data, 'model');
  5006. if (!$model) {
  5007. // 用户没有输入,从anime表获取
  5008. $model = getProp($anime, 'model');
  5009. if (!$model) {
  5010. // anime表也没有,使用默认值
  5011. $model = 'doubao-seed-2-0-mini-260215';
  5012. }
  5013. }
  5014. // 验证模型是否在可用模型表中
  5015. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5016. $model = 'doubao-seed-2-0-mini-260215';
  5017. }
  5018. $is_multi = getProp($anime, 'is_multi');
  5019. $is_single = (int)$is_multi !== 1;
  5020. // 积分余额预检(仅单剧集模式收费)
  5021. if ($is_single) {
  5022. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5023. }
  5024. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5025. if ($prompt) {
  5026. $question .= "本次修改要求如下:\n{$prompt}";
  5027. }
  5028. // if (!$file && !$content && !$bid) {
  5029. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5030. // }
  5031. // 提取文件内容
  5032. if ($file) {
  5033. $content = $this->extractFileContent($file);
  5034. if (!$content) {
  5035. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5036. }
  5037. } elseif ($script_id) {
  5038. $content = $this->getContentByScriptId($script_id);
  5039. if (!$content) {
  5040. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5041. }
  5042. } elseif ($bid) {
  5043. $content = $this->getContentByBid($bid);
  5044. if (!$content) {
  5045. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5046. }
  5047. } elseif ($content) {
  5048. $content = filterContent($content);
  5049. } else {
  5050. $content = getProp($anime, 'content');
  5051. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5052. $need_generate_content = true;
  5053. }
  5054. }
  5055. // 美术风格
  5056. $input_art_style = getProp($data, 'art_style');
  5057. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5058. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5059. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5060. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5061. 中年女:邻居阿姨
  5062. 老年男:幽默大爷
  5063. 老年女:婆婆
  5064. 萌娃:奶气萌娃";
  5065. // 判断是否需要生成原文内容
  5066. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5067. // 如果需要生成原文内容,添加额外的要求
  5068. $content_generation_requirement = $need_generate_content
  5069. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5070. : "";
  5071. // 美术风格
  5072. if (!$mappedArtStyle) {
  5073. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5074. }else {
  5075. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5076. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5077. }else {
  5078. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5079. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5080. }
  5081. }
  5082. $systemPrompt = $is_single
  5083. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5084. 强制要求:
  5085. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5086. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5087. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5088. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5089. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5090. 普通要求:
  5091. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5092. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5093. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5094. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5095. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5096. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5097. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5098. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5099. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5100. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5101. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5102. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5103. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5104. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5105. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5106. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5107. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5108. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5109. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5110. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5111. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5112. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5113. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5114. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5115. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5116. 5.{$mappedArtStyle_prompt}\n\n
  5117. 示例如下:\n
  5118. ###剧本名:西昆仑
  5119. ###故事梗概
  5120. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5121. ###剧本亮点
  5122. 亮点1:绝境奇药,生死一线
  5123. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5124. 亮点2:结拜兄妹,化解尴尬
  5125. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5126. 亮点3:纤发夺命,情愫暗涌
  5127. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5128. ###人物关系
  5129. 阿雪与梁萧之间存在兄妹之情。
  5130. ###核心矛盾
  5131. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5132. ###主体列表
  5133. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5134. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5135. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5136. 姿态:站立。}{{甜心小美}}
  5137. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5138. 全景,正面拍摄,青年女性,亚洲人。
  5139. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5140. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5141. 姿态:站立。}{{阳光青年}}
  5142. ###美术风格
  5143. 基础画风风格词:厚涂古风
  5144. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5145. ###场景列表
  5146. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5147. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5148. 无人物。}
  5149. ###分镜剧本
  5150. ##第1幕:徐家老旧厨房 白天 室内
  5151. 分镜1
  5152. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5153. 场景:徐家老旧厨房
  5154. 构图设计:全景,低角度仰视
  5155. 运镜调度:手持拍摄
  5156. 配音角色:旁白
  5157. 出镜角色:许芸-校服装、徐母
  5158. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5159. 画面类型:普通画面
  5160. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5161. 分镜2
  5162. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5163. 场景:徐家老旧厨房
  5164. 构图设计:近景,徐母面部特写
  5165. 运镜调度:固定镜头
  5166. 配音角色:徐母
  5167. 出镜角色:徐母
  5168. 台词内容:问我夜不归宿死哪儿去了。
  5169. 画面类型:对口型
  5170. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5171. ##第2幕:徐家简陋客厅 黄昏 室内
  5172. 分镜3
  5173. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5174. 场景:徐家简陋客厅
  5175. 构图设计:全景,景深虚化
  5176. 运镜调度:固定镜头
  5177. 配音角色:旁白
  5178. 出镜角色:无
  5179. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5180. 画面类型:普通画面
  5181. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5182. 分镜4
  5183. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5184. 场景:徐家简陋客厅
  5185. 构图设计:特写,火车票
  5186. 运镜调度:固定镜头
  5187. 配音角色:旁白
  5188. 出镜角色:无
  5189. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5190. 画面类型:普通画面
  5191. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5192. "
  5193. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5194. 强制要求:\n
  5195. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5196. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5197. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5198. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5199. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5200. 普通要求:\n
  5201. 1.剧本名(必须生成)必须与文档内容高度相关
  5202. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5203. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5204. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5205. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5206. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5207. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5208. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5209. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5210. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5211. 4.{$mappedArtStyle_prompt}\n\n
  5212. 示例如下:\n
  5213. ###剧本名:西昆仑
  5214. ###故事梗概
  5215. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5216. ###剧本亮点
  5217. 亮点1:绝境奇药,生死一线
  5218. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5219. 亮点2:结拜兄妹,化解尴尬
  5220. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5221. 亮点3:纤发夺命,情愫暗涌
  5222. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5223. ###人物关系
  5224. 阿雪与梁萧之间存在兄妹之情。
  5225. ###核心矛盾
  5226. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5227. ###主体列表
  5228. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5229. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5230. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5231. 姿态:站立。}{{甜心小美}}
  5232. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5233. 全景,正面拍摄,青年女性,亚洲人。
  5234. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5235. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5236. 姿态:站立。}{{阳光青年}}
  5237. ###美术风格
  5238. 基础画风风格词:厚涂古风
  5239. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5240. ###场景列表
  5241. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5242. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5243. 无人物。}";
  5244. // 构建消息
  5245. $messages = [
  5246. [
  5247. 'role' => 'system',
  5248. 'content' => $systemPrompt
  5249. ],
  5250. [
  5251. 'role' => 'user',
  5252. 'content' => "以下是文档内容:
  5253. {$content}
  5254. 用户问题:
  5255. {$question}"
  5256. ]
  5257. ];
  5258. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5259. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5260. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5261. if ($model === 'deepseek-chat') {
  5262. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5263. $model = 'deepseek-v4-flash';
  5264. $thinkingMode = 'disabled';
  5265. } elseif ($model === 'deepseek-reasoner') {
  5266. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5267. $model = 'deepseek-v4-flash';
  5268. $thinkingMode = 'enabled';
  5269. }
  5270. $post_data = [
  5271. 'model' => $model,
  5272. 'messages' => $messages,
  5273. // 'max_tokens' => 8192,
  5274. 'temperature' => 0.7,
  5275. 'frequency_penalty' => 0,
  5276. 'presence_penalty' => 0,
  5277. 'response_format' => ['type' => 'text'],
  5278. 'thinking' => ['type'=>$thinkingMode],
  5279. 'stream' => true // 启用流式输出
  5280. ];
  5281. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5282. // 根据模型类型选择调用方法
  5283. $fullContent = '';
  5284. $fullReasoningContent = '';
  5285. $usage = [];
  5286. try {
  5287. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5288. // DeepSeek 官方模型使用 DeepSeek API
  5289. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5290. } else if (in_array($model, $this->gpt_text_models)) {
  5291. // GPT-5.4 模型使用 TokenRouter API
  5292. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5293. } else if (in_array($model, $this->gemini_text_models)) {
  5294. // Gemini 模型使用 Gemini API
  5295. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5296. } else {
  5297. // 其他模型使用火山引擎API
  5298. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5299. }
  5300. // 验证返回值类型
  5301. if (!is_iterable($streamGenerator)) {
  5302. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5303. dLog('deepseek')->error('addChat流式生成器无效', [
  5304. 'generator_type' => $errorType,
  5305. 'model' => $model,
  5306. 'anime_id' => $anime_id
  5307. ]);
  5308. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5309. 'type' => $errorType,
  5310. 'model' => $model
  5311. ]);
  5312. yield [
  5313. 'type' => 'error',
  5314. 'script' => [],
  5315. 'episode' => [],
  5316. 'answer' => '',
  5317. 'reasoning' => '',
  5318. 'usage' => [],
  5319. 'error' => '接口返回数据异常,请重新请求'
  5320. ];
  5321. return;
  5322. }
  5323. // 处理流式输出
  5324. foreach ($streamGenerator as $chunk) {
  5325. if (isset($chunk['type'])) {
  5326. if ($chunk['type'] === 'done') {
  5327. // 最终结果
  5328. $fullContent = $chunk['full_content'];
  5329. $fullReasoningContent = $chunk['full_reasoning'];
  5330. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5331. } else {
  5332. // 逐块yield数据
  5333. yield $chunk;
  5334. }
  5335. }
  5336. }
  5337. } catch (\Exception $e) {
  5338. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5339. 'model' => $model,
  5340. 'anime_id' => $anime_id,
  5341. 'trace' => $e->getTraceAsString()
  5342. ]);
  5343. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5344. 'error' => $e->getMessage(),
  5345. 'model' => $model
  5346. ]);
  5347. yield [
  5348. 'type' => 'error',
  5349. 'script' => [],
  5350. 'episode' => [],
  5351. 'answer' => '',
  5352. 'reasoning' => '',
  5353. 'usage' => [],
  5354. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5355. ];
  5356. return;
  5357. }
  5358. dLog('deepseek')->info('完整内容: '.$fullContent);
  5359. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5360. // 处理完整内容并返回最终结果
  5361. $script_arr = [];
  5362. if ($fullContent) {
  5363. $script_arr = handleScriptContent($fullContent);
  5364. dLog('deepseek')->info('解析内容', $script_arr);
  5365. logDB('deepseek', 'info', '解析内容', $script_arr);
  5366. }
  5367. if (empty($script_arr['roles'])) {
  5368. // 未生成剧本相关内容,保存对话记录并返回提示
  5369. dLog('deepseek')->info('未生成剧本相关的内容');
  5370. try {
  5371. DB::beginTransaction();
  5372. $now = date('Y-m-d H:i:s');
  5373. // 保存对话记录
  5374. $records = [
  5375. [
  5376. 'uid' => $uid,
  5377. 'anime_id' => $anime_id,
  5378. 'sequence' => 0,
  5379. 'role' => 'user',
  5380. 'content' => $prompt,
  5381. 'created_at' => $now,
  5382. 'updated_at' => $now
  5383. ],
  5384. [
  5385. 'uid' => $uid,
  5386. 'anime_id' => $anime_id,
  5387. 'sequence' => 0,
  5388. 'role' => 'assistant',
  5389. // 'content' => $fullContent,
  5390. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5391. 'created_at' => $now,
  5392. 'updated_at' => $now
  5393. ]
  5394. ];
  5395. DB::table('mp_anime_records')->insert($records);
  5396. DB::commit();
  5397. } catch (\Exception $e) {
  5398. DB::rollBack();
  5399. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5400. }
  5401. yield [
  5402. 'type' => 'done',
  5403. 'script' => [],
  5404. 'episode' => [],
  5405. 'answer' => $fullContent,
  5406. 'reasoning' => $fullReasoningContent,
  5407. 'usage' => $usage,
  5408. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5409. ];
  5410. return;
  5411. }
  5412. // 如果需要生成原文内容,从script_arr中提取
  5413. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5414. $content = $script_arr['content'];
  5415. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5416. if (!$content) {
  5417. yield [
  5418. 'type' => 'done',
  5419. 'script' => [],
  5420. 'episode' => [],
  5421. 'answer' => $fullContent,
  5422. 'reasoning' => $fullReasoningContent,
  5423. 'usage' => $usage,
  5424. 'error' => '未生成剧本内容,请调整提示词再试'
  5425. ];
  5426. return;
  5427. }
  5428. }
  5429. // 替换美术风格
  5430. if ($mappedArtStyle !== '') {
  5431. $script_arr['art_style'] = $mappedArtStyle;
  5432. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5433. }
  5434. // 新建动漫
  5435. if ($user_anime_name == '新剧本策划') {
  5436. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5437. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5438. // if (!$anime_name) {
  5439. // // 未识别到剧本名,保存对话记录并返回提示
  5440. // dLog('deepseek')->info('未能识别到剧本名称');
  5441. // try {
  5442. // DB::beginTransaction();
  5443. // $now = date('Y-m-d H:i:s');
  5444. // // 保存对话记录
  5445. // $records = [
  5446. // [
  5447. // 'uid' => $uid,
  5448. // 'anime_id' => $anime_id,
  5449. // 'sequence' => 0,
  5450. // 'role' => 'user',
  5451. // 'content' => $prompt,
  5452. // 'created_at' => $now,
  5453. // 'updated_at' => $now
  5454. // ],
  5455. // [
  5456. // 'uid' => $uid,
  5457. // 'anime_id' => $anime_id,
  5458. // 'sequence' => 0,
  5459. // 'role' => 'assistant',
  5460. // 'content' => '未能生成剧本名称,请重试',
  5461. // 'created_at' => $now,
  5462. // 'updated_at' => $now
  5463. // ]
  5464. // ];
  5465. // DB::table('mp_anime_records')->insert($records);
  5466. // DB::commit();
  5467. // } catch (\Exception $e) {
  5468. // DB::rollBack();
  5469. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5470. // }
  5471. // yield [
  5472. // 'type' => 'done',
  5473. // 'script' => [],
  5474. // 'episode' => [],
  5475. // 'answer' => $fullContent,
  5476. // 'reasoning' => $fullReasoningContent,
  5477. // 'usage' => $usage,
  5478. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5479. // ];
  5480. // return;
  5481. // }
  5482. // 确认对话名称唯一性
  5483. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5484. $anime_name = $anime_name . '_' . date('YmdHis');
  5485. }
  5486. }else {
  5487. $anime_name = $user_anime_name;
  5488. }
  5489. $table_data = [
  5490. 'user_id' => $uid,
  5491. 'anime_name' => $anime_name,
  5492. 'model' => $model,
  5493. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5494. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5495. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5496. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5497. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5498. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5499. 'art_style_type' => $input_art_style,
  5500. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5501. 'status' => '解析完成',
  5502. 'content' => $content,
  5503. 'is_multi' => $is_multi,
  5504. 'ace_mode' => $ace_mode,
  5505. 'generate_status' => '待执行',
  5506. 'updated_at' => date('Y-m-d H:i:s')
  5507. ];
  5508. if ($table_data['content']) {
  5509. $chapters = splitContent($table_data['content']);
  5510. $chapter_count = count($chapters);
  5511. if ($chapter_count > 0) {
  5512. $table_data['start_episode_sequence'] = 1;
  5513. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5514. }
  5515. }
  5516. // 如果有剧本ID则进行绑定
  5517. if ($script_id) {
  5518. $table_data['script_id'] = $script_id;
  5519. }
  5520. $single_episode = [];
  5521. try {
  5522. DB::beginTransaction();
  5523. $now = date('Y-m-d H:i:s');
  5524. // 更新动漫大纲
  5525. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5526. if (!$boolen) {
  5527. dLog('deepseek')->info('动漫保存失败', $table_data);
  5528. Utils::throwError('20003:动漫保存失败');
  5529. }
  5530. // 保存对话记录
  5531. $records = [
  5532. [
  5533. 'uid' => $uid,
  5534. 'anime_id' => $anime_id,
  5535. 'sequence' => 0,
  5536. 'role' => 'user',
  5537. 'content' => $prompt,
  5538. 'created_at' => date('Y-m-d H:i:s'),
  5539. 'updated_at' => date('Y-m-d H:i:s')
  5540. ],
  5541. [
  5542. 'uid' => $uid,
  5543. 'anime_id' => $anime_id,
  5544. 'sequence' => 0,
  5545. 'role' => 'assistant',
  5546. 'content' => $fullContent,
  5547. 'created_at' => date('Y-m-d H:i:s'),
  5548. 'updated_at' => date('Y-m-d H:i:s')
  5549. ]
  5550. ];
  5551. // 保存对话记录
  5552. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5553. if (!$boolen3) {
  5554. Utils::throwError('20003:对话记录保存失败');
  5555. }
  5556. if ($is_single) {
  5557. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5558. if (empty($episode_arr['acts'])) {
  5559. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5560. }
  5561. $saveResult = $this->saveEpisodeVersionData(
  5562. $anime_id,
  5563. 1,
  5564. $episode_arr,
  5565. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5566. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5567. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5568. null,
  5569. null,
  5570. false,
  5571. $content,
  5572. $now
  5573. );
  5574. $single_episode = $saveResult['episode'];
  5575. $episode_id = $saveResult['episode_id'];
  5576. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5577. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5578. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5579. 'props' => json_encode($saveResult['merged_props'], 256),
  5580. 'updated_at' => $now
  5581. ]);
  5582. if ($boolen5 === false) {
  5583. Utils::throwError('20003:单剧集主表资源同步失败');
  5584. }
  5585. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5586. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5587. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5588. $episode_record_content = '确认分镜大纲';
  5589. if ($content !== '') {
  5590. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5591. }
  5592. $episode_records = [
  5593. [
  5594. 'uid' => $uid,
  5595. 'anime_id' => $anime_id,
  5596. 'role' => 'user',
  5597. 'content' => $episode_record_content,
  5598. 'sequence' => 1,
  5599. 'episode_id' => $episode_id,
  5600. 'created_at' => $now,
  5601. 'updated_at' => $now
  5602. ],
  5603. [
  5604. 'uid' => $uid,
  5605. 'anime_id' => $anime_id,
  5606. 'role' => 'assistant',
  5607. 'content' => $fullContent,
  5608. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5609. 'sequence' => 1,
  5610. 'episode_id' => $episode_id,
  5611. 'created_at' => $now,
  5612. 'updated_at' => $now
  5613. ]
  5614. ];
  5615. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5616. if (!$boolen4) {
  5617. Utils::throwError('20003:单剧集分镜记录保存失败');
  5618. }
  5619. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5620. if ($is_single && !empty($single_episode)) {
  5621. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5622. 'anime_id' => $anime_id,
  5623. 'episode_id' => $episode_id ?? 0,
  5624. 'model' => $model,
  5625. 'source' => 'addChat',
  5626. ]);
  5627. }
  5628. }
  5629. }catch (\Exception $e) {
  5630. DB::rollBack();
  5631. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5632. yield [
  5633. 'type' => 'done',
  5634. 'answer' => $fullContent,
  5635. 'reasoning' => $fullReasoningContent,
  5636. 'usage' => $usage,
  5637. 'error' => $e->getMessage(),
  5638. ];
  5639. return;
  5640. }
  5641. DB::commit();
  5642. dLog('deepseek')->info('保存完毕');
  5643. if ($is_single && !empty($single_episode)) {
  5644. // $this->batchSetGlobalRoleImg([
  5645. // 'anime_id' => $anime_id,
  5646. // ]);
  5647. // $this->batchSetGlobalSceneImg([
  5648. // 'anime_id' => $anime_id,
  5649. // ]);
  5650. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5651. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5652. }
  5653. $table_data['anime_id'] = $anime_id;
  5654. $table_data['roles'] = json_decode($table_data['roles'], true);
  5655. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5656. // $table_data['episodes'] = $script_arr['episodes'];
  5657. unset($table_data['created_at']);
  5658. unset($table_data['updated_at']);
  5659. unset($table_data['status']);
  5660. dLog('deepseek')->info('开始返回');
  5661. yield [
  5662. 'type' => 'done',
  5663. 'script' => $table_data,
  5664. 'episode' => $single_episode,
  5665. 'answer' => $fullContent,
  5666. 'reasoning' => $fullReasoningContent,
  5667. 'usage' => $usage
  5668. ];
  5669. }
  5670. public function reGenerateAnime($data) {
  5671. $uid = Site::getUid();
  5672. $file = getProp($data, 'file');
  5673. $content = getProp($data, 'content', '');
  5674. $bid = getProp($data, 'bid', 0);
  5675. $script_id = getProp($data, 'script_id', 0);
  5676. $anime_id = getProp($data, 'anime_id');
  5677. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5678. if (!$anime) {
  5679. Utils::throwError('20003:该对话不存在');
  5680. }
  5681. $user_anime_name = getProp($anime, 'anime_name');
  5682. $prompt = getProp($data, 'prompt');
  5683. // 处理文本模型
  5684. $model = getProp($data, 'model');
  5685. if (!$model) {
  5686. // 用户没有输入,从anime表获取
  5687. $model = getProp($anime, 'model');
  5688. if (!$model) {
  5689. // anime表也没有,使用默认值
  5690. $model = 'doubao-seed-2-0-mini-260215';
  5691. }
  5692. }
  5693. // 验证模型是否在可用模型表中
  5694. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5695. $model = 'doubao-seed-2-0-mini-260215';
  5696. }
  5697. $is_multi = getProp($anime, 'is_multi', 1);
  5698. $is_single = (int)$is_multi !== 1;
  5699. // 积分余额预检(仅单剧集模式收费)
  5700. if ($is_single) {
  5701. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5702. }
  5703. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5704. if ($is_single) {
  5705. $episode_exists = DB::table('mp_anime_episodes')
  5706. ->where('anime_id', $anime_id)
  5707. ->where('sequence', 1)
  5708. ->exists();
  5709. if ($episode_exists) {
  5710. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5711. }
  5712. }
  5713. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5714. if ($prompt) {
  5715. $question .= "本次修改要求如下:\n{$prompt}";
  5716. }
  5717. // 提取文件内容
  5718. if ($file) {
  5719. $content = $this->extractFileContent($file);
  5720. if (!$content) {
  5721. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5722. }
  5723. } elseif ($script_id) {
  5724. $content = $this->getContentByScriptId($script_id);
  5725. if (!$content) {
  5726. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5727. }
  5728. } elseif ($bid) {
  5729. $content = $this->getContentByBid($bid);
  5730. if (!$content) {
  5731. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5732. }
  5733. } elseif ($content) {
  5734. $content = filterContent($content);
  5735. }else {
  5736. $content = filterContent(getProp($anime, 'content'));
  5737. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5738. $need_generate_content = true;
  5739. }
  5740. }
  5741. // 判断是否需要生成原文内容
  5742. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5743. // 如果需要生成原文内容,添加额外的要求
  5744. $content_generation_requirement = $need_generate_content
  5745. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5746. : "";
  5747. // 美术风格
  5748. $input_art_style = getProp($anime, 'art_style');
  5749. if (!$input_art_style) {
  5750. $input_art_style = getProp($data, 'art_style');
  5751. }
  5752. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5753. // 美术风格
  5754. if (!$mappedArtStyle) {
  5755. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5756. }else {
  5757. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5758. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5759. }else {
  5760. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5761. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5762. }
  5763. }
  5764. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5765. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5766. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5767. 中年女:邻居阿姨
  5768. 老年男:幽默大爷
  5769. 老年女:婆婆
  5770. 萌娃:奶气萌娃";
  5771. $system_message = ['role'=>'system', 'content'=>$is_single
  5772. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5773. 强制要求:
  5774. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5775. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5776. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5777. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5778. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5779. 普通要求:
  5780. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5781. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5782. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5783. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5784. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5785. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5786. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5787. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5788. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5789. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5790. 3.$mappedArtStyle_prompt\n\n
  5791. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5792. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5793. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5794. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5795. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5796. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5797. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5798. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5799. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5800. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5801. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5802. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5803. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5804. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5805. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5806. 示例如下:\n
  5807. ###剧本名:西昆仑
  5808. ###故事梗概
  5809. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5810. ###剧本亮点
  5811. 亮点1:绝境奇药,生死一线
  5812. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5813. 亮点2:结拜兄妹,化解尴尬
  5814. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5815. 亮点3:纤发夺命,情愫暗涌
  5816. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5817. ###人物关系
  5818. 阿雪与梁萧之间存在兄妹之情。
  5819. ###核心矛盾
  5820. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5821. ###主体列表
  5822. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5823. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5824. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5825. 姿态:站立。}{{甜心小美}}
  5826. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5827. 全景,正面拍摄,青年女性,亚洲人。
  5828. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5829. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5830. 姿态:站立。}{{阳光青年}}
  5831. ###美术风格
  5832. 基础画风风格词:厚涂古风
  5833. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5834. ###场景列表
  5835. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5836. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5837. 无人物。}
  5838. ###分镜剧本
  5839. ##第1幕:徐家老旧厨房 白天 室内
  5840. 分镜1
  5841. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5842. 场景:徐家老旧厨房
  5843. 构图设计:全景,低角度仰视
  5844. 运镜调度:手持拍摄
  5845. 配音角色:旁白
  5846. 出镜角色:许芸-校服装、徐母
  5847. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5848. 画面类型:普通画面
  5849. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5850. 分镜2
  5851. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5852. 场景:徐家老旧厨房
  5853. 构图设计:近景,徐母面部特写
  5854. 运镜调度:固定镜头
  5855. 配音角色:徐母
  5856. 出镜角色:徐母
  5857. 台词内容:问我夜不归宿死哪儿去了。
  5858. 画面类型:对口型
  5859. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5860. ##第2幕:徐家简陋客厅 黄昏 室内
  5861. 分镜3
  5862. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5863. 场景:徐家简陋客厅
  5864. 构图设计:全景,景深虚化
  5865. 运镜调度:固定镜头
  5866. 配音角色:旁白
  5867. 出镜角色:无
  5868. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5869. 画面类型:普通画面
  5870. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5871. 分镜4
  5872. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5873. 场景:徐家简陋客厅
  5874. 构图设计:特写,火车票
  5875. 运镜调度:固定镜头
  5876. 配音角色:旁白
  5877. 出镜角色:无
  5878. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5879. 画面类型:普通画面
  5880. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5881. "
  5882. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5883. 强制要求:\n
  5884. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5885. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5886. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5887. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5888. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5889. 普通要求:\n
  5890. 1.剧本名(必须生成)必须与文档内容高度相关
  5891. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5892. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5893. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5894. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5895. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5896. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5897. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5898. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5899. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5900. 4.$mappedArtStyle_prompt\n\n
  5901. 示例如下:\n
  5902. ###剧本名:西昆仑
  5903. ###故事梗概
  5904. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5905. ###剧本亮点
  5906. 亮点1:绝境奇药,生死一线
  5907. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5908. 亮点2:结拜兄妹,化解尴尬
  5909. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5910. 亮点3:纤发夺命,情愫暗涌
  5911. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5912. ###人物关系
  5913. 阿雪与梁萧之间存在兄妹之情。
  5914. ###核心矛盾
  5915. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5916. ###主体列表
  5917. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5918. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5919. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5920. 姿态:站立。}{{甜心小美}}
  5921. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5922. 全景,正面拍摄,青年女性,亚洲人。
  5923. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5924. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5925. 姿态:站立。}{{阳光青年}}
  5926. ###美术风格
  5927. 基础画风风格词:厚涂古风
  5928. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5929. ###场景列表
  5930. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5931. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5932. 无人物。}"];
  5933. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5934. $episode_count = $this->extractEpisodeNumber($prompt);
  5935. if ((int)getProp($anime, 'is_multi') !== 1) {
  5936. yield [
  5937. 'type' => 'done',
  5938. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5939. 'reasoning' => '',
  5940. 'usage' => []
  5941. ];
  5942. return;
  5943. }
  5944. if ($episode_count) {
  5945. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5946. $system_message = [
  5947. 'role' => 'system',
  5948. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5949. 强制要求:\n
  5950. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5951. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5952. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5953. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5954. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5955. 普通要求:\n
  5956. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5957. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5958. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5959. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5960. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5961. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5962. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5963. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5964. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5965. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5966. 示例如下:\n
  5967. ###剧本名:西昆仑
  5968. ###故事梗概
  5969. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5970. ###剧本亮点
  5971. 亮点1:绝境奇药,生死一线
  5972. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5973. 亮点2:结拜兄妹,化解尴尬
  5974. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5975. 亮点3:纤发夺命,情愫暗涌
  5976. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5977. ###人物关系
  5978. 阿雪与梁萧之间存在兄妹之情。
  5979. ###核心矛盾
  5980. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5981. ###主体列表
  5982. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5983. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5984. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5985. 姿态:站立。}{{甜心小美}}
  5986. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5987. 全景,正面拍摄,青年女性,亚洲人。
  5988. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5989. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5990. 姿态:站立。}{{阳光青年}}
  5991. ###美术风格
  5992. 基础画风风格词:厚涂古风
  5993. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5994. ###场景列表
  5995. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5996. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5997. 无人物。}
  5998. ###分集详细内容
  5999. ##第1章 重生
  6000. 我重生了。
  6001. 源于一个男人偏执的暗恋。
  6002. ##第2章 相救
  6003. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6004. 我眼睛扫向站在锅炉后的卞大伟。"
  6005. ];
  6006. // 构建消息
  6007. $messages = [
  6008. $system_message,
  6009. [
  6010. 'role' => 'user',
  6011. 'content' => "以下是文档内容:
  6012. {$content}
  6013. 用户问题:
  6014. {$question}"
  6015. ]
  6016. ];
  6017. }else {
  6018. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6019. // 构建消息
  6020. $messages = [
  6021. $system_message,
  6022. [
  6023. 'role' => 'user',
  6024. 'content' => "以下是文档内容:
  6025. {$content}
  6026. 用户问题:
  6027. {$question}"
  6028. ]
  6029. ];
  6030. }else {
  6031. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6032. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6033. return (array)$value;
  6034. })->toArray();
  6035. array_unshift($messages, $system_message);
  6036. $messages[] = [
  6037. 'role' => 'user',
  6038. 'content' => $prompt
  6039. ];
  6040. }
  6041. }
  6042. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6043. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6044. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6045. if ($model === 'deepseek-chat') {
  6046. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6047. $model = 'deepseek-v4-flash';
  6048. $thinkingMode = 'disabled';
  6049. } elseif ($model === 'deepseek-reasoner') {
  6050. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6051. $model = 'deepseek-v4-flash';
  6052. $thinkingMode = 'enabled';
  6053. }
  6054. $post_data = [
  6055. 'model' => $model,
  6056. 'messages' => $messages,
  6057. // 'max_tokens' => 8192,
  6058. 'temperature' => 0.7,
  6059. 'frequency_penalty' => 0,
  6060. 'presence_penalty' => 0,
  6061. 'response_format' => ['type' => 'text'],
  6062. 'thinking' => ['type' => $thinkingMode],
  6063. 'stream' => true // 启用流式输出
  6064. ];
  6065. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6066. // 根据模型类型选择调用方法
  6067. $fullContent = '';
  6068. $fullReasoningContent = '';
  6069. $usage = [];
  6070. // dd($post_data);
  6071. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6072. try {
  6073. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6074. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6075. } else if (in_array($model, $this->gpt_text_models)) {
  6076. // GPT-5.4 模型使用 TokenRouter API
  6077. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6078. } else if (in_array($model, $this->gemini_text_models)) {
  6079. // Gemini 模型使用 Gemini API
  6080. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6081. } else {
  6082. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6083. }
  6084. // 验证返回值类型
  6085. if (!is_iterable($streamGenerator)) {
  6086. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6087. dLog('deepseek')->error('方法名流式生成器无效', [
  6088. 'generator_type' => $errorType,
  6089. 'model' => $model,
  6090. // 添加其他上下文信息
  6091. ]);
  6092. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6093. 'type' => $errorType,
  6094. 'model' => $model
  6095. ]);
  6096. yield [
  6097. 'type' => 'error',
  6098. // 根据方法返回相应的空数据结构
  6099. 'answer' => '',
  6100. 'reasoning' => '',
  6101. 'usage' => [],
  6102. 'error' => '接口返回数据异常,请重新请求'
  6103. ];
  6104. return;
  6105. }
  6106. // 处理流式输出
  6107. foreach ($streamGenerator as $chunk) {
  6108. if (isset($chunk['type'])) {
  6109. if ($chunk['type'] === 'done') {
  6110. $fullContent = $chunk['full_content'];
  6111. $fullReasoningContent = $chunk['full_reasoning'];
  6112. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6113. } else {
  6114. yield $chunk;
  6115. }
  6116. }
  6117. }
  6118. } catch (\Exception $e) {
  6119. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6120. 'model' => $model,
  6121. 'trace' => $e->getTraceAsString()
  6122. ]);
  6123. logDB('deepseek', 'error', '方法名流式处理失败', [
  6124. 'error' => $e->getMessage(),
  6125. 'model' => $model
  6126. ]);
  6127. yield [
  6128. 'type' => 'error',
  6129. // 根据方法返回相应的空数据结构
  6130. 'answer' => '',
  6131. 'reasoning' => '',
  6132. 'usage' => [],
  6133. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6134. ];
  6135. return;
  6136. }
  6137. dLog('deepseek')->info('完整内容: '.$fullContent);
  6138. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6139. // 处理完整内容并返回最终结果
  6140. $script_arr = [];
  6141. if ($fullContent) {
  6142. $script_arr = handleScriptContent($fullContent);
  6143. dLog('deepseek')->info('解析内容', $script_arr);
  6144. logDB('deepseek', 'info', '解析内容', $script_arr);
  6145. }
  6146. if (empty($script_arr['roles'])) {
  6147. // 未生成剧本相关内容,保存对话记录并返回提示
  6148. dLog('deepseek')->info('未生成剧本相关的内容');
  6149. try {
  6150. $now = date('Y-m-d H:i:s');
  6151. // 保存对话记录
  6152. $records = [
  6153. [
  6154. 'uid' => $uid,
  6155. 'anime_id' => $anime_id,
  6156. 'sequence' => 0,
  6157. 'role' => 'user',
  6158. 'content' => $prompt,
  6159. 'created_at' => $now,
  6160. 'updated_at' => $now
  6161. ],
  6162. [
  6163. 'uid' => $uid,
  6164. 'anime_id' => $anime_id,
  6165. 'sequence' => 0,
  6166. 'role' => 'assistant',
  6167. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6168. 'created_at' => $now,
  6169. 'updated_at' => $now
  6170. ]
  6171. ];
  6172. DB::table('mp_anime_records')->insert($records);
  6173. } catch (\Exception $e) {
  6174. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6175. }
  6176. yield [
  6177. 'type' => 'done',
  6178. 'script' => [],
  6179. 'episode' => [],
  6180. 'answer' => $fullContent,
  6181. 'reasoning' => $fullReasoningContent,
  6182. 'usage' => $usage,
  6183. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6184. ];
  6185. return;
  6186. }
  6187. // 替换美术风格
  6188. if ($mappedArtStyle !== '') {
  6189. $script_arr['art_style'] = $mappedArtStyle;
  6190. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6191. }
  6192. if ($user_anime_name != '新剧本策划') {
  6193. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6194. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6195. // 确认对话名称唯一性
  6196. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6197. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6198. }
  6199. }else {
  6200. $anime_name = $user_anime_name;
  6201. }
  6202. $table_data = [
  6203. 'user_id' => $uid,
  6204. 'model' => $model,
  6205. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6206. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6207. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6208. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6209. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6210. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6211. 'art_style_type' => $input_art_style,
  6212. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6213. 'status' => '解析完成',
  6214. 'generate_status' => '待执行',
  6215. 'updated_at' => date('Y-m-d H:i:s')
  6216. ];
  6217. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6218. // 如果是修改集数,则将content内容更新(会改变原文)
  6219. if (isset($episode_count) && $episode_count > 0) {
  6220. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6221. $table_data['start_episode_sequence'] = 1;
  6222. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6223. }else {
  6224. // 如果需要生成原文内容,从script_arr中提取
  6225. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6226. $table_data['content'] = $script_arr['content'];
  6227. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6228. if (!$table_data['content']) {
  6229. yield [
  6230. 'type' => 'done',
  6231. 'script' => [],
  6232. 'episode' => [],
  6233. 'answer' => $fullContent,
  6234. 'reasoning' => $fullReasoningContent,
  6235. 'usage' => $usage,
  6236. 'error' => '未生成剧本内容,请调整提示词再试'
  6237. ];
  6238. return;
  6239. }
  6240. }
  6241. if (isset($table_data['content']) && $table_data['content']) {
  6242. $chapters = splitContent($table_data['content']);
  6243. $chapter_count = count($chapters);
  6244. if ($chapter_count > 0) {
  6245. $table_data['start_episode_sequence'] = 1;
  6246. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6247. }
  6248. }
  6249. }
  6250. $single_episode = [];
  6251. try {
  6252. DB::beginTransaction();
  6253. $now = date('Y-m-d H:i:s');
  6254. // 更新动漫大纲
  6255. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6256. if (!$boolen) {
  6257. dLog('deepseek')->info('对话修改失败', $table_data);
  6258. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6259. Utils::throwError('20003:对话修改失败');
  6260. }
  6261. // 保存对话记录
  6262. $records = [
  6263. [
  6264. 'uid' => $uid,
  6265. 'anime_id' => $anime_id,
  6266. 'sequence' => 0,
  6267. 'role' => 'user',
  6268. 'content' => $prompt,
  6269. 'created_at' => $now,
  6270. 'updated_at' => $now
  6271. ],
  6272. [
  6273. 'uid' => $uid,
  6274. 'anime_id' => $anime_id,
  6275. 'sequence' => 0,
  6276. 'role' => 'assistant',
  6277. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6278. 'content' => $fullContent,
  6279. 'created_at' => $now,
  6280. 'updated_at' => $now
  6281. ]
  6282. ];
  6283. // 保存对话记录
  6284. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6285. if (!$boolen3) {
  6286. Utils::throwError('20003:对话记录保存失败');
  6287. }
  6288. // 单剧集模式:生成并保存剧集信息
  6289. if ($is_single) {
  6290. $anime_name = getProp($anime, 'anime_name', '未命名');
  6291. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6292. if (empty($episode_arr['acts'])) {
  6293. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6294. }
  6295. $saveResult = $this->saveEpisodeVersionData(
  6296. $anime_id,
  6297. 1,
  6298. $episode_arr,
  6299. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6300. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6301. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6302. null,
  6303. null,
  6304. false,
  6305. $content,
  6306. $now
  6307. );
  6308. $single_episode = $saveResult['episode'];
  6309. $episode_id = $saveResult['episode_id'];
  6310. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6311. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6312. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6313. 'props' => json_encode($saveResult['merged_props'], 256),
  6314. 'updated_at' => $now
  6315. ]);
  6316. if ($boolen5 === false) {
  6317. Utils::throwError('20003:单剧集主表资源同步失败');
  6318. }
  6319. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6320. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6321. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6322. $episode_record_content = '确认分镜大纲';
  6323. if ($content !== '') {
  6324. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6325. }
  6326. $episode_records = [
  6327. [
  6328. 'uid' => $uid,
  6329. 'anime_id' => $anime_id,
  6330. 'role' => 'user',
  6331. 'content' => $episode_record_content,
  6332. 'sequence' => 1,
  6333. 'episode_id' => $episode_id,
  6334. 'created_at' => $now,
  6335. 'updated_at' => $now
  6336. ],
  6337. [
  6338. 'uid' => $uid,
  6339. 'anime_id' => $anime_id,
  6340. 'role' => 'assistant',
  6341. 'content' => $fullContent,
  6342. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6343. 'sequence' => 1,
  6344. 'episode_id' => $episode_id,
  6345. 'created_at' => $now,
  6346. 'updated_at' => $now
  6347. ]
  6348. ];
  6349. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6350. if (!$boolen4) {
  6351. Utils::throwError('20003:单剧集分镜记录保存失败');
  6352. }
  6353. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6354. if ($is_single && !empty($single_episode)) {
  6355. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6356. 'anime_id' => $anime_id,
  6357. 'episode_id' => $episode_id ?? 0,
  6358. 'model' => $model,
  6359. 'source' => 'reGenerateAnime',
  6360. ]);
  6361. }
  6362. }
  6363. }catch (\Exception $e) {
  6364. DB::rollBack();
  6365. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6366. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6367. yield [
  6368. 'type' => 'done',
  6369. 'answer' => $fullContent,
  6370. 'reasoning' => $fullReasoningContent,
  6371. 'usage' => $usage,
  6372. 'error' => $e->getMessage(),
  6373. ];
  6374. return;
  6375. }
  6376. DB::commit();
  6377. dLog('deepseek')->info('保存完毕');
  6378. if ($is_single && !empty($single_episode)) {
  6379. // $this->batchSetGlobalRoleImg([
  6380. // 'anime_id' => $anime_id,
  6381. // ]);
  6382. // $this->batchSetGlobalSceneImg([
  6383. // 'anime_id' => $anime_id,
  6384. // ]);
  6385. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6386. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6387. }
  6388. $table_data['anime_id'] = $anime_id;
  6389. $table_data['roles'] = json_decode($table_data['roles'], true);
  6390. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6391. unset($table_data['updated_at']);
  6392. unset($table_data['status']);
  6393. yield [
  6394. 'type' => 'done',
  6395. 'script' => $table_data,
  6396. 'episode' => $single_episode,
  6397. 'answer' => $fullContent,
  6398. 'reasoning' => $fullReasoningContent,
  6399. 'usage' => $usage
  6400. ];
  6401. }
  6402. public function chat($data) {
  6403. $uid = Site::getUid();
  6404. // 积分余额预检(不足直接报错)
  6405. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6406. $anime_id = getProp($data, 'anime_id');
  6407. $file = getProp($data, 'file');
  6408. $content = getProp($data, 'content', '');
  6409. $bid = getProp($data, 'bid', 0);
  6410. $script_id = getProp($data, 'script_id', 0);
  6411. $episode_number = getProp($data, 'episode_number', 1);
  6412. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6413. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6414. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6415. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6416. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6417. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6418. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6419. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6420. $roles = is_array($roles) ? $roles : [];
  6421. $scenes = is_array($scenes) ? $scenes : [];
  6422. // 获取最后一集序号
  6423. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6424. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6425. // 转换主体列表和场景列表的格式
  6426. // 获取参考主体或场景
  6427. if ((int)$episode_number === 1) {
  6428. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6429. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6430. }else {
  6431. $prev_episode_number = $episode_number - 1;
  6432. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6433. }
  6434. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6435. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6436. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6437. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6438. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6439. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6440. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6441. 中年女:邻居阿姨
  6442. 老年男:幽默大爷
  6443. 老年女:婆婆
  6444. 萌娃:奶气萌娃";
  6445. if ($roles_content) {
  6446. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6447. 主体范围:\n {$roles_content}\n
  6448. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6449. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6450. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6451. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6452. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6453. }else {
  6454. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6455. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6456. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6457. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6458. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6459. }
  6460. if ($scenes_content) {
  6461. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6462. 场景范围:\n {$scenes_content}\n
  6463. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6464. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6465. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6466. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6467. }else {
  6468. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6469. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6470. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6471. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6472. }
  6473. // 提取文件内容
  6474. if ($file) {
  6475. $uploaded_content = $this->extractFileContent($file);
  6476. if (!$uploaded_content) {
  6477. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6478. }
  6479. } elseif ($script_id) {
  6480. $uploaded_content = $this->getContentByScriptId($script_id);
  6481. if (!$uploaded_content) {
  6482. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6483. }
  6484. } elseif ($bid) {
  6485. $uploaded_content = $this->getContentByBid($bid);
  6486. if (!$uploaded_content) {
  6487. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6488. }
  6489. } elseif ($content) {
  6490. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6491. }
  6492. // elseif ($prompt) {
  6493. // $uploaded_content = filterContent($prompt);
  6494. // }
  6495. else {
  6496. $uploaded_content = '';
  6497. }
  6498. $input_art_style = getProp($anime, 'art_style');
  6499. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6500. // 美术风格
  6501. if (!$mappedArtStyle) {
  6502. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6503. }else {
  6504. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6505. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6506. }else {
  6507. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6508. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6509. }
  6510. }
  6511. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6512. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6513. // 强制要求:
  6514. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6515. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6516. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6517. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6518. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6519. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6520. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6521. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6522. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6523. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6524. // - 分镜要和场景列表、人物主体保持一致\n
  6525. // 普通要求:
  6526. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6527. // {$role_demo}
  6528. // {$scene_demo}
  6529. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6530. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6531. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6532. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6533. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6534. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6535. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6536. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6537. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6538. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6539. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6540. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6541. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6542. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6543. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6544. // 5.$mappedArtStyle_prompt\n\n
  6545. // 示例格式:\n
  6546. // 第1集:隐形的守护者
  6547. // ###故事梗概
  6548. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6549. // ###美术风格
  6550. // 基础画风风格词:韩漫二次元
  6551. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6552. // ###主体列表
  6553. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6554. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6555. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6556. // ###场景列表
  6557. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6558. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6559. // 无人物。}
  6560. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6561. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6562. // 无人物。}
  6563. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6564. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6565. // 无人物。}
  6566. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6567. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6568. // 无人物。}
  6569. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6570. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6571. // 无人物。}
  6572. // ###分镜剧本
  6573. // ##第1幕:徐家老旧厨房 白天 室内
  6574. // 分镜1
  6575. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6576. // 场景:徐家老旧厨房
  6577. // 构图设计:全景,低角度仰视
  6578. // 运镜调度:手持拍摄
  6579. // 配音角色:旁白
  6580. // 出镜角色:许芸-校服装、徐母
  6581. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6582. // 画面类型:普通画面
  6583. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6584. // 分镜2
  6585. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6586. // 场景:徐家老旧厨房
  6587. // 构图设计:近景,徐母面部特写
  6588. // 运镜调度:固定镜头
  6589. // 配音角色:徐母
  6590. // 出镜角色:徐母
  6591. // 台词内容:问我夜不归宿死哪儿去了。
  6592. // 画面类型:对口型
  6593. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6594. // ##第2幕:徐家简陋客厅 黄昏 室内
  6595. // 分镜3
  6596. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6597. // 场景:徐家简陋客厅
  6598. // 构图设计:全景,景深虚化
  6599. // 运镜调度:固定镜头
  6600. // 配音角色:旁白
  6601. // 出镜角色:无
  6602. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6603. // 画面类型:普通画面
  6604. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6605. // 分镜4
  6606. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6607. // 场景:徐家简陋客厅
  6608. // 构图设计:特写,火车票
  6609. // 运镜调度:固定镜头
  6610. // 配音角色:旁白
  6611. // 出镜角色:无
  6612. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6613. // 画面类型:普通画面
  6614. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6615. // \n\n";
  6616. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6617. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6618. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6619. 普通要求:
  6620. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6621. {$role_demo}
  6622. {$scene_demo}
  6623. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6624. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6625. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6626. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6627. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6628. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6629. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6630. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6631. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6632. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6633. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6634. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6635. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6636. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6637. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6638. 5.$mappedArtStyle_prompt
  6639. 6.《情绪-视听语言映射表》:
  6640. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6641. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6642. -----|---------|------------|----------------
  6643. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6644. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6645. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6646. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6647. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6648. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6649. -----|---------|------------|----------------
  6650. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6651. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6652. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6653. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6654. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6655. --------|---------|--------------|-------------
  6656. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6657. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6658. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6659. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6660. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6661. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6662. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6663. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6664. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6665. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6666. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6667. -----|---------|------------|------------
  6668. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6669. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6670. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6671. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6672. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6673. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6674. --------|---------|--------------|----------
  6675. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6676. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6677. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6678. 6.6 声音设计与潜意识影响 (Soundscape)
  6679. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6680. -----|---------|------------|------------------
  6681. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6682. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6683. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6684. 理论基石:
  6685. - The Five C's of Cinematography by Joseph V. Mascelli
  6686. - Film Art: An Introduction by David Bordwell
  6687. - Sight, Sound, Motion by Herbert Zettl
  6688. - Notes on the Cinematograph by Robert Bresson
  6689. \n\n
  6690. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6691. 示例格式:\n
  6692. 第1集:隐形的守护者
  6693. ###故事梗概
  6694. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6695. ###美术风格
  6696. 基础画风风格词:韩漫二次元
  6697. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6698. ###主体列表
  6699. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6700. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6701. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6702. ###场景列表
  6703. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6704. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6705. 无人物。}
  6706. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6707. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6708. 无人物。}
  6709. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6710. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6711. 无人物。}
  6712. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6713. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6714. 无人物。}
  6715. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6716. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6717. 无人物。}
  6718. ###分镜剧本
  6719. ##第1幕:徐家老旧厨房 白天 室内
  6720. 分镜1
  6721. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6722. 场景:徐家老旧厨房
  6723. 构图设计:全景,低角度仰视
  6724. 运镜调度:手持拍摄
  6725. 配音角色:旁白
  6726. 出镜角色:许芸-校服装、徐母
  6727. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6728. 画面类型:普通画面
  6729. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6730. 分镜2
  6731. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6732. 场景:徐家老旧厨房
  6733. 构图设计:近景,徐母面部特写
  6734. 运镜调度:固定镜头
  6735. 配音角色:徐母
  6736. 出镜角色:徐母
  6737. 台词内容:问我夜不归宿死哪儿去了。
  6738. 画面类型:对口型
  6739. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6740. ##第2幕:徐家简陋客厅 黄昏 室内
  6741. 分镜3
  6742. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6743. 场景:徐家简陋客厅
  6744. 构图设计:全景,景深虚化
  6745. 运镜调度:固定镜头
  6746. 配音角色:旁白
  6747. 出镜角色:无
  6748. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6749. 画面类型:普通画面
  6750. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6751. 分镜4
  6752. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6753. 场景:徐家简陋客厅
  6754. 构图设计:特写,火车票
  6755. 运镜调度:固定镜头
  6756. 配音角色:旁白
  6757. 出镜角色:无
  6758. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6759. 画面类型:普通画面
  6760. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6761. \n\n";
  6762. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6763. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  6764. $is_regenerate_version = true;
  6765. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6766. $prompt = $origin_prompt;
  6767. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6768. // 获取章节内容
  6769. $full_content = getProp($anime, 'content');
  6770. if ($uploaded_content) {
  6771. $full_content = $uploaded_content;
  6772. }
  6773. // 根据章节内容拆分章节
  6774. $chapters = splitContent($full_content);
  6775. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6776. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6777. $messages = [];
  6778. if ($prompt == '确认分镜大纲') {
  6779. // 暂时保留
  6780. $content = $chapter_content;
  6781. if ($is_single) $content = $full_content; // 单剧集使用全文
  6782. if (!$content) {
  6783. Utils::throwError('20003:章节内容无法获取,请确认');
  6784. }
  6785. $question = $is_single
  6786. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6787. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6788. // 构建消息
  6789. $messages[] =
  6790. [
  6791. 'role' => 'user',
  6792. 'content' => $question
  6793. ];
  6794. }else if ($prompt == '继续策划下一集') {
  6795. if ($is_single) {
  6796. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6797. }
  6798. $content = $chapter_content;
  6799. if (!$content) {
  6800. Utils::throwError('20003:章节内容无法获取,请确认');
  6801. }
  6802. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6803. // 获取上一集最后记录
  6804. $prev_sequence = $episode_number - 1;
  6805. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6806. // 构建消息
  6807. $messages[] =
  6808. [
  6809. 'role' => 'user',
  6810. 'content' => $question
  6811. ];
  6812. }else {
  6813. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6814. if (!$content) {
  6815. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6816. }
  6817. if (!$content) {
  6818. Utils::throwError('20003:章节内容无法获取,请确认');
  6819. }
  6820. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6821. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6822. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6823. if ($origin_prompt) {
  6824. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6825. }
  6826. $messages[] =
  6827. [
  6828. 'role' => 'user',
  6829. 'content' => $question
  6830. ];
  6831. }
  6832. // 处理文本模型
  6833. $model = getProp($data, 'model');
  6834. if (!$model) {
  6835. // 用户没有输入,从anime表获取
  6836. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6837. $model = getProp($anime, 'model');
  6838. if (!$model) {
  6839. // anime表也没有,使用默认值
  6840. $model = 'doubao-seed-2-0-mini-260215';
  6841. }
  6842. }
  6843. // 验证模型是否在可用模型表中
  6844. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6845. $model = 'doubao-seed-2-0-mini-260215';
  6846. }
  6847. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6848. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6849. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6850. if ($model === 'deepseek-chat') {
  6851. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6852. $model = 'deepseek-v4-flash';
  6853. $thinkingMode = 'disabled';
  6854. } elseif ($model === 'deepseek-reasoner') {
  6855. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6856. $model = 'deepseek-v4-flash';
  6857. $thinkingMode = 'enabled';
  6858. }
  6859. $post_data = [
  6860. 'model' => $model,
  6861. 'messages' => $messages,
  6862. // 'max_tokens' => 8192,
  6863. 'temperature' => 0.2,
  6864. 'frequency_penalty' => 0,
  6865. 'presence_penalty' => 0,
  6866. 'response_format' => ['type' => 'text'],
  6867. 'thinking' => ['type' => $thinkingMode],
  6868. 'stream' => true // 启用流式输出
  6869. ];
  6870. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6871. // 根据模型类型选择调用方法
  6872. $fullContent = '';
  6873. $fullReasoningContent = '';
  6874. $usage = [];
  6875. try {
  6876. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6877. // DeepSeek 官方模型使用 DeepSeek API
  6878. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6879. } else if (in_array($model, $this->gpt_text_models)) {
  6880. // GPT-5.4 模型使用 TokenRouter API
  6881. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6882. } else if (in_array($model, $this->gemini_text_models)) {
  6883. // Gemini 模型使用 Gemini API
  6884. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6885. } else {
  6886. // 其他模型使用火山引擎API
  6887. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6888. }
  6889. // 验证返回值类型
  6890. if (!is_iterable($streamGenerator)) {
  6891. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6892. dLog('deepseek')->error('chat流式生成器无效', [
  6893. 'generator_type' => $errorType,
  6894. 'model' => $model,
  6895. 'anime_id' => $anime_id,
  6896. 'episode_number' => $episode_number
  6897. ]);
  6898. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6899. 'type' => $errorType,
  6900. 'model' => $model
  6901. ]);
  6902. yield [
  6903. 'type' => 'error',
  6904. 'episode' => [],
  6905. 'answer' => '',
  6906. 'reasoning' => '',
  6907. 'usage' => [],
  6908. 'error' => '接口返回数据异常,请重新请求'
  6909. ];
  6910. return;
  6911. }
  6912. // 处理流式输出
  6913. foreach ($streamGenerator as $chunk) {
  6914. if (isset($chunk['type'])) {
  6915. if ($chunk['type'] === 'done') {
  6916. // 最终结果
  6917. $fullContent = $chunk['full_content'];
  6918. $fullReasoningContent = $chunk['full_reasoning'];
  6919. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6920. } else {
  6921. // 逐块yield数据
  6922. yield $chunk;
  6923. }
  6924. }
  6925. }
  6926. } catch (\Exception $e) {
  6927. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6928. 'model' => $model,
  6929. 'anime_id' => $anime_id,
  6930. 'episode_number' => $episode_number,
  6931. 'trace' => $e->getTraceAsString()
  6932. ]);
  6933. logDB('deepseek', 'error', 'chat流式处理失败', [
  6934. 'error' => $e->getMessage(),
  6935. 'model' => $model
  6936. ]);
  6937. yield [
  6938. 'type' => 'error',
  6939. 'episode' => [],
  6940. 'answer' => '',
  6941. 'reasoning' => '',
  6942. 'usage' => [],
  6943. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6944. ];
  6945. return;
  6946. }
  6947. dLog('deepseek')->info('完整内容: '.$fullContent);
  6948. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6949. // 处理完整内容并返回最终结果
  6950. $episode_arr = handleEpisodeContent($fullContent);
  6951. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6952. if (empty($episode_arr['acts'])) {
  6953. // 未生成剧本相关内容,保存对话记录并返回提示
  6954. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6955. try {
  6956. $now = date('Y-m-d H:i:s');
  6957. // 保存对话记录
  6958. $records = [
  6959. [
  6960. 'uid' => $uid,
  6961. 'anime_id' => $anime_id,
  6962. 'sequence' => $episode_number,
  6963. 'role' => 'user',
  6964. 'content' => $prompt,
  6965. 'created_at' => $now,
  6966. 'updated_at' => $now
  6967. ],
  6968. [
  6969. 'uid' => $uid,
  6970. 'anime_id' => $anime_id,
  6971. 'sequence' => $episode_number,
  6972. 'role' => 'assistant',
  6973. 'content' => $fullContent,
  6974. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6975. 'created_at' => $now,
  6976. 'updated_at' => $now
  6977. ]
  6978. ];
  6979. DB::table('mp_anime_records')->insert($records);
  6980. } catch (\Exception $e) {
  6981. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6982. }
  6983. yield [
  6984. 'type' => 'done',
  6985. 'episode' => [],
  6986. 'answer' => $fullContent,
  6987. 'reasoning' => $fullReasoningContent,
  6988. 'usage' => $usage,
  6989. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6990. ];
  6991. return;
  6992. }
  6993. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6994. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6995. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6996. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6997. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6998. $existing_props = is_array($existing_props) ? $existing_props : [];
  6999. $now = date('Y-m-d H:i:s');
  7000. try {
  7001. DB::beginTransaction();
  7002. $saveResult = $this->saveEpisodeVersionData(
  7003. $anime_id,
  7004. $episode_number,
  7005. $episode_arr,
  7006. $existing_roles,
  7007. $existing_scenes,
  7008. $existing_props,
  7009. $current_episode,
  7010. $base_episode,
  7011. $is_regenerate_version,
  7012. $content,
  7013. $now
  7014. );
  7015. $episode = $saveResult['episode'];
  7016. $episode_id = $saveResult['episode_id'];
  7017. $merged_roles = $saveResult['merged_roles'];
  7018. $merged_scenes = $saveResult['merged_scenes'];
  7019. $merged_props = $saveResult['merged_props'];
  7020. $record_content = $origin_prompt;
  7021. if ($uploaded_content !== '') {
  7022. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7023. }
  7024. $records = [
  7025. [
  7026. 'uid' => $uid,
  7027. 'anime_id' => $anime_id,
  7028. 'role' => 'user',
  7029. 'content' => $record_content,
  7030. 'sequence' => $episode_number,
  7031. 'episode_id' => $episode_id,
  7032. 'created_at' => $now,
  7033. 'updated_at' => $now
  7034. ],
  7035. [
  7036. 'uid' => $uid,
  7037. 'anime_id' => $anime_id,
  7038. 'role' => 'assistant',
  7039. 'content' => $fullContent,
  7040. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7041. 'sequence' => $episode_number,
  7042. 'episode_id' => $episode_id,
  7043. 'created_at' => $now,
  7044. 'updated_at' => $now
  7045. ]
  7046. ];
  7047. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7048. if (!$boolen4) {
  7049. Utils::throwError('20003:对话记录保存失败');
  7050. }
  7051. // 保存模型和内容到anime表
  7052. $update_anime_data = [
  7053. 'model' => $model,
  7054. 'updated_at' => $now
  7055. ];
  7056. if ($uploaded_content) {
  7057. $update_anime_data['content'] = $uploaded_content;
  7058. }
  7059. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7060. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7061. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7062. 'anime_id' => $anime_id,
  7063. 'episode_number' => $episode_number,
  7064. 'model' => $model,
  7065. 'source' => 'chat',
  7066. ]);
  7067. }catch (\Exception $e) {
  7068. DB::rollBack();
  7069. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7070. yield [
  7071. 'type' => 'done',
  7072. 'answer' => $fullContent,
  7073. 'reasoning' => $fullReasoningContent,
  7074. 'usage' => $usage,
  7075. 'error' => $e->getMessage(),
  7076. ];
  7077. return;
  7078. }
  7079. DB::commit();
  7080. if ($is_global_generate_pics) {
  7081. // // 批量生成全局角色图片
  7082. // $this->batchSetGlobalRoleImg([
  7083. // 'anime_id' => $anime_id,
  7084. // ], true);
  7085. // // 批量生成全局场景图片
  7086. // $this->batchSetGlobalSceneImg([
  7087. // 'anime_id' => $anime_id,
  7088. // ], true);
  7089. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7090. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7091. }
  7092. $episode['episode_id'] = $episode_id;
  7093. $episode['roles'] = $merged_roles;
  7094. $episode['scenes'] = $merged_scenes;
  7095. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7096. yield [
  7097. 'type' => 'done',
  7098. 'episode' => $episode,
  7099. 'answer' => $fullContent,
  7100. 'reasoning' => $fullReasoningContent,
  7101. 'usage' => $usage
  7102. ];
  7103. }
  7104. public function addChatForAce($data) {
  7105. $uid = Site::getUid();
  7106. $anime_id = getProp($data, 'anime_id');
  7107. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7108. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7109. if (!$anime) Utils::throwError('20003:对话不存在');
  7110. $file = getProp($data, 'file');
  7111. $content = getProp($data, 'content', '');
  7112. $bid = getProp($data, 'bid', 0);
  7113. $script_id = getProp($data, 'script_id', 0);
  7114. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7115. $prompt = getProp($data, 'prompt');
  7116. $is_multi = getProp($anime, 'is_multi');
  7117. $is_single = (int)$is_multi !== 1;
  7118. // 积分余额预检(仅单剧集模式收费)
  7119. if ($is_single) {
  7120. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7121. }
  7122. $extra_products = getProp($data, 'products', []);
  7123. if (!$extra_products) {
  7124. $extra_products = getProp($anime, 'extra_products');
  7125. if ($extra_products) {
  7126. $extra_products = json_decode($extra_products, true);
  7127. }else {
  7128. $extra_products = [];
  7129. }
  7130. }else {
  7131. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7132. }
  7133. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7134. $anime_script_id = getProp($anime, 'script_id');
  7135. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7136. $cpid = Site::getCpid();
  7137. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7138. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7139. ->where('mapping.script_id', $anime_script_id)
  7140. ->where('product.cpid', $cpid)
  7141. ->where('product.is_deleted', 0);
  7142. $mappings = $script_products_mappings->select(
  7143. 'mapping.product_id',
  7144. 'mapping.episode_number',
  7145. 'product.product_name',
  7146. 'product.type',
  7147. 'product.product',
  7148. 'product.pic_prompt',
  7149. 'product.url',
  7150. 'product.pic_task_id',
  7151. 'product.pic_task_status',
  7152. 'product.three_view_image_url'
  7153. )
  7154. ->get();
  7155. // 按 product_id 分组,合并 episode_number
  7156. $productMap = [];
  7157. foreach ($mappings as $item) {
  7158. $product_id = $item->product_id;
  7159. $product_name = $item->product_name;
  7160. // 处理product_name两边的符号
  7161. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7162. if (!isset($productMap[$product_id])) {
  7163. $productMap[$product_id] = [
  7164. 'product_id' => $product_id,
  7165. 'product_name' => $product_name,
  7166. 'type' => (int)$item->type,
  7167. 'product' => (int)$item->product,
  7168. 'pic_prompt' => $item->pic_prompt,
  7169. 'url' => $item->url,
  7170. 'pic_task_id' => $item->pic_task_id,
  7171. 'pic_task_status' => $item->pic_task_status,
  7172. 'episode_numbers' => [],
  7173. ];
  7174. }
  7175. // 添加 episode_number(去重)
  7176. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7177. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7178. }
  7179. }
  7180. // 将查询到的剧本资产合并到extra_products中
  7181. // 先构建extra_products的索引(以product_id为key,用于去重)
  7182. $extraProductsMap = [];
  7183. foreach ($extra_products as $item) {
  7184. $key = getProp($item, 'product_id');
  7185. if ($key) {
  7186. $extraProductsMap[$key] = $item;
  7187. }
  7188. }
  7189. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7190. foreach ($productMap as $product) {
  7191. $product_id = $product['product_id'];
  7192. // 如果不存在则添加(不带episode_number信息)
  7193. if (!isset($extraProductsMap[$product_id])) {
  7194. $extraProductsMap[$product_id] = [
  7195. 'product_id' => $product['product_id'],
  7196. 'product_name' => $product['product_name'],
  7197. 'type' => $product['type'],
  7198. 'product' => $product['product'],
  7199. 'pic_prompt' => $product['pic_prompt'],
  7200. 'url' => $product['url'],
  7201. 'pic_task_id' => $product['pic_task_id'],
  7202. 'pic_task_status' => $product['pic_task_status'],
  7203. ];
  7204. }
  7205. }
  7206. // 重新赋值给extra_products
  7207. $extra_products = array_values($extraProductsMap);
  7208. }
  7209. $user_anime_name = getProp($anime, 'anime_name');
  7210. // 处理提示词
  7211. if ($prompt && $extra_products) {
  7212. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7213. foreach($extra_products as $item) {
  7214. $product_name = getProp($item, 'product_name');
  7215. if ($product_name) {
  7216. // 替换 {product_name} 为 product_name
  7217. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7218. }
  7219. }
  7220. }
  7221. // 处理文本模型
  7222. $model = getProp($data, 'model');
  7223. if (!$model) {
  7224. // 用户没有输入,从anime表获取
  7225. $model = getProp($anime, 'model');
  7226. if (!$model) {
  7227. // anime表也没有,使用默认值
  7228. $model = 'deepseek-v4-pro';
  7229. }
  7230. }
  7231. // 验证模型是否在可用模型表中
  7232. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7233. $model = 'deepseek-v4-pro';
  7234. }
  7235. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7236. if ($prompt) {
  7237. $question .= "本次修改要求如下:\n{$prompt}";
  7238. }
  7239. // if (!$file && !$content && !$bid) {
  7240. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7241. // }
  7242. // 提取文件内容
  7243. if ($file) {
  7244. $content = $this->extractFileContent($file);
  7245. if (!$content) {
  7246. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7247. }
  7248. } elseif ($script_id) {
  7249. $content = $this->getContentByScriptId($script_id);
  7250. if (!$content) {
  7251. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7252. }
  7253. } elseif ($bid) {
  7254. $content = $this->getContentByBid($bid);
  7255. if (!$content) {
  7256. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7257. }
  7258. } elseif ($content) {
  7259. $content = filterContent($content);
  7260. } else {
  7261. $content = getProp($anime, 'content');
  7262. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7263. $need_generate_content = true;
  7264. }
  7265. }
  7266. // 美术风格
  7267. $input_art_style = getProp($data, 'art_style');
  7268. if (!$input_art_style) {
  7269. $mappedArtStyle = getProp($anime, 'art_style');
  7270. }else {
  7271. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7272. }
  7273. // 判断是否需要生成原文内容
  7274. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7275. // 如果需要生成原文内容,添加额外的要求
  7276. $content_generation_requirement = $need_generate_content
  7277. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7278. : "";
  7279. // 美术风格
  7280. if (!$mappedArtStyle) {
  7281. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7282. }else {
  7283. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7284. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7285. }else {
  7286. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7287. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7288. }
  7289. }
  7290. // 构建主体、场景和道具提示词
  7291. $extra_role_prompt = "\n";
  7292. $extra_scene_prompt = "\n";
  7293. $extra_prop_prompt = "\n";
  7294. $ref_products = []; // 参考资产
  7295. if ($extra_products) {
  7296. foreach($extra_products as $item) {
  7297. $product = getProp($item, 'product');
  7298. $product_name = getProp($item, 'product_name');
  7299. if ($product_name == '旁白') continue;
  7300. $ref_products[$product_name] = $item;
  7301. $pic_prompt = getProp($item, 'pic_prompt');
  7302. if ((int)$product === 1) {
  7303. // 拼接角色信息
  7304. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7305. } elseif ((int)$product === 2) {
  7306. // 拼接场景信息
  7307. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7308. } elseif ((int)$product === 3) {
  7309. // 拼接道具信息
  7310. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7311. }
  7312. }
  7313. // 优化提示词,融入剧本
  7314. if (!empty(trim($extra_role_prompt))) {
  7315. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7316. }
  7317. if (!empty(trim($extra_scene_prompt))) {
  7318. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7319. }
  7320. if (!empty(trim($extra_prop_prompt))) {
  7321. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7322. }
  7323. }
  7324. if ($anime_script_id && $is_single) {
  7325. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7326. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7327. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7328. }else {
  7329. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7330. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7331. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7332. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7333. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7334. {$extra_role_prompt}";
  7335. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7336. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7337. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7338. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7339. {$extra_scene_prompt}";
  7340. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7341. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7342. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7343. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7344. {$extra_prop_prompt}";
  7345. }
  7346. $systemPrompt = $is_single
  7347. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7348. 强制要求:
  7349. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7350. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7351. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7352. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7353. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7354. 普通要求:
  7355. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7356. $role_demo
  7357. $scene_demo
  7358. $prop_demo
  7359. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7360. 5.1片段分割逻辑(优先级从高到低):
  7361. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7362. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7363. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7364. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7365. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7366. - 片段数量格式为: 片段数量:8
  7367. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7368. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7369. 5.3分镜结构:每个分镜包含以下字段:
  7370. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7371. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7372. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7373. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7374. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7375. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7376. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7377. - 运镜:场景+画面描述+运镜
  7378. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7379. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7380. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7381. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7382. 6.{$mappedArtStyle_prompt}\n\n
  7383. 示例如下:\n
  7384. ###剧本名:西昆仑
  7385. ###故事梗概
  7386. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7387. ###剧本亮点
  7388. 亮点1:绝境奇药,生死一线
  7389. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7390. 亮点2:结拜兄妹,化解尴尬
  7391. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7392. 亮点3:纤发夺命,情愫暗涌
  7393. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7394. ###人物关系
  7395. 阿雪与梁萧之间存在兄妹之情。
  7396. ###核心矛盾
  7397. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7398. ###主体列表
  7399. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7400. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7401. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7402. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7403. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7404. 全景,正面拍摄,青年女性,亚洲人。
  7405. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7406. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7407. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7408. ###美术风格
  7409. 基础画风风格词:厚涂古风
  7410. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7411. ###场景列表
  7412. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7413. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7414. 无人物。}
  7415. ###分段剧本
  7416. 片段数量:8
  7417. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7418. ##片段1
  7419. 时长:12s
  7420. 分镜1
  7421. 出场角色:刀疤脸
  7422. 场景:边境小镇街道
  7423. 出场道具:酒杯-高脚杯
  7424. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7425. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7426. 配音台词:
  7427. 背景音效:
  7428. 分镜2
  7429. 出场角色:刀疤脸
  7430. 场景:悦来酒馆
  7431. 出场道具:酒杯-高脚杯
  7432. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7433. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7434. 配音台词:
  7435. 背景音效:
  7436. 分镜3
  7437. 出场角色:刀疤脸
  7438. 场景:悦来酒馆
  7439. 出场道具:酒杯-高脚杯
  7440. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7441. 运镜:从中景推向令牌特写。
  7442. 配音台词:
  7443. 背景音效:
  7444. 分镜4
  7445. 出场角色:刀疤脸
  7446. 场景:悦来酒馆
  7447. 出场道具:酒杯-高脚杯
  7448. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7449. 运镜:极速推向酒水溅起的瞬间。
  7450. 配音台词:
  7451. 背景音效:
  7452. 分镜5
  7453. 出场角色:刀疤脸
  7454. 场景:悦来酒馆
  7455. 出场道具:酒杯-高脚杯
  7456. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7457. 运镜:固定机位,利用倾斜构图制造压迫感。
  7458. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7459. 背景音效:
  7460. \n\n"
  7461. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7462. 强制要求:\n
  7463. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7464. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7465. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7466. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7467. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7468. 普通要求:\n
  7469. 1.剧本名(必须生成)必须与文档内容高度相关
  7470. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7471. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7472. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7473. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7474. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7475. {$extra_role_prompt}
  7476. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7477. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7478. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7479. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7480. {$extra_scene_prompt}
  7481. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7482. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7483. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7484. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7485. {$extra_prop_prompt}
  7486. 5.{$mappedArtStyle_prompt}\n\n
  7487. 示例如下:\n
  7488. ###剧本名:西昆仑
  7489. ###故事梗概
  7490. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7491. ###剧本亮点
  7492. 亮点1:绝境奇药,生死一线
  7493. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7494. 亮点2:结拜兄妹,化解尴尬
  7495. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7496. 亮点3:纤发夺命,情愫暗涌
  7497. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7498. ###人物关系
  7499. 阿雪与梁萧之间存在兄妹之情。
  7500. ###核心矛盾
  7501. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7502. ###主体列表
  7503. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7504. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7505. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7506. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7507. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7508. 全景,正面拍摄,青年女性,亚洲人。
  7509. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7510. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7511. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7512. ###美术风格
  7513. 基础画风风格词:厚涂古风
  7514. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7515. ###场景列表
  7516. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7517. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7518. 无人物。}
  7519. ###道具列表
  7520. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7521. // 构建消息
  7522. $messages = [
  7523. [
  7524. 'role' => 'system',
  7525. 'content' => $systemPrompt
  7526. ],
  7527. [
  7528. 'role' => 'user',
  7529. 'content' => "以下是文档内容:
  7530. {$content}
  7531. 用户问题:
  7532. {$question}"
  7533. ]
  7534. ];
  7535. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7536. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7537. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7538. if ($model === 'deepseek-chat') {
  7539. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7540. $model = 'deepseek-v4-flash';
  7541. $thinkingMode = 'disabled';
  7542. } elseif ($model === 'deepseek-reasoner') {
  7543. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7544. $model = 'deepseek-v4-flash';
  7545. $thinkingMode = 'enabled';
  7546. }
  7547. $post_data = [
  7548. 'model' => $model,
  7549. 'messages' => $messages,
  7550. // 'max_tokens' => 8192,
  7551. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7552. 'frequency_penalty' => 0,
  7553. 'presence_penalty' => 0,
  7554. 'response_format' => ['type' => 'text'],
  7555. 'thinking' => ['type'=>$thinkingMode],
  7556. 'stream' => true // 启用流式输出
  7557. ];
  7558. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7559. // 根据模型类型选择调用方法
  7560. $fullContent = '';
  7561. $fullReasoningContent = '';
  7562. $usage = [];
  7563. try {
  7564. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7565. // DeepSeek 官方模型使用 DeepSeek API
  7566. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7567. } else if (in_array($model, $this->gpt_text_models)) {
  7568. // GPT-5.4 模型使用 TokenRouter API
  7569. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7570. } else if (in_array($model, $this->gemini_text_models)) {
  7571. // Gemini 模型使用 Gemini API
  7572. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7573. } else {
  7574. // 其他模型使用火山引擎API
  7575. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7576. }
  7577. // 验证返回值类型
  7578. if (!is_iterable($streamGenerator)) {
  7579. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7580. dLog('deepseek')->error('addChat流式生成器无效', [
  7581. 'generator_type' => $errorType,
  7582. 'model' => $model,
  7583. 'anime_id' => $anime_id
  7584. ]);
  7585. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7586. 'type' => $errorType,
  7587. 'model' => $model
  7588. ]);
  7589. yield [
  7590. 'type' => 'error',
  7591. 'script' => [],
  7592. 'episode' => [],
  7593. 'answer' => '',
  7594. 'reasoning' => '',
  7595. 'usage' => [],
  7596. 'error' => '接口返回数据异常,请重新请求'
  7597. ];
  7598. return;
  7599. }
  7600. // 处理流式输出
  7601. foreach ($streamGenerator as $chunk) {
  7602. if (isset($chunk['type'])) {
  7603. if ($chunk['type'] === 'done') {
  7604. // 最终结果
  7605. $fullContent = $chunk['full_content'];
  7606. $fullReasoningContent = $chunk['full_reasoning'];
  7607. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7608. } else {
  7609. // 逐块yield数据
  7610. yield $chunk;
  7611. }
  7612. }
  7613. }
  7614. } catch (\Exception $e) {
  7615. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7616. 'model' => $model,
  7617. 'anime_id' => $anime_id,
  7618. 'trace' => $e->getTraceAsString()
  7619. ]);
  7620. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7621. 'error' => $e->getMessage(),
  7622. 'model' => $model
  7623. ]);
  7624. yield [
  7625. 'type' => 'error',
  7626. 'script' => [],
  7627. 'episode' => [],
  7628. 'answer' => '',
  7629. 'reasoning' => '',
  7630. 'usage' => [],
  7631. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7632. ];
  7633. return;
  7634. }
  7635. dLog('deepseek')->info('完整内容: '.$fullContent);
  7636. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7637. // 处理完整内容并返回最终结果
  7638. $script_arr = [];
  7639. if ($fullContent) {
  7640. $script_arr = handleScriptContentForAce($fullContent);
  7641. dLog('deepseek')->info('解析内容', $script_arr);
  7642. logDB('deepseek', 'info', '解析内容', $script_arr);
  7643. }
  7644. if (empty($script_arr['roles'])) {
  7645. // 未生成剧本相关内容,保存对话记录并返回提示
  7646. dLog('deepseek')->info('未生成剧本相关的内容');
  7647. try {
  7648. DB::beginTransaction();
  7649. $now = date('Y-m-d H:i:s');
  7650. // 保存对话记录
  7651. $records = [
  7652. [
  7653. 'uid' => $uid,
  7654. 'anime_id' => $anime_id,
  7655. 'sequence' => 0,
  7656. 'role' => 'user',
  7657. 'content' => $prompt,
  7658. 'created_at' => $now,
  7659. 'updated_at' => $now
  7660. ],
  7661. [
  7662. 'uid' => $uid,
  7663. 'anime_id' => $anime_id,
  7664. 'sequence' => 0,
  7665. 'role' => 'assistant',
  7666. // 'content' => $fullContent,
  7667. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7668. 'created_at' => $now,
  7669. 'updated_at' => $now
  7670. ]
  7671. ];
  7672. DB::table('mp_anime_records')->insert($records);
  7673. DB::commit();
  7674. } catch (\Exception $e) {
  7675. DB::rollBack();
  7676. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7677. }
  7678. yield [
  7679. 'type' => 'done',
  7680. 'script' => [],
  7681. 'episode' => [],
  7682. 'answer' => $fullContent,
  7683. 'reasoning' => $fullReasoningContent,
  7684. 'usage' => $usage,
  7685. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7686. ];
  7687. return;
  7688. }
  7689. // 如果需要生成原文内容,从script_arr中提取
  7690. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7691. $content = $script_arr['content'];
  7692. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7693. if (!$content) {
  7694. yield [
  7695. 'type' => 'done',
  7696. 'script' => [],
  7697. 'episode' => [],
  7698. 'answer' => $fullContent,
  7699. 'reasoning' => $fullReasoningContent,
  7700. 'usage' => $usage,
  7701. 'error' => '未生成剧本内容,请调整提示词再试'
  7702. ];
  7703. return;
  7704. }
  7705. }
  7706. // 替换美术风格
  7707. if ($mappedArtStyle !== '') {
  7708. $script_arr['art_style'] = $mappedArtStyle;
  7709. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7710. }
  7711. // 新建动漫
  7712. if ($user_anime_name == '新剧本策划') {
  7713. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7714. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7715. // if (!$anime_name) {
  7716. // // 未识别到剧本名,保存对话记录并返回提示
  7717. // dLog('deepseek')->info('未能识别到剧本名称');
  7718. // try {
  7719. // DB::beginTransaction();
  7720. // $now = date('Y-m-d H:i:s');
  7721. // // 保存对话记录
  7722. // $records = [
  7723. // [
  7724. // 'uid' => $uid,
  7725. // 'anime_id' => $anime_id,
  7726. // 'sequence' => 0,
  7727. // 'role' => 'user',
  7728. // 'content' => $prompt,
  7729. // 'created_at' => $now,
  7730. // 'updated_at' => $now
  7731. // ],
  7732. // [
  7733. // 'uid' => $uid,
  7734. // 'anime_id' => $anime_id,
  7735. // 'sequence' => 0,
  7736. // 'role' => 'assistant',
  7737. // 'content' => '未能生成剧本名称,请重试',
  7738. // 'created_at' => $now,
  7739. // 'updated_at' => $now
  7740. // ]
  7741. // ];
  7742. // DB::table('mp_anime_records')->insert($records);
  7743. // DB::commit();
  7744. // } catch (\Exception $e) {
  7745. // DB::rollBack();
  7746. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7747. // }
  7748. // yield [
  7749. // 'type' => 'done',
  7750. // 'script' => [],
  7751. // 'episode' => [],
  7752. // 'answer' => $fullContent,
  7753. // 'reasoning' => $fullReasoningContent,
  7754. // 'usage' => $usage,
  7755. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7756. // ];
  7757. // return;
  7758. // }
  7759. // 确认对话名称唯一性
  7760. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7761. $anime_name = $anime_name . '_' . date('YmdHis');
  7762. }
  7763. }else {
  7764. $anime_name = $user_anime_name;
  7765. }
  7766. $table_data = [
  7767. 'user_id' => $uid,
  7768. 'anime_name' => $anime_name,
  7769. 'model' => $model,
  7770. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7771. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7772. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7773. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7774. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7775. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7776. 'art_style_type' => $input_art_style,
  7777. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7778. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7779. 'status' => '解析完成',
  7780. 'content' => $content,
  7781. 'is_multi' => $is_multi,
  7782. 'ace_mode' => $ace_mode,
  7783. 'generate_status' => '待执行',
  7784. 'updated_at' => date('Y-m-d H:i:s')
  7785. ];
  7786. if ($table_data['content']) {
  7787. $chapters = splitContent($table_data['content']);
  7788. $chapter_count = count($chapters);
  7789. if ($chapter_count > 0) {
  7790. $table_data['start_episode_sequence'] = 1;
  7791. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7792. }
  7793. }
  7794. if ($extra_products) {
  7795. $table_data['extra_products'] = json_encode($extra_products, 256);
  7796. }
  7797. // 如果有剧本ID则进行绑定
  7798. if ($script_id) {
  7799. $table_data['script_id'] = $script_id;
  7800. }
  7801. $single_episode = [];
  7802. try {
  7803. DB::beginTransaction();
  7804. $now = date('Y-m-d H:i:s');
  7805. // 更新动漫大纲
  7806. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7807. if (!$boolen) {
  7808. dLog('deepseek')->info('动漫保存失败', $table_data);
  7809. Utils::throwError('20003:动漫保存失败');
  7810. }
  7811. // 保存对话记录
  7812. $records = [
  7813. [
  7814. 'uid' => $uid,
  7815. 'anime_id' => $anime_id,
  7816. 'sequence' => 0,
  7817. 'role' => 'user',
  7818. 'content' => $prompt,
  7819. 'created_at' => date('Y-m-d H:i:s'),
  7820. 'updated_at' => date('Y-m-d H:i:s')
  7821. ],
  7822. [
  7823. 'uid' => $uid,
  7824. 'anime_id' => $anime_id,
  7825. 'sequence' => 0,
  7826. 'role' => 'assistant',
  7827. 'content' => $fullContent,
  7828. 'created_at' => date('Y-m-d H:i:s'),
  7829. 'updated_at' => date('Y-m-d H:i:s')
  7830. ]
  7831. ];
  7832. // 保存对话记录
  7833. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7834. if (!$boolen3) {
  7835. Utils::throwError('20003:对话记录保存失败');
  7836. }
  7837. if ($is_single) {
  7838. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7839. if (empty($episode_arr['acts'])) {
  7840. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7841. }
  7842. $saveResult = $this->saveEpisodeVersionData(
  7843. $anime_id,
  7844. 1,
  7845. $episode_arr,
  7846. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7847. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7848. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7849. null,
  7850. null,
  7851. false,
  7852. $content,
  7853. $now,
  7854. $ref_products
  7855. );
  7856. $single_episode = $saveResult['episode'];
  7857. $episode_id = $saveResult['episode_id'];
  7858. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7859. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7860. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7861. 'props' => json_encode($saveResult['merged_props'], 256),
  7862. 'updated_at' => $now
  7863. ]);
  7864. if ($boolen5 === false) {
  7865. Utils::throwError('20003:单剧集主表资源同步失败');
  7866. }
  7867. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7868. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7869. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7870. $episode_record_content = '确认分镜大纲';
  7871. if ($content !== '') {
  7872. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7873. }
  7874. $episode_records = [
  7875. [
  7876. 'uid' => $uid,
  7877. 'anime_id' => $anime_id,
  7878. 'role' => 'user',
  7879. 'content' => $episode_record_content,
  7880. 'sequence' => 1,
  7881. 'episode_id' => $episode_id,
  7882. 'created_at' => $now,
  7883. 'updated_at' => $now
  7884. ],
  7885. [
  7886. 'uid' => $uid,
  7887. 'anime_id' => $anime_id,
  7888. 'role' => 'assistant',
  7889. 'content' => $fullContent,
  7890. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7891. 'sequence' => 1,
  7892. 'episode_id' => $episode_id,
  7893. 'created_at' => $now,
  7894. 'updated_at' => $now
  7895. ]
  7896. ];
  7897. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7898. if (!$boolen4) {
  7899. Utils::throwError('20003:单剧集分镜记录保存失败');
  7900. }
  7901. }
  7902. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7903. if ($is_single && !empty($single_episode)) {
  7904. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7905. 'anime_id' => $anime_id,
  7906. 'episode_id' => $episode_id ?? 0,
  7907. 'model' => $model,
  7908. 'source' => 'addChatForAce',
  7909. ]);
  7910. }
  7911. }catch (\Exception $e) {
  7912. DB::rollBack();
  7913. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7914. yield [
  7915. 'type' => 'done',
  7916. 'answer' => $fullContent,
  7917. 'reasoning' => $fullReasoningContent,
  7918. 'usage' => $usage,
  7919. 'error' => $e->getMessage(),
  7920. ];
  7921. return;
  7922. }
  7923. DB::commit();
  7924. dLog('deepseek')->info('保存完毕');
  7925. if ($is_single && !empty($single_episode)) {
  7926. // $this->batchSetGlobalRoleImg([
  7927. // 'anime_id' => $anime_id,
  7928. // ]);
  7929. // $this->batchSetGlobalSceneImg([
  7930. // 'anime_id' => $anime_id,
  7931. // ]);
  7932. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7933. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7934. }
  7935. $table_data['anime_id'] = $anime_id;
  7936. $table_data['roles'] = json_decode($table_data['roles'], true);
  7937. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7938. // $table_data['episodes'] = $script_arr['episodes'];
  7939. unset($table_data['created_at']);
  7940. unset($table_data['updated_at']);
  7941. unset($table_data['status']);
  7942. dLog('deepseek')->info('开始返回');
  7943. yield [
  7944. 'type' => 'done',
  7945. 'script' => $table_data,
  7946. 'episode' => $single_episode,
  7947. 'answer' => $fullContent,
  7948. 'reasoning' => $fullReasoningContent,
  7949. 'usage' => $usage
  7950. ];
  7951. }
  7952. public function reGenerateAnimeForAce($data) {
  7953. $uid = Site::getUid();
  7954. $file = getProp($data, 'file');
  7955. $content = getProp($data, 'content', '');
  7956. $bid = getProp($data, 'bid', 0);
  7957. $script_id = getProp($data, 'script_id', 0);
  7958. $anime_id = getProp($data, 'anime_id');
  7959. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7960. if (!$anime) {
  7961. Utils::throwError('20003:该对话不存在');
  7962. }
  7963. $is_multi = getProp($anime, 'is_multi', 1);
  7964. $is_single = (int)$is_multi !== 1;
  7965. // 积分余额预检(仅单剧集模式收费)
  7966. if ($is_single) {
  7967. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7968. }
  7969. $extra_products = getProp($data, 'products', []);
  7970. if (!$extra_products) {
  7971. $extra_products = getProp($anime, 'extra_products');
  7972. if ($extra_products) {
  7973. $extra_products = json_decode($extra_products, true);
  7974. }else {
  7975. $extra_products = [];
  7976. }
  7977. }else {
  7978. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7979. }
  7980. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7981. $anime_script_id = getProp($anime, 'script_id');
  7982. if ($anime_script_id && $is_single) {
  7983. $cpid = Site::getCpid();
  7984. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7985. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7986. ->where('mapping.script_id', $anime_script_id)
  7987. ->where('product.cpid', $cpid)
  7988. ->where('product.is_deleted', 0);
  7989. $mappings = $script_products_mappings->select(
  7990. 'mapping.product_id',
  7991. 'mapping.episode_number',
  7992. 'product.product_name',
  7993. 'product.type',
  7994. 'product.product',
  7995. 'product.pic_prompt',
  7996. 'product.url',
  7997. 'product.pic_task_id',
  7998. 'product.pic_task_status',
  7999. 'product.three_view_image_url'
  8000. )
  8001. ->get();
  8002. // 按 product_id 分组,合并 episode_number
  8003. $productMap = [];
  8004. foreach ($mappings as $item) {
  8005. $product_id = $item->product_id;
  8006. $product_name = $item->product_name;
  8007. // 处理product_name两边的符号
  8008. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8009. if (!isset($productMap[$product_id])) {
  8010. $productMap[$product_id] = [
  8011. 'product_id' => $product_id,
  8012. 'product_name' => $product_name,
  8013. 'type' => (int)$item->type,
  8014. 'product' => (int)$item->product,
  8015. 'pic_prompt' => $item->pic_prompt,
  8016. 'url' => $item->url,
  8017. 'pic_task_id' => $item->pic_task_id,
  8018. 'pic_task_status' => $item->pic_task_status,
  8019. 'episode_numbers' => [],
  8020. ];
  8021. }
  8022. // 添加 episode_number(去重)
  8023. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8024. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8025. }
  8026. }
  8027. // 将查询到的剧本资产合并到extra_products中
  8028. // 先构建extra_products的索引(以product_id为key,用于去重)
  8029. $extraProductsMap = [];
  8030. foreach ($extra_products as $item) {
  8031. $key = getProp($item, 'product_id');
  8032. if ($key) {
  8033. $extraProductsMap[$key] = $item;
  8034. }
  8035. }
  8036. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8037. foreach ($productMap as $product) {
  8038. $product_id = $product['product_id'];
  8039. // 如果不存在则添加(不带episode_number信息)
  8040. if (!isset($extraProductsMap[$product_id])) {
  8041. $extraProductsMap[$product_id] = [
  8042. 'product_id' => $product['product_id'],
  8043. 'product_name' => $product['product_name'],
  8044. 'type' => $product['type'],
  8045. 'product' => $product['product'],
  8046. 'pic_prompt' => $product['pic_prompt'],
  8047. 'url' => $product['url'],
  8048. 'pic_task_id' => $product['pic_task_id'],
  8049. 'pic_task_status' => $product['pic_task_status'],
  8050. ];
  8051. }
  8052. }
  8053. // 重新赋值给extra_products
  8054. $extra_products = array_values($extraProductsMap);
  8055. }
  8056. $user_anime_name = getProp($anime, 'anime_name');
  8057. $prompt = getProp($data, 'prompt');
  8058. // 处理提示词
  8059. if ($prompt && $extra_products) {
  8060. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8061. foreach($extra_products as $item) {
  8062. $product_name = getProp($item, 'product_name');
  8063. if ($product_name) {
  8064. // 替换 {product_name} 为 product_name
  8065. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8066. }
  8067. }
  8068. }
  8069. // 处理文本模型
  8070. $model = getProp($data, 'model');
  8071. if (!$model) {
  8072. // 用户没有输入,从anime表获取
  8073. $model = getProp($anime, 'model');
  8074. if (!$model) {
  8075. // anime表也没有,使用默认值
  8076. $model = 'deepseek-v4-pro';
  8077. }
  8078. }
  8079. // 验证模型是否在可用模型表中
  8080. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8081. $model = 'deepseek-v4-pro';
  8082. }
  8083. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8084. if ($is_single) {
  8085. $episode_exists = DB::table('mp_anime_episodes')
  8086. ->where('anime_id', $anime_id)
  8087. ->where('sequence', 1)
  8088. ->exists();
  8089. if ($episode_exists) {
  8090. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8091. }
  8092. }
  8093. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8094. if ($prompt) {
  8095. $question .= "本次修改要求如下:\n{$prompt}";
  8096. }
  8097. // 提取文件内容
  8098. if ($file) {
  8099. $content = $this->extractFileContent($file);
  8100. if (!$content) {
  8101. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8102. }
  8103. } elseif ($script_id) {
  8104. $content = $this->getContentByScriptId($script_id);
  8105. if (!$content) {
  8106. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8107. }
  8108. } elseif ($bid) {
  8109. $content = $this->getContentByBid($bid);
  8110. if (!$content) {
  8111. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8112. }
  8113. } elseif ($content) {
  8114. $content = filterContent($content);
  8115. }else {
  8116. $content = filterContent(getProp($anime, 'content'));
  8117. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  8118. $need_generate_content = true;
  8119. }
  8120. }
  8121. // 判断是否需要生成原文内容
  8122. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  8123. // 如果需要生成原文内容,添加额外的要求
  8124. $content_generation_requirement = $need_generate_content
  8125. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  8126. : "";
  8127. // 美术风格
  8128. $input_art_style = getProp($data, 'art_style');
  8129. if (!$input_art_style) {
  8130. $mappedArtStyle = getProp($anime, 'art_style');
  8131. }else {
  8132. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8133. }
  8134. if (!$mappedArtStyle) {
  8135. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8136. }else {
  8137. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8138. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8139. }else {
  8140. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8141. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8142. }
  8143. }
  8144. // 构建主体、场景和道具提示词
  8145. $extra_role_prompt = "\n";
  8146. $extra_scene_prompt = "\n";
  8147. $extra_prop_prompt = "\n";
  8148. $ref_products = []; // 参考资产
  8149. if ($extra_products) {
  8150. foreach($extra_products as $item) {
  8151. $product = getProp($item, 'product');
  8152. $product_name = getProp($item, 'product_name');
  8153. if ($product_name == '旁白') continue;
  8154. $ref_products[$product_name] = $item;
  8155. $pic_prompt = getProp($item, 'pic_prompt');
  8156. if ((int)$product === 1) {
  8157. // 拼接角色信息
  8158. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8159. } elseif ((int)$product === 2) {
  8160. // 拼接场景信息
  8161. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8162. } elseif ((int)$product === 3) {
  8163. // 拼接道具信息
  8164. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8165. }
  8166. }
  8167. // 优化提示词,融入剧本
  8168. if (!empty(trim($extra_role_prompt))) {
  8169. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8170. }
  8171. if (!empty(trim($extra_scene_prompt))) {
  8172. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8173. }
  8174. if (!empty(trim($extra_prop_prompt))) {
  8175. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8176. }
  8177. }
  8178. if ($anime_script_id && $is_single) {
  8179. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  8180. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  8181. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  8182. }else {
  8183. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8184. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8185. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8186. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8187. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8188. {$extra_role_prompt}";
  8189. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8190. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8191. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8192. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8193. {$extra_scene_prompt}";
  8194. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8195. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8196. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8197. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8198. {$extra_prop_prompt}";
  8199. }
  8200. $system_message = ['role'=>'system', 'content'=>$is_single
  8201. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  8202. 强制要求:
  8203. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8204. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8205. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8206. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8207. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8208. 普通要求:
  8209. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  8210. $role_demo
  8211. $scene_demo
  8212. $prop_demo
  8213. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8214. 5.1片段分割逻辑(优先级从高到低):
  8215. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8216. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8217. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8218. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8219. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8220. - 片段数量格式为: 片段数量:8
  8221. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8222. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8223. 5.3分镜结构:每个分镜包含以下字段:
  8224. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8225. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8226. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8227. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8228. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8229. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8230. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8231. - 运镜:场景+画面描述+运镜
  8232. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8233. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8234. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8235. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  8236. 6.{$mappedArtStyle_prompt}\n\n
  8237. 示例如下:\n
  8238. ###剧本名:西昆仑
  8239. ###故事梗概
  8240. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8241. ###剧本亮点
  8242. 亮点1:绝境奇药,生死一线
  8243. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8244. 亮点2:结拜兄妹,化解尴尬
  8245. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8246. 亮点3:纤发夺命,情愫暗涌
  8247. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8248. ###人物关系
  8249. 阿雪与梁萧之间存在兄妹之情。
  8250. ###核心矛盾
  8251. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8252. ###主体列表
  8253. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8254. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8255. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8256. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8257. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8258. 全景,正面拍摄,青年女性,亚洲人。
  8259. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8260. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8261. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8262. ###美术风格
  8263. 基础画风风格词:厚涂古风
  8264. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8265. ###场景列表
  8266. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8267. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8268. 无人物。}
  8269. ###分段剧本
  8270. 片段数量:8
  8271. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8272. ##片段1
  8273. 时长:12s
  8274. 分镜1
  8275. 出场角色:刀疤脸
  8276. 场景:边境小镇街道
  8277. 出场道具:酒杯-高脚杯
  8278. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8279. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8280. 配音台词:
  8281. 背景音效:
  8282. 分镜2
  8283. 出场角色:刀疤脸
  8284. 场景:悦来酒馆
  8285. 出场道具:酒杯-高脚杯
  8286. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8287. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8288. 配音台词:
  8289. 背景音效:
  8290. 分镜3
  8291. 出场角色:刀疤脸
  8292. 场景:悦来酒馆
  8293. 出场道具:酒杯-高脚杯
  8294. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8295. 运镜:从中景推向令牌特写。
  8296. 配音台词:
  8297. 背景音效:
  8298. 分镜4
  8299. 出场角色:刀疤脸
  8300. 场景:悦来酒馆
  8301. 出场道具:酒杯-高脚杯
  8302. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8303. 运镜:极速推向酒水溅起的瞬间。
  8304. 配音台词:
  8305. 背景音效:
  8306. 分镜5
  8307. 出场角色:刀疤脸
  8308. 场景:悦来酒馆
  8309. 出场道具:酒杯-高脚杯
  8310. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8311. 运镜:固定机位,利用倾斜构图制造压迫感。
  8312. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8313. 背景音效:
  8314. \n\n"
  8315. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8316. 强制要求:\n
  8317. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8318. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8319. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8320. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8321. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8322. 普通要求:\n
  8323. 1.剧本名(必须生成)必须与文档内容高度相关
  8324. $role_demo
  8325. $scene_demo
  8326. $prop_demo
  8327. 5.{$mappedArtStyle_prompt}\n\n
  8328. 示例如下:\n
  8329. ###剧本名:西昆仑
  8330. ###故事梗概
  8331. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8332. ###剧本亮点
  8333. 亮点1:绝境奇药,生死一线
  8334. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8335. 亮点2:结拜兄妹,化解尴尬
  8336. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8337. 亮点3:纤发夺命,情愫暗涌
  8338. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8339. ###人物关系
  8340. 阿雪与梁萧之间存在兄妹之情。
  8341. ###核心矛盾
  8342. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8343. ###主体列表
  8344. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8345. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8346. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8347. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8348. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8349. 全景,正面拍摄,青年女性,亚洲人。
  8350. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8351. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8352. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8353. ###美术风格
  8354. 基础画风风格词:厚涂古风
  8355. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8356. ###场景列表
  8357. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8358. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8359. 无人物。}
  8360. ###道具列表
  8361. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  8362. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  8363. $episode_count = $this->extractEpisodeNumber($prompt);
  8364. if ((int)getProp($anime, 'is_multi') !== 1) {
  8365. yield [
  8366. 'type' => 'done',
  8367. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  8368. 'reasoning' => '',
  8369. 'usage' => []
  8370. ];
  8371. return;
  8372. }
  8373. if ($episode_count) {
  8374. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  8375. $system_message = [
  8376. 'role' => 'system',
  8377. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8378. 强制要求:\n
  8379. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8380. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8381. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8382. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8383. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8384. 普通要求:\n
  8385. 1.<故事梗概>控制在200-300字左右
  8386. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8387. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8388. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8389. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8390. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8391. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8392. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8393. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8394. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8395. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8396. 示例如下:\n
  8397. ###剧本名:西昆仑
  8398. ###故事梗概
  8399. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8400. ###剧本亮点
  8401. 亮点1:绝境奇药,生死一线
  8402. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8403. 亮点2:结拜兄妹,化解尴尬
  8404. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8405. 亮点3:纤发夺命,情愫暗涌
  8406. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8407. ###人物关系
  8408. 阿雪与梁萧之间存在兄妹之情。
  8409. ###核心矛盾
  8410. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8411. ###主体列表
  8412. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8413. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8414. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8415. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8416. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8417. 全景,正面拍摄,青年女性,亚洲人。
  8418. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8419. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8420. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8421. ###美术风格
  8422. 基础画风风格词:厚涂古风
  8423. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8424. ###场景列表
  8425. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8426. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8427. 无人物。}
  8428. ###分集详细内容
  8429. ##第1章 重生
  8430. 我重生了。
  8431. 源于一个男人偏执的暗恋。
  8432. ##第2章 相救
  8433. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8434. 我眼睛扫向站在锅炉后的卞大伟。"
  8435. ];
  8436. // 构建消息
  8437. $messages = [
  8438. $system_message,
  8439. [
  8440. 'role' => 'user',
  8441. 'content' => "以下是文档内容:
  8442. {$content}
  8443. 用户问题:
  8444. {$question}"
  8445. ]
  8446. ];
  8447. }else {
  8448. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8449. // 构建消息
  8450. $messages = [
  8451. $system_message,
  8452. [
  8453. 'role' => 'user',
  8454. 'content' => "以下是文档内容:
  8455. {$content}
  8456. 用户问题:
  8457. {$question}"
  8458. ]
  8459. ];
  8460. }else {
  8461. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8462. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8463. return (array)$value;
  8464. })->toArray();
  8465. array_unshift($messages, $system_message);
  8466. $messages[] = [
  8467. 'role' => 'user',
  8468. 'content' => $prompt
  8469. ];
  8470. }
  8471. }
  8472. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8473. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8474. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8475. if ($model === 'deepseek-chat') {
  8476. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8477. $model = 'deepseek-v4-flash';
  8478. $thinkingMode = 'disabled';
  8479. } elseif ($model === 'deepseek-reasoner') {
  8480. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8481. $model = 'deepseek-v4-flash';
  8482. $thinkingMode = 'enabled';
  8483. }
  8484. $post_data = [
  8485. 'model' => $model,
  8486. 'messages' => $messages,
  8487. // 'max_tokens' => 8192,
  8488. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8489. 'frequency_penalty' => 0,
  8490. 'presence_penalty' => 0,
  8491. 'response_format' => ['type' => 'text'],
  8492. 'thinking' => ['type' => $thinkingMode],
  8493. 'stream' => true // 启用流式输出
  8494. ];
  8495. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8496. // 根据模型类型选择调用方法
  8497. $fullContent = '';
  8498. $fullReasoningContent = '';
  8499. $usage = [];
  8500. // dd($post_data);
  8501. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8502. try {
  8503. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8504. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8505. } else if (in_array($model, $this->gpt_text_models)) {
  8506. // GPT-5.4 模型使用 TokenRouter API
  8507. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8508. } else if (in_array($model, $this->gemini_text_models)) {
  8509. // Gemini 模型使用 Gemini API
  8510. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8511. } else {
  8512. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8513. }
  8514. // 验证返回值类型
  8515. if (!is_iterable($streamGenerator)) {
  8516. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8517. dLog('deepseek')->error('方法名流式生成器无效', [
  8518. 'generator_type' => $errorType,
  8519. 'model' => $model,
  8520. // 添加其他上下文信息
  8521. ]);
  8522. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8523. 'type' => $errorType,
  8524. 'model' => $model
  8525. ]);
  8526. yield [
  8527. 'type' => 'error',
  8528. // 根据方法返回相应的空数据结构
  8529. 'answer' => '',
  8530. 'reasoning' => '',
  8531. 'usage' => [],
  8532. 'error' => '接口返回数据异常,请重新请求'
  8533. ];
  8534. return;
  8535. }
  8536. // 处理流式输出
  8537. foreach ($streamGenerator as $chunk) {
  8538. if (isset($chunk['type'])) {
  8539. if ($chunk['type'] === 'done') {
  8540. $fullContent = $chunk['full_content'];
  8541. $fullReasoningContent = $chunk['full_reasoning'];
  8542. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8543. } else {
  8544. yield $chunk;
  8545. }
  8546. }
  8547. }
  8548. } catch (\Exception $e) {
  8549. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8550. 'model' => $model,
  8551. 'trace' => $e->getTraceAsString()
  8552. ]);
  8553. logDB('deepseek', 'error', '方法名流式处理失败', [
  8554. 'error' => $e->getMessage(),
  8555. 'model' => $model
  8556. ]);
  8557. yield [
  8558. 'type' => 'error',
  8559. // 根据方法返回相应的空数据结构
  8560. 'answer' => '',
  8561. 'reasoning' => '',
  8562. 'usage' => [],
  8563. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8564. ];
  8565. return;
  8566. }
  8567. dLog('deepseek')->info('完整内容: '.$fullContent);
  8568. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8569. // 处理完整内容并返回最终结果
  8570. $script_arr = [];
  8571. if ($fullContent) {
  8572. $script_arr = handleScriptContentForAce($fullContent);
  8573. dLog('deepseek')->info('解析内容', $script_arr);
  8574. logDB('deepseek', 'info', '解析内容', $script_arr);
  8575. }
  8576. if (empty($script_arr['roles'])) {
  8577. // 未生成剧本相关内容,保存对话记录并返回提示
  8578. dLog('deepseek')->info('未生成剧本相关的内容');
  8579. try {
  8580. $now = date('Y-m-d H:i:s');
  8581. // 保存对话记录
  8582. $records = [
  8583. [
  8584. 'uid' => $uid,
  8585. 'anime_id' => $anime_id,
  8586. 'sequence' => 0,
  8587. 'role' => 'user',
  8588. 'content' => $prompt,
  8589. 'created_at' => $now,
  8590. 'updated_at' => $now
  8591. ],
  8592. [
  8593. 'uid' => $uid,
  8594. 'anime_id' => $anime_id,
  8595. 'sequence' => 0,
  8596. 'role' => 'assistant',
  8597. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8598. 'created_at' => $now,
  8599. 'updated_at' => $now
  8600. ]
  8601. ];
  8602. DB::table('mp_anime_records')->insert($records);
  8603. } catch (\Exception $e) {
  8604. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8605. }
  8606. yield [
  8607. 'type' => 'done',
  8608. 'script' => [],
  8609. 'episode' => [],
  8610. 'answer' => $fullContent,
  8611. 'reasoning' => $fullReasoningContent,
  8612. 'usage' => $usage,
  8613. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8614. ];
  8615. return;
  8616. }
  8617. // 替换美术风格
  8618. if ($mappedArtStyle !== '') {
  8619. $script_arr['art_style'] = $mappedArtStyle;
  8620. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8621. }
  8622. if ($user_anime_name != '新剧本策划') {
  8623. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8624. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8625. // 确认对话名称唯一性
  8626. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8627. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8628. }
  8629. }else {
  8630. $anime_name = $user_anime_name;
  8631. }
  8632. $table_data = [
  8633. 'user_id' => $uid,
  8634. 'model' => $model,
  8635. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8636. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8637. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8638. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8639. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8640. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8641. 'art_style_type' => $input_art_style,
  8642. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8643. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8644. 'status' => '解析完成',
  8645. 'generate_status' => '待执行',
  8646. 'updated_at' => date('Y-m-d H:i:s')
  8647. ];
  8648. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8649. // 如果是修改集数,则将content内容更新(会改变原文)
  8650. if (isset($episode_count) && $episode_count > 0) {
  8651. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8652. $table_data['start_episode_sequence'] = 1;
  8653. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8654. }else {
  8655. // 如果需要生成原文内容,从script_arr中提取
  8656. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8657. $table_data['content'] = $script_arr['content'];
  8658. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8659. if (!$table_data['content']) {
  8660. yield [
  8661. 'type' => 'done',
  8662. 'script' => [],
  8663. 'episode' => [],
  8664. 'answer' => $fullContent,
  8665. 'reasoning' => $fullReasoningContent,
  8666. 'usage' => $usage,
  8667. 'error' => '未生成剧本内容,请调整提示词再试'
  8668. ];
  8669. return;
  8670. }
  8671. }
  8672. if (isset($table_data['content']) && $table_data['content']) {
  8673. $chapters = splitContent($table_data['content']);
  8674. $chapter_count = count($chapters);
  8675. if ($chapter_count > 0) {
  8676. $table_data['start_episode_sequence'] = 1;
  8677. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8678. }
  8679. }
  8680. }
  8681. if ($extra_products) {
  8682. $table_data['extra_products'] = json_encode($extra_products, 256);
  8683. }
  8684. $single_episode = [];
  8685. try {
  8686. DB::beginTransaction();
  8687. $now = date('Y-m-d H:i:s');
  8688. // 更新动漫大纲
  8689. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8690. if (!$boolen) {
  8691. dLog('deepseek')->info('对话修改失败', $table_data);
  8692. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8693. Utils::throwError('20003:对话修改失败');
  8694. }
  8695. // 保存对话记录
  8696. $records = [
  8697. [
  8698. 'uid' => $uid,
  8699. 'anime_id' => $anime_id,
  8700. 'sequence' => 0,
  8701. 'role' => 'user',
  8702. 'content' => $prompt,
  8703. 'created_at' => $now,
  8704. 'updated_at' => $now
  8705. ],
  8706. [
  8707. 'uid' => $uid,
  8708. 'anime_id' => $anime_id,
  8709. 'sequence' => 0,
  8710. 'role' => 'assistant',
  8711. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8712. 'content' => $fullContent,
  8713. 'created_at' => $now,
  8714. 'updated_at' => $now
  8715. ]
  8716. ];
  8717. // 保存对话记录
  8718. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8719. if (!$boolen3) {
  8720. Utils::throwError('20003:对话记录保存失败');
  8721. }
  8722. // 单剧集模式:生成并保存剧集信息
  8723. if ($is_single) {
  8724. $anime_name = getProp($anime, 'anime_name', '未命名');
  8725. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8726. if (empty($episode_arr['acts'])) {
  8727. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8728. }
  8729. $saveResult = $this->saveEpisodeVersionData(
  8730. $anime_id,
  8731. 1,
  8732. $episode_arr,
  8733. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8734. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8735. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8736. null,
  8737. null,
  8738. false,
  8739. $content,
  8740. $now,
  8741. $ref_products
  8742. );
  8743. $single_episode = $saveResult['episode'];
  8744. $episode_id = $saveResult['episode_id'];
  8745. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8746. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8747. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8748. 'props' => json_encode($saveResult['merged_props'], 256),
  8749. 'updated_at' => $now
  8750. ]);
  8751. if ($boolen5 === false) {
  8752. Utils::throwError('20003:单剧集主表资源同步失败');
  8753. }
  8754. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8755. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8756. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8757. $episode_record_content = '确认分镜大纲';
  8758. if ($content !== '') {
  8759. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8760. }
  8761. $episode_records = [
  8762. [
  8763. 'uid' => $uid,
  8764. 'anime_id' => $anime_id,
  8765. 'role' => 'user',
  8766. 'content' => $episode_record_content,
  8767. 'sequence' => 1,
  8768. 'episode_id' => $episode_id,
  8769. 'created_at' => $now,
  8770. 'updated_at' => $now
  8771. ],
  8772. [
  8773. 'uid' => $uid,
  8774. 'anime_id' => $anime_id,
  8775. 'role' => 'assistant',
  8776. 'content' => $fullContent,
  8777. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8778. 'sequence' => 1,
  8779. 'episode_id' => $episode_id,
  8780. 'created_at' => $now,
  8781. 'updated_at' => $now
  8782. ]
  8783. ];
  8784. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8785. if (!$boolen4) {
  8786. Utils::throwError('20003:单剧集分镜记录保存失败');
  8787. }
  8788. }
  8789. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8790. if ($is_single && !empty($single_episode)) {
  8791. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8792. 'anime_id' => $anime_id,
  8793. 'episode_id' => $episode_id ?? 0,
  8794. 'model' => $model,
  8795. 'source' => 'reGenerateAnimeForAce',
  8796. ]);
  8797. }
  8798. }catch (\Exception $e) {
  8799. DB::rollBack();
  8800. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8801. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8802. yield [
  8803. 'type' => 'done',
  8804. 'answer' => $fullContent,
  8805. 'reasoning' => $fullReasoningContent,
  8806. 'usage' => $usage,
  8807. 'error' => $e->getMessage(),
  8808. ];
  8809. return;
  8810. }
  8811. DB::commit();
  8812. dLog('deepseek')->info('保存完毕');
  8813. if ($is_single && !empty($single_episode)) {
  8814. // $this->batchSetGlobalRoleImg([
  8815. // 'anime_id' => $anime_id,
  8816. // ]);
  8817. // $this->batchSetGlobalSceneImg([
  8818. // 'anime_id' => $anime_id,
  8819. // ]);
  8820. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8821. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8822. }
  8823. $table_data['anime_id'] = $anime_id;
  8824. $table_data['roles'] = json_decode($table_data['roles'], true);
  8825. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8826. $table_data['props'] = json_decode($table_data['props'], true);
  8827. unset($table_data['updated_at']);
  8828. unset($table_data['status']);
  8829. yield [
  8830. 'type' => 'done',
  8831. 'script' => $table_data,
  8832. 'episode' => $single_episode,
  8833. 'answer' => $fullContent,
  8834. 'reasoning' => $fullReasoningContent,
  8835. 'usage' => $usage
  8836. ];
  8837. }
  8838. public function chatForAce($data) {
  8839. $uid = Site::getUid();
  8840. // 积分余额预检(不足直接报错)
  8841. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  8842. $anime_id = getProp($data, 'anime_id');
  8843. $file = getProp($data, 'file');
  8844. $content = getProp($data, 'content', '');
  8845. $bid = getProp($data, 'bid', 0);
  8846. $script_id = getProp($data, 'script_id', 0);
  8847. $episode_number = getProp($data, 'episode_number', 1);
  8848. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8849. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8850. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8851. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8852. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8853. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8854. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8855. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8856. $roles = is_array($roles) ? $roles : [];
  8857. $scenes = is_array($scenes) ? $scenes : [];
  8858. $extra_products = getProp($data, 'products', []);
  8859. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8860. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8861. $anime_script_id = getProp($anime, 'script_id');
  8862. if ($anime_script_id) {
  8863. $cpid = Site::getCpid();
  8864. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8865. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8866. ->where('mapping.script_id', $anime_script_id)
  8867. ->where('product.cpid', $cpid)
  8868. ->where('product.is_deleted', 0);
  8869. // 如果提供了 episode_number,则过滤指定集数
  8870. if ($episode_number !== null && $episode_number !== '') {
  8871. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8872. }
  8873. $mappings = $script_products_mappings->select(
  8874. 'mapping.product_id',
  8875. 'mapping.episode_number',
  8876. 'product.product_name',
  8877. 'product.type',
  8878. 'product.product',
  8879. 'product.pic_prompt',
  8880. 'product.url',
  8881. 'product.pic_task_id',
  8882. 'product.pic_task_status',
  8883. 'product.three_view_image_url'
  8884. )
  8885. ->get();
  8886. // 按 product_id 分组,合并 episode_number
  8887. $productMap = [];
  8888. foreach ($mappings as $item) {
  8889. $product_id = $item->product_id;
  8890. $product_name = $item->product_name;
  8891. // 处理product_name两边的符号
  8892. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8893. if (!isset($productMap[$product_id])) {
  8894. $productMap[$product_id] = [
  8895. 'product_id' => $product_id,
  8896. 'product_name' => $product_name,
  8897. 'type' => (int)$item->type,
  8898. 'product' => (int)$item->product,
  8899. 'pic_prompt' => $item->pic_prompt,
  8900. 'url' => $item->url,
  8901. 'pic_task_id' => $item->pic_task_id,
  8902. 'pic_task_status' => $item->pic_task_status,
  8903. 'episode_numbers' => [],
  8904. ];
  8905. }
  8906. // 添加 episode_number(去重)
  8907. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8908. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8909. }
  8910. }
  8911. // 将查询到的剧本资产合并到extra_products中
  8912. // 先构建extra_products的索引(以product_id+episode_number为key)
  8913. $extraProductsMap = [];
  8914. foreach ($extra_products as $item) {
  8915. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8916. $extraProductsMap[$key] = $item;
  8917. }
  8918. // 合并剧本资产(去重:product_id+episode_number)
  8919. foreach ($productMap as $product) {
  8920. foreach ($product['episode_numbers'] as $ep_num) {
  8921. $key = $product['product_id'] . '_' . $ep_num;
  8922. // 如果不存在则添加
  8923. if (!isset($extraProductsMap[$key])) {
  8924. $extraProductsMap[$key] = [
  8925. 'product_id' => $product['product_id'],
  8926. 'product_name' => $product['product_name'],
  8927. 'type' => $product['type'],
  8928. 'product' => $product['product'],
  8929. 'pic_prompt' => $product['pic_prompt'],
  8930. 'url' => $product['url'],
  8931. 'pic_task_id' => $product['pic_task_id'],
  8932. 'pic_task_status' => $product['pic_task_status'],
  8933. 'episode_number' => $ep_num,
  8934. ];
  8935. }
  8936. }
  8937. }
  8938. // 重新赋值给extra_products
  8939. $extra_products = array_values($extraProductsMap);
  8940. }
  8941. // 处理提示词
  8942. if ($prompt && $extra_products) {
  8943. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8944. foreach($extra_products as $item) {
  8945. $product_name = getProp($item, 'product_name');
  8946. if ($product_name) {
  8947. // 替换 {product_name} 为 product_name
  8948. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8949. }
  8950. }
  8951. }
  8952. // 获取最后一集序号
  8953. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8954. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8955. // 转换主体列表和场景列表的格式
  8956. // 获取参考主体或场景
  8957. if ((int)$episode_number === 1) {
  8958. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8959. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8960. }else {
  8961. $prev_episode_number = $episode_number - 1;
  8962. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8963. }
  8964. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8965. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8966. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8967. // 合并anime_products和extra_products(extra_products优先,去重)
  8968. $anime_products = getProp($anime, 'extra_products');
  8969. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8970. $ref_products = [];
  8971. foreach($anime_products as $item) {
  8972. $product_name = getProp($item, 'product_name');
  8973. $ref_products[$product_name] = $item;
  8974. }
  8975. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8976. $extra_roles = []; // 从extra_products中提取的角色
  8977. $extra_scenes = []; // 从extra_products中提取的场景
  8978. $extra_props = []; // 从extra_products中提取的道具
  8979. if ($extra_products && is_array($extra_products)) {
  8980. foreach($extra_products as $item) {
  8981. $product = (int)getProp($item, 'product');
  8982. $product_name = getProp($item, 'product_name');
  8983. if ($product_name == '旁白') continue;
  8984. $pic_prompt = getProp($item, 'pic_prompt');
  8985. $ref_products[$product_name] = $item;
  8986. if ($product === 1) {
  8987. // 角色
  8988. $extra_roles[$product_name] = [
  8989. 'role' => $product_name,
  8990. 'pic_prompt' => $pic_prompt,
  8991. 'url' => getProp($item, 'url', ''),
  8992. ];
  8993. } elseif ($product === 2) {
  8994. // 场景
  8995. $extra_scenes[$product_name] = [
  8996. 'scene' => $product_name,
  8997. 'pic_prompt' => $pic_prompt,
  8998. 'url' => getProp($item, 'url', ''),
  8999. ];
  9000. } elseif ($product === 3) {
  9001. // 道具
  9002. $extra_props[$product_name] = [
  9003. 'prop' => $product_name,
  9004. 'pic_prompt' => $pic_prompt,
  9005. 'url' => getProp($item, 'url', ''),
  9006. ];
  9007. }
  9008. }
  9009. }
  9010. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  9011. $merged_roles = [];
  9012. foreach($ref_roles as $role) {
  9013. $role_name = getProp($role, 'role');
  9014. if (!isset($extra_roles[$role_name])) {
  9015. $merged_roles[$role_name] = $role;
  9016. }
  9017. }
  9018. // 添加extra_roles
  9019. foreach($extra_roles as $role_name => $role) {
  9020. $merged_roles[$role_name] = $role;
  9021. }
  9022. $ref_roles = array_values($merged_roles);
  9023. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  9024. $merged_scenes = [];
  9025. foreach($ref_scenes as $scene) {
  9026. $scene_name = getProp($scene, 'scene');
  9027. if (!isset($extra_scenes[$scene_name])) {
  9028. $merged_scenes[$scene_name] = $scene;
  9029. }
  9030. }
  9031. // 添加extra_scenes
  9032. foreach($extra_scenes as $scene_name => $scene) {
  9033. $merged_scenes[$scene_name] = $scene;
  9034. }
  9035. $ref_scenes = array_values($merged_scenes);
  9036. // 合并ref_props和extra_props(extra_props优先,去重)
  9037. $merged_props = [];
  9038. foreach($ref_props as $prop) {
  9039. $prop_name = getProp($prop, 'prop');
  9040. if (!isset($extra_props[$prop_name])) {
  9041. $merged_props[$prop_name] = $prop;
  9042. }
  9043. }
  9044. // 添加extra_props
  9045. foreach($extra_props as $prop_name => $prop) {
  9046. $merged_props[$prop_name] = $prop;
  9047. }
  9048. $ref_props = array_values($merged_props);
  9049. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  9050. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  9051. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  9052. // 构建强制主体、场景和道具提示词
  9053. $forced_roles_prompt = "";
  9054. $forced_scenes_prompt = "";
  9055. $forced_props_prompt = "";
  9056. if (!empty($extra_roles)) {
  9057. $forced_roles_list = "";
  9058. foreach($extra_roles as $role_name => $role) {
  9059. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  9060. }
  9061. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9062. }
  9063. if (!empty($extra_scenes)) {
  9064. $forced_scenes_list = "";
  9065. foreach($extra_scenes as $scene_name => $scene) {
  9066. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  9067. }
  9068. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9069. }
  9070. if (!empty($extra_props)) {
  9071. $forced_props_list = "";
  9072. foreach($extra_props as $prop_name => $prop) {
  9073. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  9074. }
  9075. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9076. }
  9077. if ($anime_script_id) {
  9078. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  9079. }else if ($roles_content) {
  9080. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  9081. 主体范围:\n {$roles_content}\n
  9082. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  9083. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9084. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9085. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9086. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9087. }else {
  9088. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9089. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9090. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9091. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9092. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9093. }
  9094. if ($anime_script_id) {
  9095. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  9096. }else if ($scenes_content) {
  9097. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9098. 场景范围:\n {$scenes_content}\n
  9099. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  9100. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  9101. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9102. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9103. }else {
  9104. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9105. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9106. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9107. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9108. }
  9109. if ($anime_script_id) {
  9110. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  9111. }else if ($props_content) {
  9112. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9113. 道具范围:\n {$props_content}\n
  9114. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  9115. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  9116. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9117. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9118. }else {
  9119. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9120. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  9121. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9122. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9123. }
  9124. // 提取文件内容
  9125. if ($file) {
  9126. $uploaded_content = $this->extractFileContent($file);
  9127. if (!$uploaded_content) {
  9128. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9129. }
  9130. } elseif ($script_id) {
  9131. $uploaded_content = $this->getContentByScriptId($script_id);
  9132. if (!$uploaded_content) {
  9133. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9134. }
  9135. } elseif ($bid) {
  9136. $uploaded_content = $this->getContentByBid($bid);
  9137. if (!$uploaded_content) {
  9138. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9139. }
  9140. } elseif ($content) {
  9141. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  9142. }
  9143. // elseif ($prompt) {
  9144. // $uploaded_content = filterContent($prompt);
  9145. // }
  9146. else {
  9147. $uploaded_content = '';
  9148. }
  9149. // 美术风格
  9150. $input_art_style = getProp($data, 'art_style');
  9151. if (!$input_art_style) {
  9152. $mappedArtStyle = getProp($anime, 'art_style');
  9153. }else {
  9154. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9155. }
  9156. if (!$mappedArtStyle) {
  9157. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9158. }else {
  9159. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9160. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9161. }else {
  9162. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9163. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9164. }
  9165. }
  9166. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9167. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9168. // 强制要求:
  9169. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9170. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9171. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9172. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  9173. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  9174. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  9175. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  9176. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  9177. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  9178. // 10.分镜要和场景列表、人物主体保持一致\n
  9179. // 普通要求:
  9180. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9181. // {$role_demo}
  9182. // {$scene_demo}
  9183. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9184. // 4.1片段分割逻辑(优先级从高到低):
  9185. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9186. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9187. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9188. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9189. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9190. // - 片段数量格式为: 片段数量:8
  9191. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9192. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9193. // 4.3分镜结构:每个分镜包含以下字段:
  9194. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  9195. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  9196. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9197. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  9198. // - 运镜:场景+画面描述+运镜
  9199. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  9200. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9201. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9202. // 5.$mappedArtStyle_prompt\n\n
  9203. // 示例格式:\n
  9204. // 第1集:隐形的守护者
  9205. // ###故事梗概
  9206. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9207. // ###美术风格
  9208. // 基础画风风格词:胡金铨武侠
  9209. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9210. // ###主体列表
  9211. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9212. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9213. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9214. // ###场景列表
  9215. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9216. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9217. // ###分段剧本
  9218. // 片段数量:8
  9219. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9220. // ##片段1
  9221. // 时长:12s
  9222. // 分镜1
  9223. // 场景:边境小镇街道
  9224. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9225. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9226. // 配音台词:
  9227. // 背景音效:
  9228. // 分镜2
  9229. // 场景:悦来酒馆
  9230. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9231. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9232. // 配音台词:
  9233. // 背景音效:
  9234. // 分镜3
  9235. // 场景:悦来酒馆
  9236. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9237. // 运镜:从中景推向令牌特写。
  9238. // 配音台词:
  9239. // 背景音效:
  9240. // 分镜4
  9241. // 场景:悦来酒馆
  9242. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9243. // 运镜:极速推向酒水溅起的瞬间。
  9244. // 配音台词:
  9245. // 背景音效:
  9246. // 分镜5
  9247. // 镜头描述
  9248. // 场景:悦来酒馆
  9249. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9250. // 运镜:固定机位,利用倾斜构图制造压迫感。
  9251. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9252. // 背景音效:
  9253. // \n\n";
  9254. /*
  9255. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  9256. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  9257. // ===================================================================
  9258. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9259. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9260. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9261. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9262. 强制要求:
  9263. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9264. 普通要求:
  9265. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9266. {$role_demo}
  9267. {$scene_demo}
  9268. {$prop_demo}
  9269. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9270. 5.1片段分割逻辑(优先级从高到低):
  9271. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9272. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9273. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9274. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9275. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9276. - 片段数量格式为: 片段数量:8
  9277. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9278. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9279. 5.3分镜结构:每个分镜包含以下字段:
  9280. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9281. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9282. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9283. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9284. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9285. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9286. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9287. - 运镜:场景+画面描述+运镜
  9288. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9289. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9290. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9291. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9292. 6.《情绪-视听语言映射表》:
  9293. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9294. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9295. -----|---------|------------|----------------
  9296. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9297. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9298. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9299. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9300. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9301. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9302. -----|---------|------------|----------------
  9303. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9304. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9305. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9306. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9307. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9308. --------|---------|--------------|-------------
  9309. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9310. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9311. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9312. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9313. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9314. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9315. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9316. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9317. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9318. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9319. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9320. -----|---------|------------|------------
  9321. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9322. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9323. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9324. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9325. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9326. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9327. --------|---------|--------------|----------
  9328. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9329. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9330. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9331. 6.6 声音设计与潜意识影响 (Soundscape)
  9332. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9333. -----|---------|------------|------------------
  9334. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9335. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9336. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9337. 理论基石:
  9338. - The Five C's of Cinematography by Joseph V. Mascelli
  9339. - Film Art: An Introduction by David Bordwell
  9340. - Sight, Sound, Motion by Herbert Zettl
  9341. - Notes on the Cinematograph by Robert Bresson
  9342. \n\n
  9343. 7.{$mappedArtStyle_prompt}
  9344. 示例格式:\n
  9345. 第1集:隐形的守护者
  9346. ###故事梗概
  9347. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9348. ###美术风格
  9349. 基础画风风格词:胡金铨武侠
  9350. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9351. ###主体列表
  9352. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9353. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9354. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9355. ###场景列表
  9356. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9357. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9358. ###道具列表
  9359. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9360. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9361. ###分段剧本
  9362. 片段数量:8
  9363. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9364. ##片段1
  9365. 时长:12s
  9366. 分镜1
  9367. 出场角色:刀疤脸
  9368. 场景:边境小镇街道
  9369. 出场道具:酒杯-高脚杯
  9370. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9371. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9372. 配音台词:
  9373. 背景音效:
  9374. 分镜2
  9375. 出场角色:刀疤脸
  9376. 场景:悦来酒馆
  9377. 出场道具:酒杯-高脚杯
  9378. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9379. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9380. 配音台词:
  9381. 背景音效:
  9382. 分镜3
  9383. 出场角色:刀疤脸
  9384. 场景:悦来酒馆
  9385. 出场道具:酒杯-高脚杯
  9386. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9387. 运镜:从中景推向令牌特写。
  9388. 配音台词:
  9389. 背景音效:
  9390. 分镜4
  9391. 出场角色:刀疤脸
  9392. 场景:悦来酒馆
  9393. 出场道具:酒杯-高脚杯
  9394. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9395. 运镜:极速推向酒水溅起的瞬间。
  9396. 配音台词:
  9397. 背景音效:
  9398. 分镜5
  9399. 出场角色:刀疤脸
  9400. 场景:悦来酒馆
  9401. 出场道具:酒杯-高脚杯
  9402. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9403. 运镜:固定机位,利用倾斜构图制造压迫感。
  9404. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9405. 背景音效:
  9406. \n\n";
  9407. */
  9408. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9409. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9410. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9411. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9412. 强制要求:
  9413. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9414. 普通要求:
  9415. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  9416. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  9417. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  9418. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  9419. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9420. 5.1片段分割逻辑(优先级从高到低):
  9421. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9422. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9423. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9424. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9425. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9426. - 片段数量格式为: 片段数量:8
  9427. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9428. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9429. 5.3分镜结构:每个分镜包含以下字段:
  9430. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9431. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9432. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9433. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9434. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9435. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9436. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9437. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9438. - 运镜:场景+画面描述+运镜
  9439. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9440. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9441. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9442. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9443. 6.《情绪-视听语言映射表》:
  9444. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9445. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9446. -----|---------|------------|----------------
  9447. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9448. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9449. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9450. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9451. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9452. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9453. -----|---------|------------|----------------
  9454. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9455. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9456. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9457. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9458. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9459. --------|---------|--------------|-------------
  9460. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9461. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9462. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9463. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9464. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9465. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9466. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9467. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9468. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9469. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9470. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9471. -----|---------|------------|------------
  9472. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9473. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9474. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9475. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9476. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9477. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9478. --------|---------|--------------|----------
  9479. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9480. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9481. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9482. 6.6 声音设计与潜意识影响 (Soundscape)
  9483. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9484. -----|---------|------------|------------------
  9485. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9486. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9487. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9488. 理论基石:
  9489. - The Five C's of Cinematography by Joseph V. Mascelli
  9490. - Film Art: An Introduction by David Bordwell
  9491. - Sight, Sound, Motion by Herbert Zettl
  9492. - Notes on the Cinematograph by Robert Bresson
  9493. \n\n
  9494. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9495. 示例格式:\n
  9496. 第1集:隐形的守护者
  9497. ###故事梗概
  9498. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9499. ###美术风格
  9500. 基础画风风格词:胡金铨武侠
  9501. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9502. ###主体列表
  9503. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9504. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9505. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9506. ###场景列表
  9507. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9508. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9509. ###道具列表
  9510. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9511. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9512. ###分段剧本
  9513. 片段数量:8
  9514. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9515. ##片段1
  9516. 时长:12s
  9517. 分镜1
  9518. 出场角色:刀疤脸
  9519. 场景:边境小镇街道
  9520. 出场道具:酒杯-高脚杯
  9521. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9522. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9523. 配音台词:
  9524. 背景音效:
  9525. 分镜2
  9526. 出场角色:刀疤脸
  9527. 场景:悦来酒馆
  9528. 出场道具:酒杯-高脚杯
  9529. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9530. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9531. 配音台词:
  9532. 背景音效:
  9533. 分镜3
  9534. 出场角色:刀疤脸
  9535. 场景:悦来酒馆
  9536. 出场道具:酒杯-高脚杯
  9537. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9538. 运镜:从中景推向令牌特写。
  9539. 配音台词:
  9540. 背景音效:
  9541. 分镜4
  9542. 出场角色:刀疤脸
  9543. 场景:悦来酒馆
  9544. 出场道具:酒杯-高脚杯
  9545. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9546. 运镜:极速推向酒水溅起的瞬间。
  9547. 配音台词:
  9548. 背景音效:
  9549. 分镜5
  9550. 出场角色:刀疤脸
  9551. 场景:悦来酒馆
  9552. 出场道具:酒杯-高脚杯
  9553. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9554. 运镜:固定机位,利用倾斜构图制造压迫感。
  9555. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9556. 背景音效:
  9557. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9558. 【本次剧集信息】剧集序号是{$episode_number}。
  9559. 【本次生成数据-主体列表】{$role_demo}
  9560. 【本次生成数据-场景列表】{$scene_demo}
  9561. 【本次生成数据-道具列表】{$prop_demo}
  9562. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9563. \n\n";
  9564. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9565. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  9566. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9567. $is_regenerate_version = true;
  9568. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9569. $prompt = $origin_prompt;
  9570. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9571. // 获取章节内容
  9572. $full_content = getProp($anime, 'content');
  9573. if ($uploaded_content) {
  9574. $full_content = $uploaded_content;
  9575. }
  9576. // 根据章节内容拆分章节
  9577. $chapters = splitContent($full_content);
  9578. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9579. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9580. $messages = [];
  9581. if ($prompt == '确认分镜大纲') {
  9582. // 暂时保留
  9583. $content = $chapter_content;
  9584. if ($is_single) $content = $full_content; // 单剧集使用全文
  9585. if (!$content) {
  9586. Utils::throwError('20003:章节内容无法获取,请确认');
  9587. }
  9588. $question = $is_single
  9589. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9590. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9591. // 构建消息
  9592. $messages[] =
  9593. [
  9594. 'role' => 'user',
  9595. 'content' => $question
  9596. ];
  9597. }else if ($prompt == '继续策划下一集') {
  9598. if ($is_single) {
  9599. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9600. }
  9601. $content = $chapter_content;
  9602. if (!$content) {
  9603. Utils::throwError('20003:章节内容无法获取,请确认');
  9604. }
  9605. // 获取上一集最后记录
  9606. $prev_sequence = $episode_number - 1;
  9607. $messages = array_merge(
  9608. [
  9609. [
  9610. 'role' => 'system',
  9611. 'content' => $demo
  9612. ]
  9613. ],
  9614. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9615. );
  9616. // 构建消息
  9617. $messages[] =
  9618. [
  9619. 'role' => 'user',
  9620. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9621. ];
  9622. /*
  9623. // 旧版逻辑
  9624. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9625. // 构建消息
  9626. $messages[] =
  9627. [
  9628. 'role' => 'user',
  9629. 'content' => $question
  9630. ];
  9631. */
  9632. // dd($messages);
  9633. }else {
  9634. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9635. if (!$content) {
  9636. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9637. }
  9638. if (!$content) {
  9639. Utils::throwError('20003:章节内容无法获取,请确认');
  9640. }
  9641. $messages = array_merge(
  9642. [
  9643. [
  9644. 'role' => 'system',
  9645. 'content' => $demo
  9646. ]
  9647. ],
  9648. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9649. );
  9650. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9651. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9652. if ($origin_prompt) {
  9653. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9654. }
  9655. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9656. $messages[] = [
  9657. 'role' => 'user',
  9658. 'content' => "本集剧情内容:\n\n{$content}\n"
  9659. ];
  9660. $messages[] =
  9661. [
  9662. 'role' => 'user',
  9663. 'content' => $question
  9664. ];
  9665. }
  9666. // 处理文本模型
  9667. $model = getProp($data, 'model');
  9668. if (!$model) {
  9669. // 用户没有输入,从anime表获取
  9670. $model = getProp($anime, 'model');
  9671. if (!$model) {
  9672. // anime表也没有,使用默认值
  9673. $model = 'deepseek-v4-pro';
  9674. }
  9675. }
  9676. // 验证模型是否在可用模型表中
  9677. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9678. $model = 'deepseek-v4-pro';
  9679. }
  9680. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9681. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9682. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9683. if ($model === 'deepseek-chat') {
  9684. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9685. $model = 'deepseek-v4-flash';
  9686. $thinkingMode = 'disabled';
  9687. } elseif ($model === 'deepseek-reasoner') {
  9688. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9689. $model = 'deepseek-v4-flash';
  9690. $thinkingMode = 'enabled';
  9691. }
  9692. $post_data = [
  9693. 'model' => $model,
  9694. 'messages' => $messages,
  9695. // 'max_tokens' => 8192,
  9696. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9697. 'frequency_penalty' => 0,
  9698. 'presence_penalty' => 0,
  9699. 'response_format' => ['type' => 'text'],
  9700. 'thinking' => ['type' => $thinkingMode],
  9701. 'stream' => true // 启用流式输出
  9702. ];
  9703. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9704. // 根据模型类型选择调用方法
  9705. $fullContent = '';
  9706. $fullReasoningContent = '';
  9707. $usage = [];
  9708. try {
  9709. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9710. // DeepSeek 官方模型使用 DeepSeek API
  9711. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9712. } else if (in_array($model, $this->gpt_text_models)) {
  9713. // GPT-5.4 模型使用 TokenRouter API
  9714. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9715. } else if (in_array($model, $this->gemini_text_models)) {
  9716. // Gemini 模型使用 Gemini API
  9717. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9718. } else {
  9719. // 其他模型使用火山引擎API
  9720. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9721. }
  9722. // 验证返回值类型
  9723. if (!is_iterable($streamGenerator)) {
  9724. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9725. dLog('deepseek')->error('chat流式生成器无效', [
  9726. 'generator_type' => $errorType,
  9727. 'model' => $model,
  9728. 'anime_id' => $anime_id,
  9729. 'episode_number' => $episode_number
  9730. ]);
  9731. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9732. 'type' => $errorType,
  9733. 'model' => $model
  9734. ]);
  9735. yield [
  9736. 'type' => 'error',
  9737. 'episode' => [],
  9738. 'answer' => '',
  9739. 'reasoning' => '',
  9740. 'usage' => [],
  9741. 'error' => '接口返回数据异常,请重新请求'
  9742. ];
  9743. return;
  9744. }
  9745. // 处理流式输出
  9746. foreach ($streamGenerator as $chunk) {
  9747. if (isset($chunk['type'])) {
  9748. if ($chunk['type'] === 'done') {
  9749. // 最终结果
  9750. $fullContent = $chunk['full_content'];
  9751. $fullReasoningContent = $chunk['full_reasoning'];
  9752. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9753. } else {
  9754. // 逐块yield数据
  9755. yield $chunk;
  9756. }
  9757. }
  9758. }
  9759. } catch (\Exception $e) {
  9760. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9761. 'model' => $model,
  9762. 'anime_id' => $anime_id,
  9763. 'episode_number' => $episode_number,
  9764. 'trace' => $e->getTraceAsString()
  9765. ]);
  9766. logDB('deepseek', 'error', 'chat流式处理失败', [
  9767. 'error' => $e->getMessage(),
  9768. 'model' => $model
  9769. ]);
  9770. yield [
  9771. 'type' => 'error',
  9772. 'episode' => [],
  9773. 'answer' => '',
  9774. 'reasoning' => '',
  9775. 'usage' => [],
  9776. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9777. ];
  9778. return;
  9779. }
  9780. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9781. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9782. dLog('deepseek')->info('完整内容: '.$fullContent);
  9783. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9784. // 处理完整内容并返回最终结果
  9785. $episode_arr = handleEpisodeContentForAce($fullContent);
  9786. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9787. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9788. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9789. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9790. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9791. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9792. // }
  9793. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9794. $max_retries = 3;
  9795. $retry_count = 0;
  9796. $validation_failed = false;
  9797. $validation_error_msg = '';
  9798. // 验证生成的内容
  9799. if ($anime_script_id) {
  9800. // 检查是否有acts数据
  9801. if (empty($episode_arr['acts'])) {
  9802. $validation_failed = true;
  9803. $validation_error_msg = '未生成分镜剧本相关的内容';
  9804. } else {
  9805. // 校验主体列表:不能为空主体(旁白不算)
  9806. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9807. // 过滤掉"旁白"角色
  9808. $generated_roles = array_filter($generated_roles, function($role) {
  9809. return $role !== '旁白';
  9810. });
  9811. if (empty($generated_roles)) {
  9812. $validation_failed = true;
  9813. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9814. }
  9815. // 仅当存在强制主体设定时校验主体列表
  9816. if (!$validation_failed && !empty($extra_roles)) {
  9817. $expected_roles = array_keys($extra_roles);
  9818. // 找出生成的主体中不在预期列表中的主体
  9819. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9820. if (!empty($invalid_roles)) {
  9821. $validation_failed = true;
  9822. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9823. }
  9824. }
  9825. // 仅当存在强制场景设定时校验场景列表
  9826. if (!$validation_failed && !empty($extra_scenes)) {
  9827. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9828. $expected_scenes = array_keys($extra_scenes);
  9829. // 找出生成的场景中不在预期列表中的场景
  9830. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9831. if (!empty($invalid_scenes)) {
  9832. $validation_failed = true;
  9833. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9834. }
  9835. }
  9836. // 仅当存在强制道具设定时校验道具列表
  9837. if (!$validation_failed && !empty($extra_props)) {
  9838. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9839. $expected_props = array_keys($extra_props);
  9840. // 找出生成的道具中不在预期列表中的道具
  9841. $invalid_props = array_diff($generated_props, $expected_props);
  9842. if (!empty($invalid_props)) {
  9843. $validation_failed = true;
  9844. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9845. }
  9846. }
  9847. }
  9848. } else {
  9849. // 如果没有anime_script_id,只检查是否有acts数据
  9850. if (empty($episode_arr['acts'])) {
  9851. $validation_failed = true;
  9852. $validation_error_msg = '未生成分镜剧本相关的内容';
  9853. } else {
  9854. // 校验主体列表:不能为空主体(旁白不算)
  9855. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9856. // 过滤掉"旁白"角色
  9857. $generated_roles = array_filter($generated_roles, function($role) {
  9858. return $role !== '旁白';
  9859. });
  9860. if (empty($generated_roles)) {
  9861. $validation_failed = true;
  9862. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9863. }
  9864. }
  9865. }
  9866. // 重试逻辑
  9867. while ($validation_failed && $retry_count < $max_retries) {
  9868. $retry_count++;
  9869. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9870. 'reason' => $validation_error_msg,
  9871. 'anime_id' => $anime_id,
  9872. 'episode_number' => $episode_number
  9873. ]);
  9874. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9875. 'reason' => $validation_error_msg,
  9876. 'anime_id' => $anime_id
  9877. ]);
  9878. // 发送流式重试提示
  9879. yield [
  9880. 'type' => 'retry',
  9881. 'retry_count' => $retry_count,
  9882. 'reason' => $validation_error_msg
  9883. ];
  9884. // 构建重试提示词
  9885. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9886. if ($anime_script_id) {
  9887. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9888. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9889. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9890. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9891. } else {
  9892. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9893. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9894. }
  9895. // 添加重试消息到messages
  9896. $messages[] = [
  9897. 'role' => 'assistant',
  9898. 'content' => $fullContent
  9899. ];
  9900. $messages[] = [
  9901. 'role' => 'user',
  9902. 'content' => $retry_prompt
  9903. ];
  9904. // 更新post_data的messages
  9905. $post_data['messages'] = $messages;
  9906. // 重新调用API
  9907. try {
  9908. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9909. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9910. } else if (in_array($model, $this->gpt_text_models)) {
  9911. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9912. } else if (in_array($model, $this->gemini_text_models)) {
  9913. // Gemini 模型使用 Gemini API
  9914. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9915. } else {
  9916. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9917. }
  9918. // 处理流式输出
  9919. $fullContent = '';
  9920. $fullReasoningContent = '';
  9921. foreach ($streamGenerator as $chunk) {
  9922. if (isset($chunk['type'])) {
  9923. if ($chunk['type'] === 'done') {
  9924. $fullContent = $chunk['full_content'];
  9925. $fullReasoningContent = $chunk['full_reasoning'];
  9926. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9927. } else {
  9928. yield $chunk;
  9929. }
  9930. }
  9931. }
  9932. // 重新解析内容
  9933. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9934. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9935. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9936. $episode_arr = handleEpisodeContentForAce($fullContent);
  9937. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9938. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9939. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9940. // }
  9941. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9942. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9943. // 重新验证
  9944. $validation_failed = false;
  9945. $validation_error_msg = '';
  9946. if ($anime_script_id) {
  9947. if (empty($episode_arr['acts'])) {
  9948. $validation_failed = true;
  9949. $validation_error_msg = '未生成分镜剧本相关的内容';
  9950. } else {
  9951. // 校验主体列表:不能为空主体(旁白不算)
  9952. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9953. // 过滤掉"旁白"角色
  9954. $generated_roles = array_filter($generated_roles, function($role) {
  9955. return $role !== '旁白';
  9956. });
  9957. if (empty($generated_roles)) {
  9958. $validation_failed = true;
  9959. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9960. }
  9961. // 仅当存在强制主体设定时校验主体列表
  9962. if (!$validation_failed && !empty($extra_roles)) {
  9963. $expected_roles = array_keys($extra_roles);
  9964. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9965. if (!empty($invalid_roles)) {
  9966. $validation_failed = true;
  9967. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9968. }
  9969. }
  9970. // 仅当存在强制场景设定时校验场景列表
  9971. if (!$validation_failed && !empty($extra_scenes)) {
  9972. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9973. $expected_scenes = array_keys($extra_scenes);
  9974. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9975. if (!empty($invalid_scenes)) {
  9976. $validation_failed = true;
  9977. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9978. }
  9979. }
  9980. // 仅当存在强制道具设定时校验道具列表
  9981. if (!$validation_failed && !empty($extra_props)) {
  9982. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9983. $expected_props = array_keys($extra_props);
  9984. $invalid_props = array_diff($generated_props, $expected_props);
  9985. if (!empty($invalid_props)) {
  9986. $validation_failed = true;
  9987. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9988. }
  9989. }
  9990. }
  9991. } else {
  9992. if (empty($episode_arr['acts'])) {
  9993. $validation_failed = true;
  9994. $validation_error_msg = '未生成分镜剧本相关的内容';
  9995. } else {
  9996. // 校验主体列表:不能为空主体(旁白不算)
  9997. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9998. // 过滤掉"旁白"角色
  9999. $generated_roles = array_filter($generated_roles, function($role) {
  10000. return $role !== '旁白';
  10001. });
  10002. if (empty($generated_roles)) {
  10003. $validation_failed = true;
  10004. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10005. }
  10006. }
  10007. }
  10008. } catch (\Exception $e) {
  10009. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  10010. 'trace' => $e->getTraceAsString()
  10011. ]);
  10012. break;
  10013. }
  10014. }
  10015. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  10016. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  10017. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  10018. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  10019. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  10020. if ($validation_failed && $retry_count >= $max_retries) {
  10021. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  10022. 'retry_count' => $retry_count,
  10023. 'last_error' => $validation_error_msg
  10024. ]);
  10025. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  10026. 'error' => $validation_error_msg,
  10027. 'anime_id' => $anime_id
  10028. ]);
  10029. $validation_failed = false;
  10030. $validation_error_msg = '';
  10031. }
  10032. // 如果重试后仍然失败
  10033. if ($validation_failed) {
  10034. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  10035. 'retry_count' => $retry_count,
  10036. 'last_error' => $validation_error_msg
  10037. ]);
  10038. try {
  10039. $now = date('Y-m-d H:i:s');
  10040. $records = [
  10041. [
  10042. 'uid' => $uid,
  10043. 'anime_id' => $anime_id,
  10044. 'sequence' => $episode_number,
  10045. 'role' => 'user',
  10046. 'content' => $prompt,
  10047. 'created_at' => $now,
  10048. 'updated_at' => $now
  10049. ],
  10050. [
  10051. 'uid' => $uid,
  10052. 'anime_id' => $anime_id,
  10053. 'sequence' => $episode_number,
  10054. 'role' => 'assistant',
  10055. 'content' => $fullContent,
  10056. 'created_at' => $now,
  10057. 'updated_at' => $now
  10058. ]
  10059. ];
  10060. DB::table('mp_anime_records')->insert($records);
  10061. } catch (\Exception $e) {
  10062. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  10063. }
  10064. yield [
  10065. 'type' => 'done',
  10066. 'episode' => [],
  10067. 'answer' => $fullContent,
  10068. 'reasoning' => $fullReasoningContent,
  10069. 'usage' => $usage,
  10070. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  10071. ];
  10072. return;
  10073. }
  10074. // 验证成功,记录日志
  10075. if ($retry_count > 0) {
  10076. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  10077. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  10078. }
  10079. // 老逻辑
  10080. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  10081. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  10082. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  10083. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  10084. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  10085. $existing_props = is_array($existing_props) ? $existing_props : [];
  10086. $now = date('Y-m-d H:i:s');
  10087. try {
  10088. DB::beginTransaction();
  10089. $saveResult = $this->saveEpisodeVersionData(
  10090. $anime_id,
  10091. $episode_number,
  10092. $episode_arr,
  10093. $existing_roles,
  10094. $existing_scenes,
  10095. $existing_props,
  10096. $current_episode,
  10097. $base_episode,
  10098. $is_regenerate_version,
  10099. $content,
  10100. $now,
  10101. $ref_products
  10102. );
  10103. $episode = $saveResult['episode'];
  10104. $episode_id = $saveResult['episode_id'];
  10105. $merged_roles = $saveResult['merged_roles'];
  10106. $merged_scenes = $saveResult['merged_scenes'];
  10107. $merged_props = $saveResult['merged_props'];
  10108. $record_content = $origin_prompt;
  10109. if ($uploaded_content !== '') {
  10110. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  10111. }
  10112. $records = [
  10113. [
  10114. 'uid' => $uid,
  10115. 'anime_id' => $anime_id,
  10116. 'role' => 'user',
  10117. 'content' => $record_content,
  10118. 'sequence' => $episode_number,
  10119. 'episode_id' => $episode_id,
  10120. 'created_at' => $now,
  10121. 'updated_at' => $now
  10122. ],
  10123. [
  10124. 'uid' => $uid,
  10125. 'anime_id' => $anime_id,
  10126. 'role' => 'assistant',
  10127. 'content' => $fullContent,
  10128. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10129. 'sequence' => $episode_number,
  10130. 'episode_id' => $episode_id,
  10131. 'created_at' => $now,
  10132. 'updated_at' => $now
  10133. ]
  10134. ];
  10135. $boolen4 = DB::table('mp_anime_records')->insert($records);
  10136. if (!$boolen4) {
  10137. Utils::throwError('20003:对话记录保存失败');
  10138. }
  10139. // 保存模型到anime表
  10140. $update_anime_data = [
  10141. 'model' => $model,
  10142. 'updated_at' => $now
  10143. ];
  10144. if ($uploaded_content) {
  10145. $update_anime_data['content'] = $uploaded_content;
  10146. }
  10147. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  10148. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10149. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10150. 'anime_id' => $anime_id,
  10151. 'episode_number' => $episode_number,
  10152. 'model' => $model,
  10153. 'source' => 'chatForAce',
  10154. ]);
  10155. }catch (\Exception $e) {
  10156. DB::rollBack();
  10157. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  10158. yield [
  10159. 'type' => 'done',
  10160. 'answer' => $fullContent,
  10161. 'reasoning' => $fullReasoningContent,
  10162. 'usage' => $usage,
  10163. 'error' => $e->getMessage(),
  10164. ];
  10165. return;
  10166. }
  10167. DB::commit();
  10168. if ($is_global_generate_pics) {
  10169. // // 批量生成全局角色图片
  10170. // $this->batchSetGlobalRoleImg([
  10171. // 'anime_id' => $anime_id,
  10172. // ], true);
  10173. // // 批量生成全局场景图片
  10174. // $this->batchSetGlobalSceneImg([
  10175. // 'anime_id' => $anime_id,
  10176. // ], true);
  10177. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10178. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10179. }
  10180. $episode['episode_id'] = $episode_id;
  10181. $episode['roles'] = $merged_roles;
  10182. $episode['scenes'] = $merged_scenes;
  10183. $episode['props'] = $merged_props;
  10184. $episode['end_episode_sequence'] = $end_episode_sequence;
  10185. // 获取mp_animes表中的视频参数
  10186. $episode['video_params'] = [
  10187. 'video_model' => getProp($anime, 'video_model'),
  10188. 'video_resolution' => getProp($anime, 'video_resolution'),
  10189. 'ratio' => getProp($anime, 'video_ratio'),
  10190. ];
  10191. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10192. yield [
  10193. 'type' => 'done',
  10194. 'episode' => $episode,
  10195. 'answer' => $fullContent,
  10196. 'reasoning' => $fullReasoningContent,
  10197. 'usage' => $usage
  10198. ];
  10199. }
  10200. /**
  10201. * chatForAce的非流式版本 - 用于定时任务
  10202. * 只获取最终 type=done 的数据,并验证必要字段
  10203. *
  10204. * @param array $data 请求数据
  10205. * @return array 生成结果
  10206. */
  10207. public function chatForAceNonStream($data) {
  10208. $finalResult = null;
  10209. // 调用流式方法,只保存 type=done 的数据
  10210. foreach ($this->chatForAce($data) as $chunk) {
  10211. // 只关注最终结果
  10212. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  10213. $finalResult = $chunk;
  10214. break; // 找到 done 就退出循环
  10215. }
  10216. }
  10217. // 验证最终结果
  10218. if (!$finalResult) {
  10219. return ['error' => '生成失败:未获取到最终结果'];
  10220. }
  10221. // 检查是否有错误
  10222. if (isset($finalResult['error']) && $finalResult['error']) {
  10223. return $finalResult;
  10224. }
  10225. // 验证必要字段
  10226. $episode = $finalResult['episode'] ?? [];
  10227. // 验证 roles(旁白不算主体,过滤后不能为空)
  10228. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  10229. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  10230. }
  10231. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  10232. return $role !== '旁白';
  10233. });
  10234. if (empty($nonNarratorRoles)) {
  10235. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  10236. }
  10237. // 验证 scenes
  10238. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  10239. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  10240. }
  10241. // 验证 props(道具可以为空,但必须存在且为数组)
  10242. if (!isset($episode['props']) || !is_array($episode['props'])) {
  10243. $episode['props'] = [];
  10244. }
  10245. // 验证 acts(分镜剧本)
  10246. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  10247. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  10248. }
  10249. // 更新验证后的 episode 数据
  10250. $finalResult['episode'] = $episode;
  10251. // 记录验证成功日志
  10252. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  10253. 'roles_count' => count($episode['roles']),
  10254. 'scenes_count' => count($episode['scenes']),
  10255. 'props_count' => count($episode['props']),
  10256. 'acts_count' => count($episode['acts'])
  10257. ]);
  10258. return $finalResult;
  10259. }
  10260. /**
  10261. * 批量生成多个分集
  10262. *
  10263. * @param array $data 请求数据
  10264. * @return array 任务信息
  10265. */
  10266. public function batchGenerateEpisodes($data) {
  10267. $uid = Site::getUid();
  10268. $cpid = Site::getCpid();
  10269. $anime_id = getProp($data, 'anime_id');
  10270. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  10271. $start_episode_number = getProp($data, 'start_episode_number');
  10272. $end_episode_number = getProp($data, 'end_episode_number');
  10273. if (!$anime_id) {
  10274. Utils::throwError('20003:anime_id参数缺失');
  10275. }
  10276. if ($generate_episode_number < 1) {
  10277. Utils::throwError('20003:生成集数必须大于0');
  10278. }
  10279. // 获取动漫信息
  10280. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10281. if (!$anime) {
  10282. Utils::throwError('20003:该剧集不存在');
  10283. }
  10284. // 检查是否是全能模式
  10285. if ((int)getProp($anime, 'ace_mode') !== 1) {
  10286. Utils::throwError('20003:只有全能模式才支持批量生成');
  10287. }
  10288. // 检查是否是多剧集模式
  10289. if ((int)getProp($anime, 'is_multi') !== 1) {
  10290. Utils::throwError('20003:单剧集不支持批量生成');
  10291. }
  10292. // 指定起始/结束剧集序号时的校验
  10293. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  10294. || ($end_episode_number !== null && $end_episode_number !== '');
  10295. if ($hasSpecifiedRange) {
  10296. if ($start_episode_number === null || $start_episode_number === ''
  10297. || $end_episode_number === null || $end_episode_number === '') {
  10298. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  10299. }
  10300. $start_episode_number = (int)$start_episode_number;
  10301. $end_episode_number = (int)$end_episode_number;
  10302. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  10303. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  10304. }
  10305. $startEpisodeNumber = $start_episode_number;
  10306. $endEpisodeNumber = $end_episode_number;
  10307. } else {
  10308. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  10309. $currentMaxEpisode = DB::table('mp_anime_episodes')
  10310. ->where('anime_id', $anime_id)
  10311. ->where('is_default', 1)
  10312. ->max('episode_number');
  10313. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  10314. // 确定起始集数
  10315. $startEpisodeNumber = $currentMaxEpisode + 1;
  10316. // 计算结束集数
  10317. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  10318. }
  10319. // 本次实际生成的集数
  10320. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  10321. // 检查是否超过总集数限制
  10322. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  10323. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  10324. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  10325. }
  10326. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  10327. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  10328. ->where('anime_id', $anime_id)
  10329. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10330. ->pluck('episode_number')
  10331. ->unique()
  10332. ->sort()
  10333. ->values()
  10334. ->toArray();
  10335. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  10336. ->where('anime_id', $anime_id)
  10337. ->where('is_default', 1)
  10338. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10339. ->pluck('episode_number')
  10340. ->unique()
  10341. ->sort()
  10342. ->values()
  10343. ->toArray();
  10344. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  10345. $duplicateMessages = [];
  10346. if (!empty($duplicatedBatchEpisodes)) {
  10347. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  10348. }
  10349. if (!empty($duplicatedAnimeEpisodes)) {
  10350. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  10351. }
  10352. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  10353. }
  10354. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  10355. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  10356. ->where('anime_id', $anime_id)
  10357. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10358. ->whereIn('status', ['pending', 'processing', 'completed'])
  10359. ->count();
  10360. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  10361. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  10362. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  10363. if ($needEpisodeCount > 0) {
  10364. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  10365. }
  10366. $now = date('Y-m-d H:i:s');
  10367. $createdTasks = [];
  10368. $skippedTasks = [];
  10369. // 为每一集创建详情记录
  10370. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  10371. // 检查是否已有该集的任务记录
  10372. $existingTask = DB::table('mp_batch_episode_generation_details')
  10373. ->where('anime_id', $anime_id)
  10374. ->where('episode_number', $episodeNumber)
  10375. ->first();
  10376. if ($existingTask) {
  10377. // 如果已存在且未完成,跳过
  10378. if (in_array($existingTask->status, ['pending', 'processing'])) {
  10379. $skippedTasks[] = $episodeNumber;
  10380. continue;
  10381. }
  10382. // 如果是失败状态,可以重新创建(删除旧记录)
  10383. if ($existingTask->status === 'failed') {
  10384. DB::table('mp_batch_episode_generation_details')
  10385. ->where('id', $existingTask->id)
  10386. ->delete();
  10387. }
  10388. // 如果是已完成状态,也跳过
  10389. if ($existingTask->status === 'completed') {
  10390. $skippedTasks[] = $episodeNumber;
  10391. continue;
  10392. }
  10393. }
  10394. // 准备任务数据
  10395. $taskData = [
  10396. 'anime_id' => $anime_id,
  10397. 'uid' => $uid,
  10398. 'cpid' => $cpid,
  10399. 'episode_number' => $episodeNumber,
  10400. 'status' => 'pending',
  10401. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  10402. 'retry_count' => 0,
  10403. 'created_at' => $now,
  10404. 'updated_at' => $now
  10405. ];
  10406. // 创建任务记录
  10407. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  10408. if ($taskId) {
  10409. $createdTasks[] = $episodeNumber;
  10410. }
  10411. }
  10412. if (empty($createdTasks)) {
  10413. if (!empty($skippedTasks)) {
  10414. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  10415. } else {
  10416. Utils::throwError('20003:创建批量生成任务失败');
  10417. }
  10418. }
  10419. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  10420. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  10421. $uid,
  10422. $cpid,
  10423. $anime_id,
  10424. $generate_episode_number,
  10425. $startEpisodeNumber,
  10426. $endEpisodeNumber
  10427. );
  10428. return [
  10429. 'anime_id' => $anime_id,
  10430. 'start_episode' => $startEpisodeNumber,
  10431. 'end_episode' => $endEpisodeNumber,
  10432. 'total_episodes' => $totalEpisodeCount,
  10433. 'created_episodes' => $createdTasks,
  10434. 'skipped_episodes' => $skippedTasks,
  10435. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  10436. "已创建: " . implode(',', $createdTasks) .
  10437. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  10438. 'task_center_id' => $taskCenterId
  10439. ];
  10440. }
  10441. /**
  10442. * 根据入参创建或复用批量生成分集的任务中心记录
  10443. *
  10444. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  10445. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  10446. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  10447. *
  10448. * @param int|string $uid
  10449. * @param int|string $cpid
  10450. * @param int|string $anime_id
  10451. * @param int $generate_episode_number
  10452. * @param int $startEpisodeNumber
  10453. * @param int $endEpisodeNumber
  10454. * @return int 任务中心ID
  10455. */
  10456. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  10457. $params = [
  10458. 'anime_id' => (int)$anime_id,
  10459. 'generate_episode_number' => (int)$generate_episode_number,
  10460. 'start_episode' => (int)$startEpisodeNumber,
  10461. 'end_episode' => (int)$endEpisodeNumber,
  10462. ];
  10463. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  10464. $paramsMd5 = md5(json_encode([
  10465. 'anime_id' => (int)$anime_id,
  10466. 'generate_episode_number' => (int)$generate_episode_number,
  10467. 'start_episode' => (int)$startEpisodeNumber,
  10468. 'end_episode' => (int)$endEpisodeNumber,
  10469. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  10470. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  10471. $existing = DB::table('mp_task_center')
  10472. ->where('uid', (int)$uid)
  10473. ->where('cpid', (int)$cpid)
  10474. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10475. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10476. ->where('params_md5', $paramsMd5)
  10477. ->orderBy('id', 'desc')
  10478. ->first();
  10479. if ($existing) {
  10480. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  10481. 'anime_id' => $anime_id,
  10482. 'task_center_id' => $existing->id,
  10483. 'params_md5' => $paramsMd5,
  10484. ]);
  10485. return (int)$existing->id;
  10486. }
  10487. $now = date('Y-m-d H:i:s');
  10488. DB::table('mp_task_center')->insertOrIgnore([
  10489. 'uid' => (int)$uid,
  10490. 'cpid' => (int)$cpid,
  10491. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  10492. 'title' => '批量生成分集',
  10493. 'ref_task_id' => 0,
  10494. 'status' => MpTaskCenter::STATUS_PROCESSING,
  10495. 'result' => null,
  10496. 'error_message' => null,
  10497. 'prompt' => null,
  10498. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  10499. 'params_md5' => $paramsMd5,
  10500. 'created_at' => $now,
  10501. 'updated_at' => $now,
  10502. ]);
  10503. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  10504. $taskId = (int)DB::table('mp_task_center')
  10505. ->where('uid', (int)$uid)
  10506. ->where('cpid', (int)$cpid)
  10507. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10508. ->where('params_md5', $paramsMd5)
  10509. ->orderBy('id', 'desc')
  10510. ->value('id');
  10511. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  10512. 'anime_id' => $anime_id,
  10513. 'task_center_id' => $taskId,
  10514. 'params_md5' => $paramsMd5,
  10515. ]);
  10516. return $taskId;
  10517. }
  10518. /**
  10519. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  10520. *
  10521. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  10522. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  10523. * 统一汇总更新,避免在每个更新点重复处理。
  10524. *
  10525. * @param int|string $animeId
  10526. * @return int 更新的任务中心记录数
  10527. */
  10528. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  10529. $animeId = (int)$animeId;
  10530. $updated = 0;
  10531. // 该 anime 是否还有未结束的详情任务
  10532. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  10533. ->where('anime_id', $animeId)
  10534. ->whereIn('status', ['pending', 'processing'])
  10535. ->exists();
  10536. // 扫描该 anime 相关的未完成任务中心记录
  10537. $tasks = DB::table('mp_task_center')
  10538. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10539. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10540. ->orderBy('id', 'desc')
  10541. ->limit(500)
  10542. ->get();
  10543. if ($hasUnfinished && !$tasks) {
  10544. return 0;
  10545. }
  10546. foreach ($tasks as $task) {
  10547. try {
  10548. $taskParams = json_decode((string)$task->params, true);
  10549. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  10550. continue;
  10551. }
  10552. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  10553. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  10554. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  10555. continue;
  10556. }
  10557. $details = DB::table('mp_batch_episode_generation_details')
  10558. ->where('anime_id', $animeId)
  10559. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  10560. ->get();
  10561. // 该批次范围内存在缺失记录,等待下一次检查
  10562. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  10563. continue;
  10564. }
  10565. $completedEpisodes = [];
  10566. $failedEpisodes = [];
  10567. $allFinished = true;
  10568. foreach ($details as $detail) {
  10569. if ($detail->status === 'completed') {
  10570. $completedEpisodes[] = $detail->episode_number;
  10571. } elseif ($detail->status === 'failed') {
  10572. $failedEpisodes[] = [
  10573. 'episode_number' => $detail->episode_number,
  10574. 'error_message' => $detail->error_message ?? '',
  10575. ];
  10576. } else {
  10577. // pending/processing(防御处理,正常不会走到)
  10578. $allFinished = false;
  10579. break;
  10580. }
  10581. }
  10582. if (!$allFinished) {
  10583. continue;
  10584. }
  10585. $result = json_encode([
  10586. 'anime_id' => $animeId,
  10587. 'start_episode' => $startEpisode,
  10588. 'end_episode' => $endEpisode,
  10589. 'total_episodes' => count($details),
  10590. 'completed_count' => count($completedEpisodes),
  10591. 'failed_count' => count($failedEpisodes),
  10592. 'completed_episodes' => $completedEpisodes,
  10593. 'failed_episodes' => $failedEpisodes,
  10594. ], JSON_UNESCAPED_UNICODE);
  10595. DB::table('mp_task_center')
  10596. ->where('id', $task->id)
  10597. ->update([
  10598. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  10599. 'result' => $result,
  10600. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  10601. 'updated_at' => date('Y-m-d H:i:s'),
  10602. ]);
  10603. $updated++;
  10604. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  10605. 'task_center_id' => $task->id,
  10606. 'anime_id' => $animeId,
  10607. 'start_episode' => $startEpisode,
  10608. 'end_episode' => $endEpisode,
  10609. ]);
  10610. } catch (\Exception $e) {
  10611. dLog('command')->error('更新批量生成分集任务中心异常', [
  10612. 'task_center_id' => $task->id,
  10613. 'anime_id' => $animeId,
  10614. 'error' => $e->getMessage(),
  10615. ]);
  10616. }
  10617. }
  10618. return $updated;
  10619. }
  10620. /**
  10621. * 获取批量生成任务状态
  10622. *
  10623. * @param array $data 请求数据
  10624. * @return array 任务状态信息
  10625. */
  10626. public function getBatchGenerationTaskStatus($data) {
  10627. $anime_id = getProp($data, 'anime_id');
  10628. if (!$anime_id) {
  10629. Utils::throwError('20003:anime_id参数缺失');
  10630. }
  10631. // 获取该anime的所有任务
  10632. $tasks = DB::table('mp_batch_episode_generation_details')
  10633. ->where('anime_id', $anime_id)
  10634. ->orderBy('episode_number')
  10635. ->get()
  10636. ->map(function($item) {
  10637. return [
  10638. 'id' => $item->id,
  10639. 'episode_number' => $item->episode_number,
  10640. 'status' => $item->status,
  10641. 'error_message' => $item->error_message,
  10642. 'retry_count' => $item->retry_count,
  10643. 'created_at' => $item->created_at,
  10644. 'updated_at' => $item->updated_at,
  10645. 'completed_at' => $item->completed_at
  10646. ];
  10647. })
  10648. ->toArray();
  10649. if (empty($tasks)) {
  10650. Utils::throwError('20003:该剧集没有批量生成任务');
  10651. }
  10652. // 统计各状态数量
  10653. $totalCount = count($tasks);
  10654. $pendingCount = 0;
  10655. $processingCount = 0;
  10656. $completedCount = 0;
  10657. $failedCount = 0;
  10658. $failed_episodes = [];
  10659. foreach ($tasks as $task) {
  10660. switch ($task['status']) {
  10661. case 'pending':
  10662. $pendingCount++;
  10663. break;
  10664. case 'processing':
  10665. $processingCount++;
  10666. break;
  10667. case 'completed':
  10668. $completedCount++;
  10669. break;
  10670. case 'failed':
  10671. $failedCount++;
  10672. // 组装失败分集对象(新对象):分集序号、错误原因
  10673. $failed_episodes[] = [
  10674. 'episode_number' => $task['episode_number'],
  10675. 'error_message' => $task['error_message'] ?? ''
  10676. ];
  10677. break;
  10678. }
  10679. }
  10680. // 计算进度百分比
  10681. $progress = 0;
  10682. if ($totalCount > 0) {
  10683. $progress = round(($completedCount / $totalCount) * 100, 2);
  10684. }
  10685. // 判断整体状态
  10686. $overallStatus = 'processing';
  10687. if ($completedCount === $totalCount) {
  10688. $overallStatus = 'completed';
  10689. } elseif ($pendingCount === $totalCount) {
  10690. $overallStatus = 'pending';
  10691. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  10692. $overallStatus = 'failed';
  10693. }
  10694. return [
  10695. 'anime_id' => $anime_id,
  10696. 'total_episodes' => $totalCount,
  10697. 'pending_count' => $pendingCount,
  10698. 'processing_count' => $processingCount,
  10699. 'completed_count' => $completedCount,
  10700. 'failed_count' => $failedCount,
  10701. 'progress' => $progress,
  10702. 'overall_status' => $overallStatus,
  10703. 'failed_episodes' => $failed_episodes,
  10704. 'tasks' => $tasks
  10705. ];
  10706. }
  10707. /**
  10708. * 将生成内容中不在强制列表中的资源合并进强制列表
  10709. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  10710. *
  10711. * @param array $generated 生成内容中的资源列表
  10712. * @param array $forced 强制资源列表(key为资源名称)
  10713. * @param string $type 资源类型:role、scene、prop
  10714. * @return array
  10715. */
  10716. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  10717. {
  10718. foreach ($generated as $item) {
  10719. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  10720. if ($name === null || $name === '') {
  10721. continue;
  10722. }
  10723. if ($name === '旁白') {
  10724. continue;
  10725. }
  10726. if (!isset($forced[$name])) {
  10727. $forced[$name] = $item;
  10728. }
  10729. }
  10730. return $forced;
  10731. }
  10732. /**
  10733. * 智能匹配并替换主体和场景名称
  10734. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10735. *
  10736. * @param array $episode_arr 解析后的剧集数据
  10737. * @param array $extra_roles 强制主体设定(key为主体名称)
  10738. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10739. * @return array 替换后的剧集数据
  10740. */
  10741. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10742. $replaced_count = 0;
  10743. // 1. 处理主体列表
  10744. if (!empty($episode_arr['roles'])) {
  10745. foreach ($episode_arr['roles'] as &$role) {
  10746. $generated_role_name = $role['role'] ?? '';
  10747. // 跳过旁白
  10748. if ($generated_role_name === '旁白') {
  10749. continue;
  10750. }
  10751. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10752. if (!isset($extra_roles[$generated_role_name])) {
  10753. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10754. if ($matched_role) {
  10755. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10756. $role['role'] = $matched_role;
  10757. $replaced_count++;
  10758. }
  10759. }
  10760. }
  10761. }
  10762. // 2. 处理场景列表
  10763. if (!empty($episode_arr['scenes'])) {
  10764. foreach ($episode_arr['scenes'] as &$scene) {
  10765. $generated_scene_name = $scene['scene'] ?? '';
  10766. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10767. if (!isset($extra_scenes[$generated_scene_name])) {
  10768. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10769. if ($matched_scene) {
  10770. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10771. $scene['scene'] = $matched_scene;
  10772. $replaced_count++;
  10773. }
  10774. }
  10775. }
  10776. }
  10777. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10778. if (!empty($episode_arr['acts'])) {
  10779. foreach ($episode_arr['acts'] as &$act) {
  10780. if (!empty($act['segments'])) {
  10781. foreach ($act['segments'] as &$segment) {
  10782. if (!empty($segment['segment_content'])) {
  10783. $original_content = $segment['segment_content'];
  10784. $replaced_content = $original_content;
  10785. // 替换场景名 - 在文本中查找并替换
  10786. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10787. // 尝试找到可能的短名称
  10788. $potential_short_names = [];
  10789. // 提取场景名的主要部分(冒号之前)
  10790. if (mb_strpos($full_scene_name, ':') !== false) {
  10791. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10792. $potential_short_names[] = $short_name;
  10793. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10794. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10795. $potential_short_names[] = $short_name;
  10796. }
  10797. // 替换场景字段中的短名称
  10798. foreach ($potential_short_names as $short_name) {
  10799. if ($short_name !== $full_scene_name) {
  10800. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10801. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10802. if ($new_content !== $replaced_content) {
  10803. $replaced_content = $new_content;
  10804. $replaced_count++;
  10805. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10806. }
  10807. }
  10808. }
  10809. }
  10810. // 替换配音角色名(跳过旁白)
  10811. foreach (array_keys($extra_roles) as $full_role_name) {
  10812. if ($full_role_name === '旁白') {
  10813. continue;
  10814. }
  10815. // 尝试找到可能的短名称
  10816. $potential_short_names = [];
  10817. // 提取角色名的主要部分(短横线之前)
  10818. if (mb_strpos($full_role_name, '-') !== false) {
  10819. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10820. $potential_short_names[] = $short_name;
  10821. }
  10822. // 替换配音台词中的短名称
  10823. foreach ($potential_short_names as $short_name) {
  10824. if ($short_name !== $full_role_name) {
  10825. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10826. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10827. if ($new_content !== $replaced_content) {
  10828. $replaced_content = $new_content;
  10829. $replaced_count++;
  10830. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10831. }
  10832. }
  10833. }
  10834. }
  10835. // 如果有替换,更新segment_content
  10836. if ($replaced_content !== $original_content) {
  10837. $segment['segment_content'] = $replaced_content;
  10838. }
  10839. }
  10840. }
  10841. }
  10842. }
  10843. }
  10844. if ($replaced_count > 0) {
  10845. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10846. 'replaced_count' => $replaced_count
  10847. ]);
  10848. }
  10849. return $episode_arr;
  10850. }
  10851. /**
  10852. * 查找匹配的名称
  10853. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10854. *
  10855. * @param string $generated_name 生成的名称
  10856. * @param array $expected_names 预期的名称列表
  10857. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10858. */
  10859. private function findMatchingName($generated_name, $expected_names) {
  10860. if (empty($generated_name)) {
  10861. return null;
  10862. }
  10863. // 尝试精确匹配
  10864. if (in_array($generated_name, $expected_names)) {
  10865. return $generated_name;
  10866. }
  10867. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10868. foreach ($expected_names as $expected_name) {
  10869. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10870. if (mb_strpos($expected_name, $generated_name) === 0) {
  10871. return $expected_name;
  10872. }
  10873. }
  10874. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10875. // 这样可以处理一些变体,但优先级较低
  10876. foreach ($expected_names as $expected_name) {
  10877. if (mb_strpos($expected_name, $generated_name) !== false) {
  10878. return $expected_name;
  10879. }
  10880. }
  10881. return null;
  10882. }
  10883. /**
  10884. * 重新生成分段剧本
  10885. * @param array $data 包含以下字段:
  10886. * - prompt: string|null 用户修改要求(可选)
  10887. * - template_id: int|null 提示词模板ID(可选)
  10888. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10889. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10890. * @return array 返回生成结果
  10891. */
  10892. public function regenerateSegmentScript($data) {
  10893. $uid = Site::getUid();
  10894. $prompt = trim((string)getProp($data, 'prompt', ''));
  10895. $template_id = getProp($data, 'template_id', 0);
  10896. $act_id = getProp($data, 'act_id', 0);
  10897. $episode_id = getProp($data, 'episode_id', 0);
  10898. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  10899. // 验证:prompt和template_id至少提供一个
  10900. if (empty($prompt) && empty($template_id)) {
  10901. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10902. }
  10903. // 验证:act_id和episode_id二选一
  10904. if (empty($act_id) && empty($episode_id)) {
  10905. Utils::throwError('20003:请提供片段ID或剧集ID');
  10906. }
  10907. if (!empty($act_id) && !empty($episode_id)) {
  10908. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10909. }
  10910. // 积分余额预检(仅剧集ID模式收费)
  10911. if (!empty($episode_id)) {
  10912. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  10913. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  10914. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10915. }
  10916. // 如果提供了template_id,获取模板提示词
  10917. $template_prompt = '';
  10918. if ($template_id > 0) {
  10919. $template = DB::table('mp_prompt_templates')
  10920. ->where('id', $template_id)
  10921. ->where('is_deleted', 0)
  10922. ->first();
  10923. if (!$template) {
  10924. Utils::throwError('20003:提示词模板不存在或已删除');
  10925. }
  10926. $template_prompt = $template->template_prompt ?? '';
  10927. }
  10928. // 合并用户提示词和模板提示词
  10929. $final_prompt = '';
  10930. if (!empty($template_prompt)) {
  10931. $final_prompt = $template_prompt;
  10932. if (!empty($prompt)) {
  10933. $final_prompt .= "\n\n补充要求:" . $prompt;
  10934. }
  10935. } else {
  10936. $final_prompt = $prompt;
  10937. }
  10938. // 获取需要重新生成的内容参考
  10939. $reference_content = '';
  10940. $target_episode_id = 0;
  10941. $target_anime_id = 0;
  10942. $target_episode_number = 0;
  10943. if ($act_id > 0) {
  10944. // 单个片段模式:获取该片段的内容
  10945. $segment = DB::table('mp_episode_segments')
  10946. ->where('id', $act_id)
  10947. ->first();
  10948. if (!$segment) {
  10949. Utils::throwError('20003:片段不存在');
  10950. }
  10951. $target_episode_id = $segment->episode_id;
  10952. $target_anime_id = $segment->anime_id;
  10953. $target_episode_number = $segment->episode_number;
  10954. $reference_content = $segment->act_content ?? '';
  10955. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10956. } else {
  10957. // 整个剧集模式:获取所有片段的内容
  10958. $segments = DB::table('mp_episode_segments')
  10959. ->where('episode_id', $episode_id)
  10960. ->orderBy('act_number')
  10961. ->get();
  10962. if ($segments->isEmpty()) {
  10963. Utils::throwError('20003:该剧集没有片段数据');
  10964. }
  10965. $target_episode_id = $episode_id;
  10966. $target_anime_id = $segments[0]->anime_id;
  10967. $target_episode_number = $segments[0]->episode_number;
  10968. // 拼接所有片段内容,保留格式用于AI理解
  10969. $act_contents = [];
  10970. foreach ($segments as $seg) {
  10971. $act_number = $seg->act_number;
  10972. $act_content = $seg->act_content ?? '';
  10973. if (!empty($act_content)) {
  10974. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  10975. }
  10976. }
  10977. $reference_content = implode("\n\n", $act_contents);
  10978. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  10979. if ($episode_content) {
  10980. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  10981. }else {
  10982. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10983. }
  10984. }
  10985. if (empty($reference_content)) {
  10986. Utils::throwError('20003:没有可参考的片段内容');
  10987. }
  10988. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  10989. $episode = DB::table('mp_anime_episodes')
  10990. ->where('id', $target_episode_id)
  10991. ->first();
  10992. if (!$episode) {
  10993. Utils::throwError('20003:剧集不存在');
  10994. }
  10995. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  10996. $anime_script_id = getProp($anime, 'script_id');
  10997. $intro = $episode->intro ?? '';
  10998. $art_style = $episode->art_style ?? '';
  10999. $roles = json_decode($episode->roles ?? '[]', true);
  11000. $scenes = json_decode($episode->scenes ?? '[]', true);
  11001. $props = json_decode($episode->props ?? '[]', true);
  11002. // 构建提示词中的主体列表和场景列表参考
  11003. $roles_ref = '';
  11004. if (!empty($roles) && is_array($roles)) {
  11005. $roles_list = [];
  11006. foreach ($roles as $role) {
  11007. $role_name = getProp($role, 'role', '');
  11008. $role_desc = getProp($role, 'description', '');
  11009. $pic_prompt = getProp($role, 'pic_prompt', '');
  11010. $voice_prompt = getProp($role, 'voice_prompt', '');
  11011. if (!empty($role_name)) {
  11012. $role_line = $role_name;
  11013. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  11014. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  11015. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  11016. $roles_list[] = $role_line;
  11017. }
  11018. }
  11019. if (!empty($roles_list)) {
  11020. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  11021. }
  11022. }
  11023. $scenes_ref = '';
  11024. if (!empty($scenes) && is_array($scenes)) {
  11025. $scenes_list = [];
  11026. foreach ($scenes as $scene) {
  11027. $scene_name = getProp($scene, 'scene', '');
  11028. $scene_desc = getProp($scene, 'description', '');
  11029. $pic_prompt = getProp($scene, 'pic_prompt', '');
  11030. if (!empty($scene_name)) {
  11031. $scene_line = $scene_name;
  11032. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  11033. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  11034. $scenes_list[] = $scene_line;
  11035. }
  11036. }
  11037. if (!empty($scenes_list)) {
  11038. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  11039. }
  11040. }
  11041. $props_ref = '';
  11042. if (!empty($props) && is_array($props)) {
  11043. $props_list = [];
  11044. foreach ($props as $prop) {
  11045. $prop_name = getProp($prop, 'prop', '');
  11046. $prop_desc = getProp($prop, 'description', '');
  11047. $pic_prompt = getProp($prop, 'pic_prompt', '');
  11048. if (!empty($prop_name)) {
  11049. $prop_line = $prop_name;
  11050. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  11051. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  11052. $props_list[] = $prop_line;
  11053. }
  11054. }
  11055. if (!empty($props_list)) {
  11056. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  11057. }
  11058. }
  11059. // 构建美术风格参考
  11060. $art_style_ref = '';
  11061. if (!empty($art_style)) {
  11062. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  11063. }
  11064. // 构建内容简介参考
  11065. $intro_ref = '';
  11066. if (!empty($intro)) {
  11067. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  11068. }
  11069. // 构建完整的AI提示词
  11070. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  11071. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  11072. $user_prompt .= $intro_ref;
  11073. $user_prompt .= $art_style_ref;
  11074. $user_prompt .= $reference_content;
  11075. // $user_prompt .= $roles_ref;
  11076. // $user_prompt .= $scenes_ref;
  11077. $system_prompt = "\n\n【强制要求】\n";
  11078. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  11079. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  11080. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  11081. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  11082. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  11083. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  11084. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  11085. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  11086. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  11087. ###分段剧本
  11088. 片段数量:8
  11089. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  11090. ##片段1
  11091. 时长:12s
  11092. 分镜1
  11093. 出场角色:刀疤脸
  11094. 场景:边境小镇街道
  11095. 出场道具:酒杯-高脚杯
  11096. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  11097. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  11098. 配音台词:
  11099. 背景音效:
  11100. 分镜2
  11101. 出场角色:刀疤脸
  11102. 场景:悦来酒馆
  11103. 出场道具:酒杯-高脚杯
  11104. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  11105. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  11106. 配音台词:
  11107. 背景音效:
  11108. 分镜3
  11109. 出场角色:刀疤脸
  11110. 场景:悦来酒馆
  11111. 出场道具:酒杯-高脚杯
  11112. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  11113. 运镜:从中景推向令牌特写。
  11114. 配音台词:
  11115. 背景音效:
  11116. 分镜4
  11117. 出场角色:刀疤脸
  11118. 场景:悦来酒馆
  11119. 出场道具:酒杯-高脚杯
  11120. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  11121. 运镜:极速推向酒水溅起的瞬间。
  11122. 配音台词:
  11123. 背景音效:
  11124. 分镜5
  11125. 出场角色:刀疤脸
  11126. 场景:悦来酒馆
  11127. 出场道具:酒杯-高脚杯
  11128. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  11129. 运镜:固定机位,利用倾斜构图制造压迫感。
  11130. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  11131. 背景音效:";
  11132. // 获取模型配置
  11133. $model = getProp($data, 'model');
  11134. if (!$model) {
  11135. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  11136. }
  11137. // 验证模型是否在可用模型表中
  11138. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11139. $model = 'deepseek-v4-pro';
  11140. }
  11141. // 模型兼容性处理
  11142. $thinkingMode = 'disabled';
  11143. $reasoningEffort = 'high';
  11144. if ($model === 'deepseek-chat') {
  11145. $model = 'deepseek-v4-flash';
  11146. $thinkingMode = 'disabled';
  11147. } elseif ($model === 'deepseek-reasoner') {
  11148. $model = 'deepseek-v4-flash';
  11149. $thinkingMode = 'enabled';
  11150. }
  11151. // 构建消息
  11152. $messages = [
  11153. [
  11154. 'role' => 'system',
  11155. 'content' => $system_prompt
  11156. ],
  11157. [
  11158. 'role' => 'user',
  11159. 'content' => $user_prompt
  11160. ]
  11161. ];
  11162. // dd($messages);
  11163. // 构建请求参数
  11164. $post_data = [
  11165. 'model' => $model,
  11166. 'messages' => $messages,
  11167. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11168. 'frequency_penalty' => 0,
  11169. 'presence_penalty' => 0,
  11170. 'response_format' => ['type' => 'text'],
  11171. 'thinking' => ['type' => $thinkingMode],
  11172. 'stream' => false // 非流式输出
  11173. ];
  11174. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11175. // 调用AI生成新的分段剧本
  11176. try {
  11177. $fullContent = '';
  11178. $usage = [];
  11179. // 根据模型类型选择调用方法
  11180. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11181. // DeepSeek 官方模型使用 DeepSeek API
  11182. $chatResult = $this->chatOnly($post_data);
  11183. } else if (in_array($model, $this->gpt_text_models)) {
  11184. // GPT 模型使用 TokenRouter API
  11185. $chatResult = $this->gpt54ChatOnly($post_data);
  11186. } else {
  11187. // 其他模型使用火山引擎API
  11188. $chatResult = $this->volcEngineChatCompletion($post_data);
  11189. }
  11190. if (is_array($chatResult)) {
  11191. $fullContent = $chatResult['fullContent'] ?? '';
  11192. $usage = $chatResult['usage'] ?? [];
  11193. }
  11194. $generated_content = $fullContent;
  11195. if (empty($generated_content)) {
  11196. Utils::throwError('20003:AI生成内容为空,请重试');
  11197. }
  11198. // 解析生成的内容 - 按片段分割
  11199. $parsed_segments = [];
  11200. // 先在开头添加换行符,确保第1片段也能被正确分割
  11201. $normalizedText = "\n" . $generated_content;
  11202. $parts = preg_split('/\n\s*##/', $normalizedText);
  11203. foreach ($parts as $part) {
  11204. $part = trim($part);
  11205. if (empty($part)) continue;
  11206. // 匹配"片段X"格式
  11207. if (!preg_match('/^片段\d+/', $part)) {
  11208. continue;
  11209. }
  11210. // 分离标题和内容
  11211. $lines = explode("\n", $part, 2);
  11212. $actTitle = trim($lines[0]);
  11213. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  11214. // 解析标题,提取序号
  11215. $actNumber = 0;
  11216. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  11217. $actNumber = intval($segmentTitleMatch[1]);
  11218. } else {
  11219. $actNumber = count($parsed_segments) + 1;
  11220. }
  11221. // 提取时长(仅保留数字)
  11222. $actDuration = 0;
  11223. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  11224. $actDurationStr = trim($actDurationMatch[1]);
  11225. // 提取数字部分(支持整数和小数)
  11226. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  11227. $actDuration = (float)$numMatch[1];
  11228. }
  11229. }
  11230. // 清理act_content:去除时长、旁白音色等非分镜内容行
  11231. // 只保留分镜内容,并确保分镜标记使用【】格式
  11232. $cleaned_content = '';
  11233. $content_lines = explode("\n", $actContent);
  11234. $is_capturing = false; // 标记是否开始捕获分镜内容
  11235. $count = 0;
  11236. foreach ($content_lines as $line) {
  11237. $trimmed_line = trim($line);
  11238. // 跳过时长和旁白音色行
  11239. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  11240. continue;
  11241. }
  11242. // 检测是否是分镜开始
  11243. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  11244. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  11245. $count++;
  11246. $is_capturing = true;
  11247. // 如果没有【】,则添加
  11248. if (!preg_match('/^【/u', $trimmed_line)) {
  11249. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  11250. }
  11251. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  11252. }
  11253. // 如果已经开始捕获,则添加该行
  11254. if ($is_capturing && !empty($trimmed_line)) {
  11255. $cleaned_content .= $trimmed_line."\n";
  11256. }
  11257. }
  11258. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  11259. $parsed_segments[] = [
  11260. 'act_number' => $actNumber,
  11261. 'act_title' => $actTitle,
  11262. 'act_duration' => $actDuration,
  11263. 'act_content' => $cleaned_content,
  11264. ];
  11265. }
  11266. if (empty($parsed_segments)) {
  11267. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  11268. }
  11269. // 收集所有资产名称(角色、场景、道具)
  11270. $product_names = [];
  11271. // 收集角色名称
  11272. if (!empty($roles) && is_array($roles)) {
  11273. foreach ($roles as $role) {
  11274. $role_name = getProp($role, 'role', '');
  11275. if (!empty($role_name)) {
  11276. $product_names[] = $role_name;
  11277. }
  11278. }
  11279. }
  11280. // 收集场景名称
  11281. if (!empty($scenes) && is_array($scenes)) {
  11282. foreach ($scenes as $scene) {
  11283. $scene_name = getProp($scene, 'scene', '');
  11284. if (!empty($scene_name)) {
  11285. $product_names[] = $scene_name;
  11286. }
  11287. }
  11288. }
  11289. // 收集道具名称
  11290. if (!empty($props) && is_array($props)) {
  11291. foreach ($props as $prop) {
  11292. $prop_name = getProp($prop, 'prop', '');
  11293. if (!empty($prop_name)) {
  11294. $product_names[] = $prop_name;
  11295. }
  11296. }
  11297. }
  11298. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  11299. $product_names = array_unique($product_names);
  11300. usort($product_names, function($a, $b) {
  11301. return mb_strlen($b) - mb_strlen($a);
  11302. });
  11303. // 处理每个片段的 act_show_content
  11304. foreach ($parsed_segments as &$segment) {
  11305. $act_content = getProp($segment, 'act_content', '');
  11306. if (empty($act_content)) {
  11307. $segment['act_show_content'] = '';
  11308. continue;
  11309. }
  11310. $processed_content = $act_content;
  11311. // 统一替换所有资产名称为 {资产名} 格式
  11312. // 使用占位符避免嵌套替换问题
  11313. $placeholder_map = [];
  11314. $placeholder_index = 0;
  11315. foreach ($product_names as $product_name) {
  11316. // 转义特殊字符
  11317. $escaped_product = preg_quote($product_name, '/');
  11318. // 检查是否匹配且未被 {} 包裹
  11319. $processed_content = preg_replace_callback(
  11320. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  11321. function($matches) use (&$placeholder_map, &$placeholder_index) {
  11322. // 使用唯一占位符
  11323. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  11324. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  11325. $placeholder_index++;
  11326. return $placeholder;
  11327. },
  11328. $processed_content
  11329. );
  11330. }
  11331. // 将所有占位符替换回实际内容
  11332. foreach ($placeholder_map as $placeholder => $replacement) {
  11333. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  11334. }
  11335. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  11336. $shot_counter = 0;
  11337. $processed_content = preg_replace_callback(
  11338. '/【(?:镜头|分镜)(\d+)】/u',
  11339. function($matches) use (&$shot_counter) {
  11340. $shot_counter++;
  11341. return '【镜头' . $shot_counter . '】';
  11342. },
  11343. $processed_content
  11344. );
  11345. $segment['act_show_content'] = $processed_content;
  11346. }
  11347. unset($segment); // 解除引用
  11348. // 保存到数据库
  11349. $now = date('Y-m-d H:i:s');
  11350. $saved_acts = []; // 用于记录保存后的片段信息
  11351. if ($act_id > 0) {
  11352. // 单个片段模式:更新单条记录
  11353. if (count($parsed_segments) > 0) {
  11354. $new_segment = $parsed_segments[0];
  11355. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  11356. if ($check_mode === 1) {
  11357. return [
  11358. 'check_mode' => 1,
  11359. 'act_id' => (int)$act_id,
  11360. 'act_title' => getProp($new_segment, 'act_title', ''),
  11361. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11362. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  11363. ];
  11364. }
  11365. $update_data = [
  11366. 'act_content' => getProp($new_segment, 'act_content', ''),
  11367. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  11368. 'act_title' => getProp($new_segment, 'act_title', ''),
  11369. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11370. 'updated_at' => $now,
  11371. ];
  11372. DB::table('mp_episode_segments')
  11373. ->where('id', $act_id)
  11374. ->update($update_data);
  11375. // 获取更新后的记录
  11376. $updated_act = DB::table('mp_episode_segments')
  11377. ->where('id', $act_id)
  11378. ->first();
  11379. if ($updated_act) {
  11380. $saved_acts[] = [
  11381. 'act_id' => $updated_act->id,
  11382. 'act_number' => $updated_act->act_number,
  11383. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  11384. 'act_content' => $updated_act->act_content,
  11385. 'act_show_content' => $updated_act->act_show_content,
  11386. 'video_url' => $updated_act->video_url ?? '',
  11387. 'video_duration' => $updated_act->video_duration ?? 0,
  11388. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  11389. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  11390. ];
  11391. }
  11392. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  11393. }
  11394. } else {
  11395. // 整个剧集模式:删除原有记录并批量保存新记录
  11396. DB::beginTransaction();
  11397. try {
  11398. // 删除原有的所有片段记录
  11399. DB::table('mp_episode_segments')
  11400. ->where('episode_id', $target_episode_id)
  11401. ->delete();
  11402. // 批量插入新的片段记录
  11403. $segments_to_insert = [];
  11404. foreach ($parsed_segments as $index => $segment) {
  11405. $act_number = $index + 1;
  11406. $segments_to_insert[] = [
  11407. 'anime_id' => $target_anime_id,
  11408. 'episode_id' => $target_episode_id,
  11409. 'episode_number' => $target_episode_number,
  11410. 'act_number' => $act_number,
  11411. 'act_title' => getProp($segment, 'act_title', ''),
  11412. 'act_duration' => getProp($segment, 'act_duration', 0),
  11413. 'act_content' => getProp($segment, 'act_content', ''),
  11414. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  11415. 'created_at' => $now,
  11416. 'updated_at' => $now,
  11417. ];
  11418. }
  11419. if (!empty($segments_to_insert)) {
  11420. DB::table('mp_episode_segments')->insert($segments_to_insert);
  11421. }
  11422. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11423. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11424. 'anime_id' => $target_anime_id,
  11425. 'episode_id' => $target_episode_id,
  11426. 'model' => $model,
  11427. 'source' => 'regenerateSegmentScript',
  11428. ]);
  11429. DB::commit();
  11430. // 查询保存后的所有片段记录
  11431. $saved_segments = DB::table('mp_episode_segments')
  11432. ->where('episode_id', $target_episode_id)
  11433. ->orderBy('act_number')
  11434. ->get();
  11435. foreach ($saved_segments as $saved_segment) {
  11436. $saved_acts[] = [
  11437. 'act_id' => $saved_segment->id,
  11438. 'act_number' => $saved_segment->act_number,
  11439. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  11440. 'act_content' => $saved_segment->act_content,
  11441. 'act_show_content' => $saved_segment->act_show_content,
  11442. 'video_url' => $saved_segment->video_url ?? '',
  11443. 'video_duration' => $saved_segment->video_duration ?? 0,
  11444. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  11445. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  11446. ];
  11447. }
  11448. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  11449. 'episode_id' => $target_episode_id,
  11450. 'segments_count' => count($segments_to_insert)
  11451. ]);
  11452. } catch (\Exception $e) {
  11453. DB::rollBack();
  11454. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  11455. Utils::throwError('20003:保存失败,请重试');
  11456. }
  11457. }
  11458. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  11459. return [
  11460. 'anime_id' => $target_anime_id,
  11461. 'episode_id' => $target_episode_id,
  11462. 'title' => getProp($episode, 'title', ''),
  11463. 'episode_number' => $target_episode_number,
  11464. 'is_generated' => getProp($episode, 'is_generated', 0),
  11465. 'acts' => $saved_acts,
  11466. ];
  11467. } catch (\Exception $e) {
  11468. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  11469. throw $e;
  11470. }
  11471. }
  11472. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  11473. {
  11474. $episode_arr = [
  11475. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  11476. 'intro' => getProp($script_arr, 'intro'),
  11477. 'art_style' => getProp($script_arr, 'art_style'),
  11478. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  11479. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  11480. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  11481. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  11482. ];
  11483. if (empty($episode_arr['acts'])) {
  11484. $fallback_episode_arr = handleEpisodeContent($fullContent);
  11485. if (!empty($fallback_episode_arr['acts'])) {
  11486. $episode_arr = array_merge($fallback_episode_arr, [
  11487. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  11488. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  11489. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  11490. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  11491. ]);
  11492. }
  11493. }
  11494. // if (!getProp($episode_arr, 'episode_title')) {
  11495. // $episode_title = '';
  11496. // $episodes = getProp($script_arr, 'episodes', []);
  11497. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  11498. // $episode_title = '第1集:' . $episodes[0]['title'];
  11499. // }
  11500. // if (!$episode_title) {
  11501. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  11502. // }
  11503. // $episode_arr['episode_title'] = $episode_title;
  11504. // }
  11505. return $episode_arr;
  11506. }
  11507. private function saveEpisodeVersionData(
  11508. int $anime_id,
  11509. int $episode_number,
  11510. array $episode_arr,
  11511. array $existing_roles,
  11512. array $existing_scenes,
  11513. array $existing_props,
  11514. $current_episode,
  11515. $base_episode,
  11516. bool $is_regenerate_version,
  11517. string $content,
  11518. string $now,
  11519. array $ref_products = []
  11520. ): array {
  11521. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  11522. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  11523. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  11524. // 过滤掉关键字段为空的条目
  11525. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  11526. return !empty($item['role'] ?? null);
  11527. }));
  11528. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  11529. return !empty($item['scene'] ?? null);
  11530. }));
  11531. $merged_props = array_values(array_filter($generated_props, function ($item) {
  11532. return !empty($item['prop'] ?? null);
  11533. }));
  11534. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  11535. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  11536. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  11537. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11538. $ace_mode = getProp($anime, 'ace_mode');
  11539. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  11540. $global_roles = json_decode(getProp($anime, 'roles'), true);
  11541. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  11542. $global_roles = is_array($global_roles) ? $global_roles : [];
  11543. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  11544. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  11545. $art_style_type = getProp($anime, 'art_style_type');
  11546. // 检查并创建 roles 的图片生成任务
  11547. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  11548. // 检查并创建 scenes 的图片生成任务
  11549. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  11550. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  11551. if ($arr && is_array($arr)) {
  11552. $merged_roles = $arr['roles'];
  11553. $merged_scenes = $arr['scenes'];
  11554. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  11555. }
  11556. // 确保数据是数组类型
  11557. if (!is_array($merged_roles)) {
  11558. dLog('deepseek')->error('merged_roles不是数组类型', [
  11559. 'type' => gettype($merged_roles),
  11560. 'value' => $merged_roles
  11561. ]);
  11562. $merged_roles = [];
  11563. }
  11564. if (!is_array($merged_scenes)) {
  11565. dLog('deepseek')->error('merged_scenes不是数组类型', [
  11566. 'type' => gettype($merged_scenes),
  11567. 'value' => $merged_scenes
  11568. ]);
  11569. $merged_scenes = [];
  11570. }
  11571. if (!is_array($merged_props)) {
  11572. dLog('deepseek')->error('merged_props不是数组类型', [
  11573. 'type' => gettype($merged_props),
  11574. 'value' => $merged_props
  11575. ]);
  11576. $merged_props = [];
  11577. }
  11578. // 同步新出现的主体和场景到全局
  11579. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  11580. $role_arr = [];
  11581. foreach ($merged_roles as $item) {
  11582. $role_arr[$item['role']] = $item;
  11583. }
  11584. $version_count = DB::table('mp_anime_episodes')
  11585. ->where('anime_id', $anime_id)
  11586. ->where('episode_number', $episode_number)
  11587. ->count('id');
  11588. $episode = [
  11589. 'anime_id' => $anime_id,
  11590. 'episode_number' => $episode_number,
  11591. 'title' => getProp($episode_arr, 'episode_title'),
  11592. 'content' => $content,
  11593. 'intro' => getProp($episode_arr, 'intro'),
  11594. 'art_style' => getProp($episode_arr, 'art_style'),
  11595. 'roles' => json_encode($merged_roles, 256),
  11596. 'scenes' => json_encode($merged_scenes, 256),
  11597. 'props' => json_encode($merged_props, 256),
  11598. 'generate_status' => '待执行',
  11599. 'generate_at' => $now,
  11600. 'is_default' => 1,
  11601. 'updated_at' => $now,
  11602. ];
  11603. $del_flag = false;
  11604. if ($is_regenerate_version) {
  11605. DB::table('mp_anime_episodes')
  11606. ->where('anime_id', $anime_id)
  11607. ->where('episode_number', $episode_number)
  11608. ->update(['is_default' => 0, 'updated_at' => $now]);
  11609. $episode['sequence'] = $version_count + 1;
  11610. $episode['created_at'] = $now;
  11611. $episode['cpid'] = Site::getCpid();
  11612. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11613. if (!$episode_id) {
  11614. Utils::throwError('20003:创建剧集版本失败');
  11615. }
  11616. } else {
  11617. $target_episode = $current_episode ?: $base_episode;
  11618. if ($target_episode) {
  11619. $episode_id = getProp($target_episode, 'id');
  11620. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  11621. DB::table('mp_anime_episodes')
  11622. ->where('anime_id', $anime_id)
  11623. ->where('episode_number', $episode_number)
  11624. ->where('id', '<>', $episode_id)
  11625. ->update(['is_default' => 0, 'updated_at' => $now]);
  11626. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  11627. if ($boolen === false) {
  11628. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11629. Utils::throwError('20003:分集内容保存失败');
  11630. }
  11631. $del_flag = true;
  11632. } else {
  11633. DB::table('mp_anime_episodes')
  11634. ->where('anime_id', $anime_id)
  11635. ->where('episode_number', $episode_number)
  11636. ->update(['is_default' => 0, 'updated_at' => $now]);
  11637. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  11638. $episode['created_at'] = $now;
  11639. $episode['cpid'] = Site::getCpid();
  11640. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11641. if (!$episode_id) {
  11642. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  11643. Utils::throwError('20003:分集内容保存失败');
  11644. }
  11645. }
  11646. }
  11647. $segments = [];
  11648. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11649. // 如果是第2集及以后,获取上一集的主体音色数据
  11650. $previous_roles_voice = [];
  11651. if ($episode_number >= 2) {
  11652. $previous_episode = DB::table('mp_anime_episodes')
  11653. ->where('anime_id', $anime_id)
  11654. ->where('episode_number', $episode_number - 1)
  11655. ->where('is_default', 1)
  11656. ->first();
  11657. if ($previous_episode) {
  11658. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  11659. if (is_array($previous_roles)) {
  11660. foreach ($previous_roles as $prev_role) {
  11661. $role_name = getProp($prev_role, 'role');
  11662. if ($role_name) {
  11663. $previous_roles_voice[$role_name] = [
  11664. 'voice_name' => getProp($prev_role, 'voice_name'),
  11665. 'voice_type' => getProp($prev_role, 'voice_type'),
  11666. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  11667. ];
  11668. $voice_prompt = getProp($prev_role, 'voice_prompt');
  11669. if ($voice_prompt) {
  11670. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  11671. }
  11672. }
  11673. }
  11674. }
  11675. }
  11676. }
  11677. // 将继承的音色数据同步到当前集的主体列表
  11678. if (!empty($previous_roles_voice)) {
  11679. foreach ($merged_roles as &$role) {
  11680. $role_name = getProp($role, 'role');
  11681. if ($role_name && isset($previous_roles_voice[$role_name])) {
  11682. // 强制继承上一集的音色数据
  11683. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  11684. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  11685. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  11686. // 如果上一集有 voice_prompt 则继承,否则跳过
  11687. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  11688. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  11689. }
  11690. }
  11691. }
  11692. unset($role); // 解除引用
  11693. // 更新 role_arr 以便后续使用
  11694. $role_arr = [];
  11695. foreach ($merged_roles as $item) {
  11696. $role_arr[$item['role']] = $item;
  11697. }
  11698. }
  11699. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  11700. $emotion_list = array_flip($emotion_list);
  11701. foreach ($acts as $act) {
  11702. $act_segments = getProp($act, 'segments', []);
  11703. if (!is_array($act_segments)) {
  11704. continue;
  11705. }
  11706. if ((int)$ace_mode === 1) {
  11707. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  11708. $merged_parts = [];
  11709. foreach ($act_segments as $seg) {
  11710. $seg_num = getProp($seg, 'segment_number');
  11711. $seg_content = getProp($seg, 'segment_content');
  11712. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  11713. }
  11714. $act_content = implode("\n", $merged_parts);
  11715. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11716. $segments[] = [
  11717. 'anime_id' => $anime_id,
  11718. 'episode_id' => $episode_id,
  11719. 'episode_number' => $episode_number,
  11720. 'act_number' => getProp($act, 'act_number'),
  11721. 'act_title' => getProp($act, 'act_title'),
  11722. 'act_duration' => getProp($act, 'act_duration'),
  11723. 'act_content' => $act_content,
  11724. 'created_at' => $now,
  11725. 'updated_at' => $now
  11726. ];
  11727. } else {
  11728. foreach ($act_segments as $segment) {
  11729. $voice_actor = getProp($segment, 'voice_actor');
  11730. // 优先从上一集继承音色数据
  11731. $timbre_info = [];
  11732. if (isset($previous_roles_voice[$voice_actor])) {
  11733. // 从上一集继承音色数据
  11734. $timbre_info = $previous_roles_voice[$voice_actor];
  11735. } elseif (isset($role_arr[$voice_actor])) {
  11736. // 使用当前集的主体音色数据
  11737. $timbre_info = $role_arr[$voice_actor];
  11738. }
  11739. $voice_type = getProp($timbre_info, 'voice_type');
  11740. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  11741. if ($timbre_emotion) {
  11742. $timbre_emotion = explode(',', $timbre_emotion);
  11743. } else {
  11744. $timbre_emotion = [];
  11745. }
  11746. $emotion = getProp($segment, 'emotion', '中性');
  11747. if (!in_array($emotion, $timbre_emotion)) {
  11748. $emotion = '中性';
  11749. }
  11750. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11751. $segments[] = [
  11752. 'anime_id' => $anime_id,
  11753. 'episode_id' => $episode_id,
  11754. 'episode_number' => $episode_number,
  11755. 'act_number' => getProp($act, 'act_number'),
  11756. 'act_title' => getProp($act, 'act_title'),
  11757. 'act_duration' => getProp($act, 'act_duration'),
  11758. 'segment_id' => getProp($segment, 'segment_id'),
  11759. 'segment_number' => getProp($segment, 'segment_number'),
  11760. 'segment_content' => getProp($segment, 'segment_content'),
  11761. 'description' => getProp($segment, 'description'),
  11762. 'composition' => getProp($segment, 'composition'),
  11763. 'camera_movement' => getProp($segment, 'camera_movement'),
  11764. 'voice_actor' => $voice_actor,
  11765. 'dialogue' => getProp($segment, 'dialogue'),
  11766. 'frame_type' => getProp($segment, 'frame_type'),
  11767. 'scene' => getProp($segment, 'scene'),
  11768. 'characters' => getProp($segment, 'characters'),
  11769. 'tail_frame' => getProp($segment, 'tail_frame'),
  11770. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11771. 'voice_type' => $voice_type,
  11772. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11773. 'emotion' => $emotion,
  11774. 'emotion_type' => $emotion_type,
  11775. 'gender' => getProp($segment, 'gender', '0'),
  11776. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11777. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11778. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11779. 'pitch' => getProp($segment, 'pitch', 0),
  11780. 'created_at' => $now,
  11781. 'updated_at' => $now
  11782. ];
  11783. }
  11784. }
  11785. }
  11786. if ($segments) {
  11787. if ($del_flag) {
  11788. DB::table('mp_episode_segments')
  11789. ->where('anime_id', $anime_id)
  11790. ->where('episode_id', $episode_id)
  11791. ->delete();
  11792. }
  11793. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11794. if (!$boolen) {
  11795. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11796. Utils::throwError('20003:分镜内容保存失败');
  11797. }
  11798. }
  11799. dLog('deepseek')->info('segments', $segments);
  11800. // ace_mode=1: acts 返回值按合并格式调整
  11801. if ((int)$ace_mode === 1) {
  11802. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11803. $act_map = [];
  11804. foreach ($table_act_data as $item) {
  11805. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11806. }
  11807. $restructured_acts = [];
  11808. foreach ($acts as $act) {
  11809. $act_segments = getProp($act, 'segments', []);
  11810. if (!is_array($act_segments)) {
  11811. continue;
  11812. }
  11813. $merged_parts = [];
  11814. foreach ($act_segments as $seg) {
  11815. $seg_num = getProp($seg, 'segment_number');
  11816. $seg_content = getProp($seg, 'segment_content');
  11817. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11818. }
  11819. $act_content = implode("\n", $merged_parts);
  11820. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11821. $restructured_acts[] = [
  11822. 'anime_id' => $anime_id,
  11823. 'episode_id' => $episode_id,
  11824. 'episode_number' => $episode_number,
  11825. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11826. 'act_number' => getProp($act, 'act_number'),
  11827. 'act_title' => getProp($act, 'act_title'),
  11828. 'act_duration' => getProp($act, 'act_duration'),
  11829. 'act_content' => $act_content,
  11830. 'created_at' => $now,
  11831. 'updated_at' => $now,
  11832. ];
  11833. }
  11834. $acts = $restructured_acts;
  11835. }
  11836. $episode['episode_id'] = $episode_id;
  11837. $episode['roles'] = $merged_roles;
  11838. $episode['scenes'] = $merged_scenes;
  11839. $episode['props'] = $merged_props;
  11840. $episode['acts'] = $acts;
  11841. return [
  11842. 'episode' => $episode,
  11843. 'episode_id' => $episode_id,
  11844. 'merged_roles' => $merged_roles,
  11845. 'merged_scenes' => $merged_scenes,
  11846. 'merged_props' => $merged_props,
  11847. ];
  11848. }
  11849. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11850. {
  11851. $content = '';
  11852. foreach ($items as $item) {
  11853. $name = trim((string)getProp($item, $nameKey));
  11854. if ($name === '' || $name === '旁白') {
  11855. continue;
  11856. }
  11857. $description = trim((string)getProp($item, 'description'));
  11858. $content .= $name . ': ' . $description;
  11859. if ($nameKey == 'role') {
  11860. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11861. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11862. $voice_name = trim(getProp($item, 'voice_name'));
  11863. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11864. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  11865. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11866. }else {
  11867. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11868. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11869. }
  11870. $content .= "\n";
  11871. }
  11872. return trim($content);
  11873. }
  11874. private function getEpisodeChatContent($animeId, $sequence, $content) {
  11875. if ((int)$sequence <= 0) {
  11876. return [];
  11877. }
  11878. $origin_content = '';
  11879. if ($content) {
  11880. $origin_content = '本集剧情内容:'.$content;
  11881. }else {
  11882. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  11883. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  11884. }
  11885. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  11886. // 获取分集信息
  11887. $episode = DB::table('mp_anime_episodes')
  11888. ->where('anime_id', $animeId)
  11889. ->where('episode_number', $sequence)
  11890. ->where('is_default', 1)
  11891. ->first();
  11892. if (!$episode) {
  11893. return [];
  11894. }
  11895. $episode_id = getProp($episode, 'id');
  11896. $episode_number = getProp($episode, 'episode_number');
  11897. $title = getProp($episode, 'title');
  11898. $intro = getProp($episode, 'intro');
  11899. $art_style = getProp($episode, 'art_style');
  11900. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11901. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11902. // 组装纯文本内容
  11903. $content = '';
  11904. // 添加分集标题和梗概
  11905. $content .= "###第{$episode_number}集:{$title}\n\n";
  11906. $content .= "###故事梗概\n";
  11907. $content .= trim($intro) . "\n\n";
  11908. // 添加美术风格
  11909. $content .= "###美术风格\n";
  11910. $content .= trim($art_style) . "\n\n";
  11911. // 添加主体列表
  11912. $content .= "###主体列表\n";
  11913. $pangbai_voice_prompt = "";
  11914. foreach ($roles as $role) {
  11915. $name = getProp($role, 'role');
  11916. $description = getProp($role, 'description');
  11917. $pic_prompt = getProp($role, 'pic_prompt');
  11918. $voice_prompt = getProp($role, 'voice_prompt');
  11919. $voice_name = getProp($role, 'voice_name');
  11920. $content .= "{$name}: {$description}";
  11921. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11922. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11923. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11924. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  11925. $content .= "\n";
  11926. }
  11927. $content .= "\n";
  11928. // 添加场景列表
  11929. $content .= "###场景列表\n";
  11930. foreach ($scenes as $scene) {
  11931. $name = getProp($scene, 'scene');
  11932. $description = getProp($scene, 'description');
  11933. $pic_prompt = getProp($scene, 'pic_prompt');
  11934. $content .= "{$name}: {$description}";
  11935. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11936. $content .= "\n";
  11937. }
  11938. $content .= "\n";
  11939. // 获取分镜信息
  11940. $segments = DB::table('mp_episode_segments')
  11941. ->where('anime_id', $animeId)
  11942. ->where('episode_id', $episode_id)
  11943. ->orderBy('segment_number')
  11944. ->get();
  11945. if ($segments && count($segments) > 0) {
  11946. if ((int)$ace_mode === 1) {
  11947. $content .= "###分段剧本\n";
  11948. // 获取片段数量
  11949. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  11950. $content .= "片段数量:{$act_count}\n";
  11951. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  11952. $content .= "\n";
  11953. }else {
  11954. $content .= "###分镜剧本\n";
  11955. }
  11956. // 按幕分组
  11957. $currentAct = null;
  11958. foreach ($segments as $segment) {
  11959. $act_number = getProp($segment, 'act_number');
  11960. $act_title = getProp($segment, 'act_title');
  11961. $act_duration = getProp($segment, 'act_duration');
  11962. $segment_number = getProp($segment, 'segment_number');
  11963. $segment_content = getProp($segment, 'segment_content');
  11964. $scene_description = getProp($segment, 'scene_description');
  11965. $scene_name = getProp($segment, 'scene_name');
  11966. $composition = getProp($segment, 'composition');
  11967. $camera_movement = getProp($segment, 'camera_movement');
  11968. $voice_type = getProp($segment, 'voice_type');
  11969. $characters = getProp($segment, 'characters');
  11970. $dialogue = getProp($segment, 'dialogue');
  11971. $frame_type = getProp($segment, 'frame_type');
  11972. $tail_frame_description = getProp($segment, 'tail_frame_description');
  11973. // 判断是否是全能模式
  11974. if ((int)$ace_mode === 1) { // 全能模式
  11975. // 如果是新的分段,添加分段标题
  11976. if ($act_number !== $currentAct) {
  11977. $currentAct = $act_number;
  11978. $content .= "##{$act_title}\n";
  11979. $content .= "时长:{$act_duration}s\n";
  11980. }
  11981. }else {
  11982. // 如果是新的幕,添加幕标题
  11983. if ($act_number !== $currentAct) {
  11984. $currentAct = $act_number;
  11985. $content .= "##第{$act_number}幕:{$scene_name}\n";
  11986. }
  11987. }
  11988. // 添加分镜信息
  11989. $content .= "分镜{$segment_number}\n";
  11990. $content .= "分镜内容:\n{$segment_content}\n";
  11991. // $content .= "画面描述:{$scene_description}\n";
  11992. // $content .= "场景:{$scene_name}\n";
  11993. // $content .= "构图设计:{$composition}\n";
  11994. // $content .= "运镜调度:{$camera_movement}\n";
  11995. // if (!empty($voice_type)) {
  11996. // $content .= "配音角色:{$voice_type}\n";
  11997. // }
  11998. // if (!empty($characters)) {
  11999. // $content .= "出镜角色:{$characters}\n";
  12000. // }
  12001. // if (!empty($dialogue)) {
  12002. // $content .= "台词内容:\"{$dialogue}\"\n";
  12003. // }
  12004. // $content .= "画面类型:{$frame_type}\n";
  12005. // $content .= "尾帧描述:{$tail_frame_description}\n";
  12006. $content .= "\n";
  12007. }
  12008. }
  12009. $content = trim($content);
  12010. if($content) $content = "上集剧本内容:\n{$content}";
  12011. return [
  12012. [
  12013. 'role' => 'user',
  12014. 'content' => $origin_content
  12015. ],
  12016. [
  12017. 'role' => 'assistant',
  12018. 'content' => $content
  12019. ]
  12020. ];
  12021. }
  12022. private function getEpisodeChatMessages($animeId, $sequence): array
  12023. {
  12024. if ((int)$sequence <= 0) {
  12025. return [];
  12026. }
  12027. return DB::table('mp_anime_records')
  12028. ->where('anime_id', $animeId)
  12029. ->where('sequence', $sequence)
  12030. ->where('episode_id', '>', 0)
  12031. ->select('role', 'content')
  12032. ->orderBy('created_at')
  12033. ->orderBy('id')
  12034. ->get()
  12035. ->map(function ($value) {
  12036. return (array)$value;
  12037. })
  12038. ->toArray();
  12039. }
  12040. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  12041. {
  12042. $existingMap = [];
  12043. foreach ($existingItems as $item) {
  12044. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12045. if ($itemKey === '') {
  12046. continue;
  12047. }
  12048. $existingMap[$itemKey] = $item;
  12049. }
  12050. if (!$generatedItems) {
  12051. return array_values($existingItems);
  12052. }
  12053. $merged = [];
  12054. foreach ($generatedItems as $item) {
  12055. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12056. if ($itemKey === '') {
  12057. continue;
  12058. }
  12059. if (isset($existingMap[$itemKey])) {
  12060. if (trim((string)getProp($item, 'description')) === '') {
  12061. $merged[] = $existingMap[$itemKey];
  12062. continue;
  12063. }
  12064. // 检查内容是否发生变化
  12065. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  12066. if (!$isChanged) {
  12067. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  12068. $mergedItem = [
  12069. $nameKey => trim((string)getProp($item, $nameKey)),
  12070. 'description' => trim((string)getProp($item, 'description')),
  12071. ];
  12072. // 如果有 pic_prompt,添加到合并项中
  12073. $picPrompt = getProp($item, 'pic_prompt');
  12074. if (!empty($picPrompt)) {
  12075. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12076. }
  12077. // 继承现有项的 URL
  12078. $existingUrl = getProp($existingMap[$itemKey], 'url');
  12079. if (!empty($existingUrl)) {
  12080. $mergedItem['url'] = $existingUrl;
  12081. }
  12082. // 继承现有项的 task_id
  12083. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  12084. if (!empty($existingTaskId)) {
  12085. $mergedItem['task_id'] = $existingTaskId;
  12086. }
  12087. // 继承现有项的 task_status
  12088. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  12089. if (!empty($existingTaskStatus)) {
  12090. $mergedItem['task_status'] = $existingTaskStatus;
  12091. }
  12092. // 保留生成项的音色字段
  12093. $voiceName = getProp($item, 'voice_name');
  12094. if (!empty($voiceName)) {
  12095. $mergedItem['voice_name'] = $voiceName;
  12096. }
  12097. $voiceType = getProp($item, 'voice_type');
  12098. if (!empty($voiceType)) {
  12099. $mergedItem['voice_type'] = $voiceType;
  12100. }
  12101. $audioUrl = getProp($item, 'voice_audio_url');
  12102. if (!empty($audioUrl)) {
  12103. $mergedItem['voice_audio_url'] = $audioUrl;
  12104. }
  12105. $merged[] = $mergedItem;
  12106. } else {
  12107. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  12108. $mergedItem = [
  12109. $nameKey => trim((string)getProp($item, $nameKey)),
  12110. 'description' => trim((string)getProp($item, 'description')),
  12111. ];
  12112. // 如果有 pic_prompt,添加到合并项中
  12113. $picPrompt = getProp($item, 'pic_prompt');
  12114. if (!empty($picPrompt)) {
  12115. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12116. }
  12117. // 保留生成项的音色字段
  12118. $voiceName = getProp($item, 'voice_name');
  12119. if (!empty($voiceName)) {
  12120. $mergedItem['voice_name'] = $voiceName;
  12121. }
  12122. $voiceType = getProp($item, 'voice_type');
  12123. if (!empty($voiceType)) {
  12124. $mergedItem['voice_type'] = $voiceType;
  12125. }
  12126. $audioUrl = getProp($item, 'voice_audio_url');
  12127. if (!empty($audioUrl)) {
  12128. $mergedItem['voice_audio_url'] = $audioUrl;
  12129. }
  12130. // 不继承 URL、task_id 和 task_status(重置状态)
  12131. $merged[] = $mergedItem;
  12132. }
  12133. } else {
  12134. // 新增项,保留生成项的所有字段
  12135. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  12136. }
  12137. }
  12138. return $merged ?: array_values($existingItems);
  12139. }
  12140. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  12141. {
  12142. $resetItem = [
  12143. $nameKey => trim((string)getProp($item, $nameKey)),
  12144. 'description' => trim((string)getProp($item, 'description')),
  12145. ];
  12146. // 保留指定的字段
  12147. foreach ($preserveFields as $field) {
  12148. $value = getProp($item, $field);
  12149. if (!empty($value)) {
  12150. $resetItem[$field] = $value;
  12151. }
  12152. }
  12153. return $resetItem;
  12154. }
  12155. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  12156. {
  12157. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  12158. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  12159. if ($existingKey !== $generatedKey) {
  12160. return true;
  12161. }
  12162. // 比较 description 是否变化
  12163. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  12164. return true;
  12165. }
  12166. // 比较 pic_prompt 是否变化
  12167. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  12168. }
  12169. private function normalizeEpisodeResourceKey($value): string
  12170. {
  12171. $value = trim((string)$value);
  12172. if ($value === '') {
  12173. return '';
  12174. }
  12175. return strtolower((string)preg_replace('/\s+/u', '', $value));
  12176. }
  12177. // 生成全局角色图片
  12178. private function batchSetGlobalRoleImg($data, $is_force=false) {
  12179. $anime_id = getProp($data, 'anime_id');
  12180. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12181. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12182. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12183. $art_style = getProp($anime, 'art_style');
  12184. $update_flag = false;
  12185. foreach ($roles as &$role) {
  12186. $role_name = getProp($role, 'role');
  12187. if ($role_name == '旁白') continue;
  12188. // 优先使用 pic_prompt,如果没有则使用 description
  12189. $pic_prompt = getProp($role, 'pic_prompt');
  12190. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12191. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12192. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12193. // 参考图地址
  12194. $ref_img_url = getProp($role, 'url');
  12195. if (!$is_force && $ref_img_url) continue;
  12196. $update_flag = true;
  12197. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12198. try {
  12199. $params = [
  12200. 'prompt' => $description,
  12201. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  12202. 'ref_img_urls' => []
  12203. ];
  12204. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12205. $task_id = $task->id;
  12206. if (!$task_id) {
  12207. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  12208. }
  12209. $role['task_id'] = $task_id;
  12210. $role['task_status'] = 'processing';
  12211. } catch (\Exception $e) {
  12212. Utils::throwError("20003:" . $e->getMessage());
  12213. }
  12214. }
  12215. if (!$update_flag) return true;
  12216. // 保存角色信息
  12217. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12218. 'roles' => json_encode($roles, 256),
  12219. 'generate_status' => '执行中',
  12220. 'generate_at' => date('Y-m-d H:i:s'),
  12221. 'updated_at' => date('Y-m-d H:i:s')
  12222. ]);
  12223. if (!$boolen) {
  12224. Utils::throwError('20003:保存角色信息失败');
  12225. }
  12226. return $boolen;
  12227. }
  12228. // 生成全局场景图片
  12229. private function batchSetGlobalSceneImg($data, $is_force=false) {
  12230. $anime_id = getProp($data, 'anime_id');
  12231. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12232. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12233. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12234. $art_style = getProp($anime, 'art_style');
  12235. $update_flag = false;
  12236. foreach ($scenes as &$scene) {
  12237. $scene_name = getProp($scene, 'scene');
  12238. // 优先使用 pic_prompt,如果没有则使用 description
  12239. $pic_prompt = getProp($scene, 'pic_prompt');
  12240. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12241. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  12242. // 参考图地址
  12243. $ref_img_url = getProp($scene, 'url');
  12244. if (!$is_force && $ref_img_url) continue;
  12245. $update_flag = true;
  12246. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12247. try {
  12248. $params = [
  12249. 'prompt' => $description,
  12250. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  12251. 'ref_img_urls' => []
  12252. ];
  12253. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12254. $task_id = $task->id;
  12255. if (!$task_id) {
  12256. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  12257. }
  12258. $scene['task_id'] = $task_id;
  12259. $scene['task_status'] = 'processing';
  12260. } catch (\Exception $e) {
  12261. Utils::throwError("20003:" . $e->getMessage());
  12262. }
  12263. }
  12264. if (!$update_flag) return true;
  12265. // 保存角色信息
  12266. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12267. 'scenes' => json_encode($scenes, 256),
  12268. 'generate_status' => '执行中',
  12269. 'generate_at' => date('Y-m-d H:i:s'),
  12270. 'updated_at' => date('Y-m-d H:i:s')
  12271. ]);
  12272. if (!$boolen) {
  12273. Utils::throwError('20003:保存角色信息失败');
  12274. }
  12275. return $boolen;
  12276. }
  12277. // 生成分镜主体、场景和道具图片
  12278. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  12279. $character_prefix = '';
  12280. $scene_prefix = '';
  12281. $prop_prefix = '';
  12282. if ($art_style_type) {
  12283. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  12284. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  12285. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  12286. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  12287. }
  12288. $update_flag = false;
  12289. // 获取上一集的roles、scenes和props数据
  12290. $prev_roles = [];
  12291. $prev_scenes = [];
  12292. $prev_props = [];
  12293. if ($episode_number > 1) {
  12294. $prev_episode = DB::table('mp_anime_episodes')
  12295. ->where('anime_id', $anime_id)
  12296. ->where('episode_number', $episode_number - 1)
  12297. ->where('is_default', 1)
  12298. ->first();
  12299. if ($prev_episode) {
  12300. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  12301. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  12302. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  12303. dLog('deepseek')->info("获取上一集数据成功", [
  12304. 'anime_id' => $anime_id,
  12305. 'prev_episode_number' => $episode_number - 1,
  12306. 'prev_roles_count' => count($prev_roles),
  12307. 'prev_scenes_count' => count($prev_scenes),
  12308. 'prev_props_count' => count($prev_props)
  12309. ]);
  12310. }
  12311. }
  12312. // 处理角色图片生成
  12313. foreach ($roles as &$role) {
  12314. $role_name = getProp($role, 'role');
  12315. if ($role_name == '旁白') continue;
  12316. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  12317. if (isset($ref_products[$role_name])) {
  12318. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  12319. if ($role['url']) continue;
  12320. }
  12321. $role_description = getProp($role, 'description');
  12322. $role_pic_prompt = getProp($role, 'pic_prompt');
  12323. $role_url = getProp($role, 'url');
  12324. // 检查是否可以从上一集继承
  12325. $inherited = false;
  12326. if (!$is_force && !empty($prev_roles)) {
  12327. foreach ($prev_roles as $prev_role) {
  12328. $prev_role_name = getProp($prev_role, 'role');
  12329. $prev_description = getProp($prev_role, 'description');
  12330. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  12331. $prev_url = getProp($prev_role, 'url');
  12332. $prev_task_id = getProp($prev_role, 'task_id');
  12333. $prev_task_status = getProp($prev_role, 'task_status');
  12334. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  12335. if ($role_name == $prev_role_name
  12336. && $role_description == $prev_description
  12337. && $role_pic_prompt == $prev_pic_prompt
  12338. && !empty($prev_url)) {
  12339. $role['task_id'] = $prev_task_id;
  12340. $role['task_status'] = $prev_task_status;
  12341. $role['url'] = $prev_url;
  12342. $inherited = true;
  12343. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  12344. 'anime_id' => $anime_id,
  12345. 'episode_number' => $episode_number,
  12346. 'task_id' => $prev_task_id,
  12347. 'url' => $prev_url
  12348. ]);
  12349. break;
  12350. }
  12351. }
  12352. }
  12353. // 如果已继承或已有url,跳过生成
  12354. if ($inherited || (!$is_force && $role_url)) {
  12355. continue;
  12356. }
  12357. // 优先使用 pic_prompt,如果没有则使用 description
  12358. $pic_prompt = getProp($role, 'pic_prompt');
  12359. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12360. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12361. $update_flag = true;
  12362. // 调用AIImageGenerationService的生成图片任务接口
  12363. try {
  12364. $params = [
  12365. 'prompt' => $description,
  12366. 'ref_img_urls' => []
  12367. ];
  12368. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12369. $task_id = $task->id;
  12370. if (!$task_id) {
  12371. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  12372. continue; // 不中断,继续处理其他角色
  12373. }
  12374. $role['task_id'] = $task_id;
  12375. $role['task_status'] = 'processing';
  12376. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  12377. 'anime_id' => $anime_id,
  12378. 'episode_number' => $episode_number,
  12379. 'task_id' => $task_id
  12380. ]);
  12381. } catch (\Exception $e) {
  12382. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  12383. // 不抛出异常,继续处理其他角色
  12384. }
  12385. }
  12386. // 处理场景图片生成
  12387. foreach ($scenes as &$scene) {
  12388. $scene_name = getProp($scene, 'scene');
  12389. $scene_description = getProp($scene, 'description');
  12390. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  12391. $scene_url = getProp($scene, 'url');
  12392. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  12393. if (isset($ref_products[$scene_name])) {
  12394. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  12395. if ($scene['url']) continue;
  12396. }
  12397. // 检查是否可以从上一集继承
  12398. $inherited = false;
  12399. if (!$is_force && !empty($prev_scenes)) {
  12400. foreach ($prev_scenes as $prev_scene) {
  12401. $prev_scene_name = getProp($prev_scene, 'scene');
  12402. $prev_description = getProp($prev_scene, 'description');
  12403. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  12404. $prev_url = getProp($prev_scene, 'url');
  12405. $prev_task_id = getProp($prev_scene, 'task_id');
  12406. $prev_task_status = getProp($prev_scene, 'task_status');
  12407. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  12408. if ($scene_name == $prev_scene_name
  12409. && $scene_description == $prev_description
  12410. && $scene_pic_prompt == $prev_pic_prompt
  12411. && !empty($prev_url)) {
  12412. $scene['task_id'] = $prev_task_id;
  12413. $scene['task_status'] = $prev_task_status;
  12414. $scene['url'] = $prev_url;
  12415. $inherited = true;
  12416. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  12417. 'anime_id' => $anime_id,
  12418. 'episode_number' => $episode_number,
  12419. 'task_id' => $prev_task_id,
  12420. 'url' => $prev_url
  12421. ]);
  12422. break;
  12423. }
  12424. }
  12425. }
  12426. // 如果已继承或已有url,跳过生成
  12427. if ($inherited || (!$is_force && $scene_url)) {
  12428. continue;
  12429. }
  12430. // 优先使用 pic_prompt,如果没有则使用 description
  12431. $pic_prompt = getProp($scene, 'pic_prompt');
  12432. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12433. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12434. $update_flag = true;
  12435. // 调用AIImageGenerationService的生成图片任务接口
  12436. try {
  12437. $params = [
  12438. 'prompt' => $description,
  12439. 'ref_img_urls' => []
  12440. ];
  12441. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12442. $task_id = $task->id;
  12443. if (!$task_id) {
  12444. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  12445. continue; // 不中断,继续处理其他场景
  12446. }
  12447. $scene['task_id'] = $task_id;
  12448. $scene['task_status'] = 'processing';
  12449. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  12450. 'anime_id' => $anime_id,
  12451. 'episode_number' => $episode_number,
  12452. 'task_id' => $task_id
  12453. ]);
  12454. } catch (\Exception $e) {
  12455. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  12456. // 不抛出异常,继续处理其他场景
  12457. }
  12458. }
  12459. // 处理道具图片生成(逻辑与场景一致)
  12460. foreach ($props as &$prop) {
  12461. $prop_name = getProp($prop, 'prop');
  12462. $prop_description = getProp($prop, 'description');
  12463. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  12464. $prop_url = getProp($prop, 'url');
  12465. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  12466. if (isset($ref_products[$prop_name])) {
  12467. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  12468. if ($prop['url']) continue;
  12469. }
  12470. // 检查是否可以从上一集继承
  12471. $inherited = false;
  12472. if (!$is_force && !empty($prev_props)) {
  12473. foreach ($prev_props as $prev_prop) {
  12474. $prev_prop_name = getProp($prev_prop, 'prop');
  12475. $prev_description = getProp($prev_prop, 'description');
  12476. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  12477. $prev_url = getProp($prev_prop, 'url');
  12478. $prev_task_id = getProp($prev_prop, 'task_id');
  12479. $prev_task_status = getProp($prev_prop, 'task_status');
  12480. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  12481. if ($prop_name == $prev_prop_name
  12482. && $prop_description == $prev_description
  12483. && $prop_pic_prompt == $prev_pic_prompt
  12484. && !empty($prev_url)) {
  12485. $prop['task_id'] = $prev_task_id;
  12486. $prop['task_status'] = $prev_task_status;
  12487. $prop['url'] = $prev_url;
  12488. $inherited = true;
  12489. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  12490. 'anime_id' => $anime_id,
  12491. 'episode_number' => $episode_number,
  12492. 'task_id' => $prev_task_id,
  12493. 'url' => $prev_url
  12494. ]);
  12495. break;
  12496. }
  12497. }
  12498. }
  12499. // 如果已继承或已有url,跳过生成
  12500. if ($inherited || (!$is_force && $prop_url)) {
  12501. continue;
  12502. }
  12503. // 优先使用 pic_prompt,如果没有则使用 description
  12504. $pic_prompt = getProp($prop, 'pic_prompt');
  12505. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  12506. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12507. $update_flag = true;
  12508. // 调用AIImageGenerationService的生成图片任务接口
  12509. try {
  12510. $params = [
  12511. 'prompt' => $description,
  12512. 'ref_img_urls' => []
  12513. ];
  12514. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12515. $task_id = $task->id;
  12516. if (!$task_id) {
  12517. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  12518. continue; // 不中断,继续处理其他道具
  12519. }
  12520. $prop['task_id'] = $task_id;
  12521. $prop['task_status'] = 'processing';
  12522. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  12523. 'anime_id' => $anime_id,
  12524. 'episode_number' => $episode_number,
  12525. 'task_id' => $task_id
  12526. ]);
  12527. } catch (\Exception $e) {
  12528. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  12529. // 不抛出异常,继续处理其他道具
  12530. }
  12531. }
  12532. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12533. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  12534. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  12535. // // 保存剧集的角色和场景信息
  12536. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  12537. // 'roles' => json_encode($roles, 256),
  12538. // 'scenes' => json_encode($scenes, 256),
  12539. // 'generate_status' => '执行中',
  12540. // 'generate_at' => date('Y-m-d H:i:s'),
  12541. // 'updated_at' => date('Y-m-d H:i:s')
  12542. // ]);
  12543. // if (!$boolen) {
  12544. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  12545. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  12546. // }
  12547. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  12548. // 'episode_id' => $episode_id,
  12549. 'roles_count' => count($roles),
  12550. 'scenes_count' => count($scenes),
  12551. 'props_count' => count($props)
  12552. ]);
  12553. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12554. }
  12555. /**
  12556. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  12557. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  12558. *
  12559. * @param int $anime_id 动漫对话ID
  12560. * @param array $episode_roles 剧集角色数据
  12561. * @param array $episode_scenes 剧集场景数据
  12562. * @param array $episode_props 剧集道具数据
  12563. * @return bool
  12564. */
  12565. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  12566. // 获取全局数据
  12567. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12568. if (!$anime) {
  12569. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12570. return false;
  12571. }
  12572. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12573. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12574. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  12575. $roles_added = false;
  12576. $roles_updated = false;
  12577. $scenes_added = false;
  12578. $props_added = false;
  12579. // 处理角色同步
  12580. foreach ($episode_roles as $episode_role) {
  12581. $episode_role_name = getProp($episode_role, 'role');
  12582. $episode_description = getProp($episode_role, 'description');
  12583. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12584. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  12585. // 跳过旁白
  12586. if ($episode_role_name == '旁白') {
  12587. continue;
  12588. }
  12589. // 检查全局中是否已存在相同的角色
  12590. $exists = false;
  12591. $global_role_index = -1;
  12592. foreach ($global_roles as $index => $global_role) {
  12593. $global_role_name = getProp($global_role, 'role');
  12594. $global_description = getProp($global_role, 'description');
  12595. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12596. // 如果role、description、pic_prompt三项都一致,则认为已存在
  12597. if ($episode_role_name == $global_role_name
  12598. && $episode_description == $global_description
  12599. && $episode_pic_prompt == $global_pic_prompt) {
  12600. $exists = true;
  12601. $global_role_index = $index;
  12602. break;
  12603. }
  12604. }
  12605. // 如果不存在,则添加到全局
  12606. if (!$exists) {
  12607. $global_roles[] = $episode_role;
  12608. $roles_added = true;
  12609. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  12610. 'anime_id' => $anime_id,
  12611. 'role' => $episode_role_name
  12612. ]);
  12613. } else {
  12614. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  12615. if (!empty($episode_voice_prompt)) {
  12616. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  12617. // 如果全局没有voice_prompt或与剧集不一致,则更新
  12618. if ($global_voice_prompt !== $episode_voice_prompt) {
  12619. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  12620. $roles_updated = true;
  12621. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  12622. 'anime_id' => $anime_id,
  12623. 'role' => $episode_role_name,
  12624. 'voice_prompt' => $episode_voice_prompt
  12625. ]);
  12626. }
  12627. }
  12628. }
  12629. }
  12630. // 处理场景同步
  12631. foreach ($episode_scenes as $episode_scene) {
  12632. $episode_scene_name = getProp($episode_scene, 'scene');
  12633. $episode_description = getProp($episode_scene, 'description');
  12634. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12635. // 检查全局中是否已存在相同的场景
  12636. $exists = false;
  12637. foreach ($global_scenes as $global_scene) {
  12638. $global_scene_name = getProp($global_scene, 'scene');
  12639. $global_description = getProp($global_scene, 'description');
  12640. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12641. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  12642. if ($episode_scene_name == $global_scene_name
  12643. && $episode_description == $global_description
  12644. && $episode_pic_prompt == $global_pic_prompt) {
  12645. $exists = true;
  12646. break;
  12647. }
  12648. }
  12649. // 如果不存在,则添加到全局
  12650. if (!$exists) {
  12651. $global_scenes[] = $episode_scene;
  12652. $scenes_added = true;
  12653. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  12654. 'anime_id' => $anime_id,
  12655. 'scene' => $episode_scene_name
  12656. ]);
  12657. }
  12658. }
  12659. // 处理道具同步(逻辑与场景一致)
  12660. foreach ($episode_props as $episode_prop) {
  12661. $episode_prop_name = getProp($episode_prop, 'prop');
  12662. $episode_description = getProp($episode_prop, 'description');
  12663. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  12664. // 检查全局中是否已存在相同的道具
  12665. $exists = false;
  12666. foreach ($global_props as $global_prop) {
  12667. $global_prop_name = getProp($global_prop, 'prop');
  12668. $global_description = getProp($global_prop, 'description');
  12669. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  12670. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  12671. if ($episode_prop_name == $global_prop_name
  12672. && $episode_description == $global_description
  12673. && $episode_pic_prompt == $global_pic_prompt) {
  12674. $exists = true;
  12675. break;
  12676. }
  12677. }
  12678. // 如果不存在,则添加到全局
  12679. if (!$exists) {
  12680. $global_props[] = $episode_prop;
  12681. $props_added = true;
  12682. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  12683. 'anime_id' => $anime_id,
  12684. 'prop' => $episode_prop_name
  12685. ]);
  12686. }
  12687. }
  12688. // 如果有新增或更新,则更新全局数据
  12689. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  12690. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12691. if ($roles_added || $roles_updated) {
  12692. $update_data['roles'] = json_encode($global_roles, 256);
  12693. }
  12694. if ($scenes_added) {
  12695. $update_data['scenes'] = json_encode($global_scenes, 256);
  12696. }
  12697. if ($props_added) {
  12698. $update_data['props'] = json_encode($global_props, 256);
  12699. }
  12700. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12701. dLog('deepseek')->info('剧集数据同步到全局完成', [
  12702. 'anime_id' => $anime_id,
  12703. 'roles_added' => $roles_added,
  12704. 'roles_updated' => $roles_updated,
  12705. 'scenes_added' => $scenes_added,
  12706. 'props_added' => $props_added,
  12707. 'global_roles_count' => count($global_roles),
  12708. 'global_scenes_count' => count($global_scenes),
  12709. 'global_props_count' => count($global_props)
  12710. ]);
  12711. }
  12712. return true;
  12713. }
  12714. /**
  12715. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  12716. *
  12717. * @param int $anime_id 动漫对话ID
  12718. * @param int $episode_id 分集ID
  12719. * @return bool
  12720. */
  12721. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  12722. // 获取全局角色和场景数据
  12723. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12724. if (!$anime) {
  12725. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12726. return false;
  12727. }
  12728. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12729. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12730. // 获取指定的分集
  12731. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  12732. if (!$episode) {
  12733. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12734. return false;
  12735. }
  12736. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12737. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12738. $roles_updated = false;
  12739. $scenes_updated = false;
  12740. // 继承角色的task_id、task_status和url
  12741. foreach ($episode_roles as &$episode_role) {
  12742. $episode_role_name = getProp($episode_role, 'role');
  12743. $episode_description = getProp($episode_role, 'description');
  12744. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12745. $episode_url = getProp($episode_role, 'url');
  12746. // 跳过旁白角色
  12747. if ($episode_role_name == '旁白') {
  12748. continue;
  12749. }
  12750. // 如果剧集中已有URL,跳过
  12751. if (!empty($episode_url)) {
  12752. continue;
  12753. }
  12754. // 遍历全局角色数据,查找匹配的角色
  12755. foreach ($global_roles as $global_role) {
  12756. $global_role_name = getProp($global_role, 'role');
  12757. $global_description = getProp($global_role, 'description');
  12758. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12759. $global_url = getProp($global_role, 'url');
  12760. $global_task_id = getProp($global_role, 'task_id');
  12761. $global_task_status = getProp($global_role, 'task_status');
  12762. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12763. if ($episode_role_name == $global_role_name
  12764. && $episode_description == $global_description
  12765. && $episode_pic_prompt == $global_pic_prompt) {
  12766. // 继承 task_id、task_status 和 url
  12767. if (!empty($global_task_id)) {
  12768. $episode_role['task_id'] = $global_task_id;
  12769. $episode_role['task_status'] = $global_task_status;
  12770. $roles_updated = true;
  12771. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12772. 'episode_id' => $episode_id,
  12773. 'role' => $episode_role_name,
  12774. 'task_id' => $global_task_id,
  12775. 'task_status' => $global_task_status
  12776. ]);
  12777. }
  12778. if (!empty($global_url)) {
  12779. $episode_role['url'] = $global_url;
  12780. $roles_updated = true;
  12781. dLog('deepseek')->info('剧集角色继承全局url', [
  12782. 'episode_id' => $episode_id,
  12783. 'role' => $episode_role_name,
  12784. 'url' => $global_url
  12785. ]);
  12786. }
  12787. break;
  12788. }
  12789. }
  12790. }
  12791. // 继承场景的task_id、task_status和url
  12792. foreach ($episode_scenes as &$episode_scene) {
  12793. $episode_scene_name = getProp($episode_scene, 'scene');
  12794. $episode_description = getProp($episode_scene, 'description');
  12795. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12796. $episode_url = getProp($episode_scene, 'url');
  12797. // 如果剧集中已有URL,跳过
  12798. if (!empty($episode_url)) {
  12799. continue;
  12800. }
  12801. // 遍历全局场景数据,查找匹配的场景
  12802. foreach ($global_scenes as $global_scene) {
  12803. $global_scene_name = getProp($global_scene, 'scene');
  12804. $global_description = getProp($global_scene, 'description');
  12805. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12806. $global_url = getProp($global_scene, 'url');
  12807. $global_task_id = getProp($global_scene, 'task_id');
  12808. $global_task_status = getProp($global_scene, 'task_status');
  12809. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12810. if ($episode_scene_name == $global_scene_name
  12811. && $episode_description == $global_description
  12812. && $episode_pic_prompt == $global_pic_prompt) {
  12813. // 继承 task_id、task_status 和 url
  12814. if (!empty($global_task_id)) {
  12815. $episode_scene['task_id'] = $global_task_id;
  12816. $episode_scene['task_status'] = $global_task_status;
  12817. $scenes_updated = true;
  12818. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12819. 'episode_id' => $episode_id,
  12820. 'scene' => $episode_scene_name,
  12821. 'task_id' => $global_task_id,
  12822. 'task_status' => $global_task_status
  12823. ]);
  12824. }
  12825. if (!empty($global_url)) {
  12826. $episode_scene['url'] = $global_url;
  12827. $scenes_updated = true;
  12828. dLog('deepseek')->info('剧集场景继承全局url', [
  12829. 'episode_id' => $episode_id,
  12830. 'scene' => $episode_scene_name,
  12831. 'url' => $global_url
  12832. ]);
  12833. }
  12834. break;
  12835. }
  12836. }
  12837. }
  12838. // 如果有更新,则保存到数据库
  12839. if ($roles_updated || $scenes_updated) {
  12840. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12841. if ($roles_updated) {
  12842. $update_data['roles'] = json_encode($episode_roles, 256);
  12843. }
  12844. if ($scenes_updated) {
  12845. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12846. }
  12847. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12848. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12849. 'episode_id' => $episode_id,
  12850. 'roles_updated' => $roles_updated,
  12851. 'scenes_updated' => $scenes_updated
  12852. ]);
  12853. }
  12854. return true;
  12855. }
  12856. public function chatChangeImg($data) {
  12857. $segment = getProp($data, 'segment');
  12858. $segment_content = getProp($segment, 'segment_content');
  12859. $prompt = getProp($data, 'prompt');
  12860. $ref_img = getProp($data, 'ref_img');
  12861. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12862. // 处理文本模型
  12863. $model = getProp($data, 'model');
  12864. if (!$model) {
  12865. // 用户没有输入,从anime表获取
  12866. $segment_id = getProp($segment, 'segment_id');
  12867. if ($segment_id) {
  12868. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  12869. if ($episode_id) {
  12870. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  12871. if ($anime_id) {
  12872. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  12873. }
  12874. }
  12875. }
  12876. if (!$model) {
  12877. // anime表也没有,使用默认值
  12878. $model = 'doubao-seed-2-0-mini-260215';
  12879. }
  12880. }
  12881. // 验证模型是否在可用模型表中
  12882. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12883. $model = 'doubao-seed-2-0-mini-260215';
  12884. }
  12885. $messages[] =
  12886. [
  12887. 'role' => 'user',
  12888. 'content' => $question
  12889. ];
  12890. $post_data = [
  12891. 'model' => $model,
  12892. 'messages' => $messages,
  12893. // 'max_tokens' => 8192,
  12894. 'temperature' => 0.7,
  12895. 'frequency_penalty' => 0,
  12896. 'presence_penalty' => 0,
  12897. 'response_format' => ['type' => 'text'],
  12898. 'stream' => false // 是否启用流式输出
  12899. ];
  12900. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12901. // DeepSeek 官方模型使用 DeepSeek API
  12902. $chatResult = $this->chatOnly($post_data);
  12903. } else if (in_array($model, $this->gpt_text_models)) {
  12904. // GPT-5.4 模型使用 TokenRouter API
  12905. $chatResult = $this->gpt54ChatOnly($post_data);
  12906. } else {
  12907. // 其他模型使用火山引擎API
  12908. $chatResult = $this->volcEngineChatCompletion($post_data);
  12909. }
  12910. if (is_array($chatResult)) {
  12911. extract($chatResult);
  12912. }else {
  12913. Utils::throwError('20003: 接口调用失败!');
  12914. }
  12915. // 仅记录 token 使用明细(不扣积分)
  12916. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  12917. 'model' => $model,
  12918. 'source' => 'chatChangeImg',
  12919. ], $model);
  12920. return [
  12921. 'type' => 'done',
  12922. // 'episode' => $episode,
  12923. 'answer' => $fullContent,
  12924. 'reasoning' => $fullReasoningContent,
  12925. 'usage' => $usage
  12926. ];
  12927. }
  12928. /**
  12929. * 仅调用 deepseek 对话接口(非流式)
  12930. *
  12931. * @param array $post_data
  12932. * @param int $timeout
  12933. * @return array
  12934. */
  12935. private function chatOnly($post_data, $timeout = 1800) {
  12936. $post_data['max_tokens'] = 300000;
  12937. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  12938. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  12939. $response = $result->getBody()->getContents();
  12940. $response_arr = json_decode($response, true);
  12941. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  12942. $fullContent = '';
  12943. $fullReasoningContent = [];
  12944. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12945. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12946. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12947. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  12948. }
  12949. return [
  12950. 'fullContent' => $fullContent,
  12951. 'fullReasoningContent' => $fullReasoningContent,
  12952. 'usage' => $usage
  12953. ];
  12954. }
  12955. /**
  12956. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  12957. *
  12958. * @param string $errorMessage
  12959. * @return string|null
  12960. */
  12961. public function analyzeErrorMessage($errorMessage)
  12962. {
  12963. try {
  12964. $post_data = [
  12965. 'model' => 'deepseek-v4-flash',
  12966. 'messages' => [
  12967. [
  12968. 'role' => 'system',
  12969. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  12970. ],
  12971. [
  12972. 'role' => 'user',
  12973. 'content' => (string)$errorMessage,
  12974. ],
  12975. ],
  12976. 'temperature' => 0.3,
  12977. 'frequency_penalty' => 0,
  12978. 'presence_penalty' => 0,
  12979. 'response_format' => ['type' => 'text'],
  12980. 'stream' => false,
  12981. ];
  12982. $result = $this->chatOnly($post_data, 8);
  12983. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  12984. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  12985. 'model' => 'deepseek-v4-flash',
  12986. 'source' => 'analyzeErrorMessage',
  12987. ], 'deepseek-v4-flash');
  12988. $content = trim((string)($result['fullContent'] ?? ''));
  12989. if ($content === '') {
  12990. return null;
  12991. }
  12992. return mb_substr($content, 0, 50);
  12993. } catch (\Exception $e) {
  12994. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  12995. 'error_message' => $errorMessage
  12996. ]);
  12997. return null;
  12998. }
  12999. }
  13000. // 仅调用 GPT-5.4 对话接口(非流式)
  13001. private function gpt54ChatOnly($post_data) {
  13002. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  13003. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  13004. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  13005. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  13006. $usedLunaFallback = false;
  13007. if (empty($apiKey)) {
  13008. Utils::throwError('20003:GPT-5.4 API Key未配置');
  13009. }
  13010. // 先探活,服务不可用时自动重试
  13011. $this->ensureGptServiceAvailable($apiKey);
  13012. $client = new Client(['timeout' => 1800, 'verify' => false]);
  13013. // 移除 thinking 参数,GPT-5.4 不支持
  13014. if (isset($post_data['thinking'])) {
  13015. unset($post_data['thinking']);
  13016. }
  13017. if (isset($post_data['reasoning_effort'])) {
  13018. unset($post_data['reasoning_effort']);
  13019. }
  13020. $post_data['max_completion_tokens'] = 100000;
  13021. // 确保 stream 为 false
  13022. $post_data['stream'] = false;
  13023. $maxRetries = $this->gptRetryTimes();
  13024. $interval = $this->gptRetryInterval();
  13025. $attempt = 0;
  13026. while (true) {
  13027. try {
  13028. $headers = [
  13029. 'Authorization' => 'Bearer ' . $apiKey,
  13030. 'Content-Type' => 'application/json'
  13031. ];
  13032. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  13033. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  13034. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  13035. 'json' => $post_data,
  13036. 'headers' => $headers
  13037. ]);
  13038. $response = $result->getBody()->getContents();
  13039. $response_arr = json_decode($response, true);
  13040. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  13041. $fullContent = '';
  13042. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  13043. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  13044. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  13045. }
  13046. return [
  13047. 'fullContent' => $fullContent,
  13048. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  13049. 'usage' => $usage
  13050. ];
  13051. } catch (\Exception $e) {
  13052. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  13053. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  13054. $usedLunaFallback = true;
  13055. $apiKey = $lunaApiKey;
  13056. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  13057. continue;
  13058. }
  13059. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  13060. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  13061. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  13062. throw $e;
  13063. }
  13064. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  13065. 'retry' => $attempt + 1,
  13066. 'max_retries' => $maxRetries,
  13067. 'error' => $e->getMessage()
  13068. ]);
  13069. sleep($interval);
  13070. $attempt++;
  13071. }
  13072. }
  13073. }
  13074. public function getContentByBid($bid) {
  13075. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  13076. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  13077. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  13078. $content = '';
  13079. foreach ($chapters as $chapter) {
  13080. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  13081. }
  13082. return $content;
  13083. }
  13084. public function getContentByScriptId($script_id) {
  13085. $content = '';
  13086. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  13087. if ($contents) {
  13088. $content = implode(PHP_EOL, $contents);
  13089. }else {
  13090. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  13091. }
  13092. return $content;
  13093. }
  13094. /**
  13095. * 根据文件类型提取文本内容
  13096. *
  13097. * @param mixed $file 文件对象或文件路径
  13098. * @return string
  13099. */
  13100. public function extractFileContent($file) {
  13101. // 获取文件路径和扩展名
  13102. if (is_string($file)) {
  13103. $filePath = $file;
  13104. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  13105. } else {
  13106. // Laravel UploadedFile 对象
  13107. $filePath = $file->getRealPath();
  13108. $extension = strtolower($file->getClientOriginalExtension());
  13109. }
  13110. $content = '';
  13111. switch ($extension) {
  13112. case 'txt':
  13113. $content = $this->extractTxtContent($filePath);
  13114. break;
  13115. case 'pdf':
  13116. $content = $this->extractPdfContent($filePath);
  13117. break;
  13118. case 'doc':
  13119. case 'docx':
  13120. $content = $this->extractWordContent($filePath);
  13121. break;
  13122. // case 'jpg':
  13123. // case 'jpeg':
  13124. // case 'png':
  13125. // case 'gif':
  13126. // case 'bmp':
  13127. // case 'webp':
  13128. // $content = $this->extractImageContent($filePath);
  13129. // break;
  13130. default:
  13131. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  13132. }
  13133. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  13134. if (!mb_check_encoding($content, 'UTF-8')) {
  13135. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  13136. $content = $cleaned === false ? $content : $cleaned;
  13137. }
  13138. return $content;
  13139. }
  13140. /**
  13141. * 提取 TXT 文件内容
  13142. */
  13143. private function extractTxtContent($filePath) {
  13144. if (!file_exists($filePath)) {
  13145. Utils::throwError('20003:文件不存在');
  13146. }
  13147. $content = file_get_contents($filePath);
  13148. // 尝试检测并转换编码
  13149. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  13150. if ($encoding && $encoding !== 'UTF-8') {
  13151. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  13152. }
  13153. return trim($content);
  13154. }
  13155. /**
  13156. * 提取 PDF 文件内容
  13157. */
  13158. private function extractPdfContent($filePath) {
  13159. if (!file_exists($filePath)) {
  13160. Utils::throwError('20003:文件不存在');
  13161. }
  13162. try {
  13163. $parser = new PdfParser();
  13164. $pdf = $parser->parseFile($filePath);
  13165. $content = $pdf->getText();
  13166. return trim($content);
  13167. } catch (\Exception $e) {
  13168. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  13169. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  13170. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  13171. }
  13172. }
  13173. /**
  13174. * 提取 Word 文件内容(支持 doc 和 docx)
  13175. */
  13176. private function extractWordContent($filePath) {
  13177. if (!file_exists($filePath)) {
  13178. Utils::throwError('20003:文件不存在');
  13179. }
  13180. try {
  13181. $phpWord = WordIOFactory::load($filePath);
  13182. $content = '';
  13183. foreach ($phpWord->getSections() as $section) {
  13184. foreach ($section->getElements() as $element) {
  13185. $content .= $this->extractWordElementText($element);
  13186. }
  13187. }
  13188. return trim($content);
  13189. } catch (\Exception $e) {
  13190. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  13191. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  13192. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  13193. }
  13194. }
  13195. /**
  13196. * 递归提取 Word 元素中的文本
  13197. */
  13198. private function extractWordElementText($element) {
  13199. $text = '';
  13200. if (method_exists($element, 'getText')) {
  13201. $text .= $element->getText() . "\n";
  13202. } elseif (method_exists($element, 'getElements')) {
  13203. foreach ($element->getElements() as $childElement) {
  13204. $text .= $this->extractWordElementText($childElement);
  13205. }
  13206. }
  13207. return $text;
  13208. }
  13209. /**
  13210. * 提取图片内容(使用火山引擎 OCR)
  13211. */
  13212. private function extractImageContent($filePath) {
  13213. if (!file_exists($filePath)) {
  13214. Utils::throwError('20003:文件不存在');
  13215. }
  13216. try {
  13217. // 读取图片并转换为 base64
  13218. $imageData = file_get_contents($filePath);
  13219. $base64Image = base64_encode($imageData);
  13220. // 调用火山引擎 OCR 服务
  13221. $content = $this->callVolcEngineOCR($base64Image);
  13222. return trim($content);
  13223. } catch (\Exception $e) {
  13224. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  13225. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  13226. Utils::throwError('20003:图片识别失败');
  13227. }
  13228. }
  13229. /**
  13230. * 调用火山引擎 OCR 服务识别图片文字
  13231. *
  13232. * @param string $base64Image base64 编码的图片数据
  13233. * @return string 识别的文字内容
  13234. */
  13235. private function callVolcEngineOCR($base64Image) {
  13236. $method = 'POST';
  13237. $service = 'cv';
  13238. $host = 'visual.volcengineapi.com';
  13239. $region = env('VOLC_REGION', 'cn-north-1');
  13240. $access_key = env('VOLC_AK');
  13241. $secret_key = env('VOLC_SK');
  13242. $action = 'OCRNormal';
  13243. $version = '2020-08-26';
  13244. if (!$access_key || !$secret_key) {
  13245. Utils::throwError('20003:请配置火山引擎 AK/SK');
  13246. }
  13247. // 请求体
  13248. $body = json_encode([
  13249. 'image_base64' => $base64Image
  13250. ]);
  13251. // 生成签名
  13252. $headers = $this->getVolcEngineSignHeaders(
  13253. $method, $service, $host, $region,
  13254. "Action={$action}&Version={$version}",
  13255. $access_key, $secret_key, $body
  13256. );
  13257. $client = new Client(['timeout' => 1800, 'verify' => false]);
  13258. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  13259. 'headers' => $headers,
  13260. 'body' => $body
  13261. ]);
  13262. $response_arr = json_decode($response->getBody()->getContents(), true);
  13263. // 提取识别的文字
  13264. $textLines = [];
  13265. if (isset($response_arr['data']['line_texts'])) {
  13266. $textLines = $response_arr['data']['line_texts'];
  13267. } elseif (isset($response_arr['data']['ocr_infos'])) {
  13268. foreach ($response_arr['data']['ocr_infos'] as $info) {
  13269. if (isset($info['text'])) {
  13270. $textLines[] = $info['text'];
  13271. }
  13272. }
  13273. }
  13274. if (empty($textLines)) {
  13275. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  13276. return '';
  13277. }
  13278. return implode("\n", $textLines);
  13279. }
  13280. /**
  13281. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  13282. */
  13283. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  13284. $contentType = 'application/json';
  13285. $accept = 'application/json';
  13286. // 获取当前UTC时间
  13287. $t = new DateTime('now', new DateTimeZone('UTC'));
  13288. $xDate = $t->format('Ymd\THis\Z');
  13289. $dateStamp = $t->format('Ymd');
  13290. // 计算 body 的 sha256 哈希
  13291. $payloadHash = hash('sha256', $body);
  13292. // 1. 拼接规范请求串
  13293. $canonicalUri = '/';
  13294. $canonicalQueryString = $queryString;
  13295. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  13296. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  13297. $canonicalRequest = implode("\n", [
  13298. $method,
  13299. $canonicalUri,
  13300. $canonicalQueryString,
  13301. $canonicalHeaders,
  13302. $signedHeaders,
  13303. $payloadHash
  13304. ]);
  13305. // 2. 拼接待签名字符串
  13306. $algorithm = 'HMAC-SHA256';
  13307. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  13308. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  13309. $stringToSign = implode("\n", [
  13310. $algorithm,
  13311. $xDate,
  13312. $credentialScope,
  13313. $hashedCanonicalRequest
  13314. ]);
  13315. // 3. 计算签名
  13316. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  13317. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  13318. // 4. 添加签名到请求头
  13319. $authorizationHeader = sprintf(
  13320. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  13321. $algorithm,
  13322. $access_key,
  13323. $credentialScope,
  13324. $signedHeaders,
  13325. $signature
  13326. );
  13327. return [
  13328. 'Accept' => $accept,
  13329. 'Content-Type' => $contentType,
  13330. 'Host' => $host,
  13331. 'X-Date' => $xDate,
  13332. 'X-Content-Sha256'=> $payloadHash,
  13333. 'Authorization' => $authorizationHeader
  13334. ];
  13335. }
  13336. public function generateScriptWords($cid, $model = 'r1') {
  13337. ini_set('max_execution_time', 0);
  13338. if (!$cid) Utils::throwError('20003: 请选择章节!');
  13339. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  13340. // 模型兼容性处理和思考模式设置
  13341. $thinkingMode = 'disabled';
  13342. $reasoningEffort = 'high';
  13343. if ($model == 'r1') {
  13344. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  13345. $thinkingMode = 'enabled';
  13346. } else {
  13347. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  13348. $thinkingMode = 'disabled';
  13349. }
  13350. $messages = [
  13351. [
  13352. 'role' => 'system',
  13353. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  13354. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  13355. 2.非对话部分请全部用旁白角色代替
  13356. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  13357. ],
  13358. [
  13359. 'role' => 'user',
  13360. 'content' => $content
  13361. ]
  13362. ];
  13363. $post_data = [
  13364. 'model' => $model,
  13365. 'messages' => $messages,
  13366. // 'max_tokens' => 8192,
  13367. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  13368. 'frequency_penalty' => 0,
  13369. 'presence_penalty' => 0,
  13370. 'thinking' => ['type' => $thinkingMode],
  13371. 'response_format' => [
  13372. 'type' => 'text'
  13373. ],
  13374. 'stream' => false
  13375. ];
  13376. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  13377. // 根据模型类型选择调用方法
  13378. $fullContent = '';
  13379. $usage = [];
  13380. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  13381. // DeepSeek 官方模型使用 DeepSeek API
  13382. $chatResult = $this->chatOnly($post_data);
  13383. } else if (in_array($model, $this->gpt_text_models)) {
  13384. // GPT-5.4 模型使用 TokenRouter API
  13385. $chatResult = $this->gpt54ChatOnly($post_data);
  13386. } else {
  13387. // 其他模型使用火山引擎API
  13388. $chatResult = $this->volcEngineChatCompletion($post_data);
  13389. }
  13390. if (is_array($chatResult)) {
  13391. $fullContent = $chatResult['fullContent'];
  13392. $usage = $chatResult['usage'] ?? [];
  13393. }
  13394. // 仅记录 token 使用明细(不扣积分)
  13395. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  13396. 'model' => $model,
  13397. 'cid' => $cid,
  13398. 'source' => 'generateScriptWords',
  13399. ], $model);
  13400. return $fullContent;
  13401. }
  13402. /**
  13403. * 智能化解析集数信息
  13404. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  13405. *
  13406. * @param string $prompt 用户输入的提示词
  13407. * @return int|null 解析出的集数,如果没有找到则返回null
  13408. */
  13409. private function extractEpisodeNumber($prompt)
  13410. {
  13411. if (empty($prompt)) {
  13412. return null;
  13413. }
  13414. // 定义各种可能的表达模式
  13415. $patterns = [
  13416. // 基本模式:改成N集、调整成N集、修改成N集
  13417. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  13418. // 扩展模式:分成N集、拆分成N集、分割成N集
  13419. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  13420. // 数量模式:N集、共N集、总共N集
  13421. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  13422. // 制作模式:制作N集、生成N集、创建N集
  13423. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  13424. // 计划模式:计划N集、预计N集、打算N集
  13425. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  13426. // 需要模式:需要N集、要N集
  13427. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  13428. // 中文数字模式:改成三集、调整成五集等
  13429. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  13430. // 英文数字模式
  13431. '/(?: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',
  13432. ];
  13433. // 中文数字转阿拉伯数字的映射
  13434. $chineseNumbers = [
  13435. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  13436. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  13437. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  13438. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  13439. ];
  13440. // 逐个尝试匹配模式
  13441. foreach ($patterns as $pattern) {
  13442. if (preg_match($pattern, $prompt, $matches)) {
  13443. $number = trim($matches[1]);
  13444. // 如果是中文数字,转换为阿拉伯数字
  13445. if (isset($chineseNumbers[$number])) {
  13446. return $chineseNumbers[$number];
  13447. }
  13448. // 如果是阿拉伯数字,直接返回
  13449. if (is_numeric($number)) {
  13450. $episodeNum = intval($number);
  13451. // 合理性检查:集数应该在1-100之间
  13452. if ($episodeNum >= 1 && $episodeNum <= 100) {
  13453. return $episodeNum;
  13454. }
  13455. }
  13456. }
  13457. }
  13458. return null;
  13459. }
  13460. /**
  13461. * 调用火山引擎对话(Chat) API
  13462. *
  13463. * @param array $params 包含以下参数:
  13464. * - model: 模型ID(必填)
  13465. * - messages: 消息列表(必填)
  13466. * - stream: 是否流式输出(可选,默认false)
  13467. * - max_tokens: 最大输出token数(可选)
  13468. * - temperature: 采样温度(可选,默认1)
  13469. * - top_p: 核采样概率(可选,默认0.7)
  13470. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  13471. * - presence_penalty: 存在惩罚系数(可选,默认0)
  13472. * - stop: 停止词(可选)
  13473. * - tools: 工具列表(可选)
  13474. * @return array|Generator 非流式返回数组,流式返回生成器
  13475. */
  13476. public function volcEngineChatCompletion(array $params)
  13477. {
  13478. $apiKey = env('VOLC_AI_API_KEY');
  13479. if (empty($apiKey)) {
  13480. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  13481. }
  13482. // 构建请求参数
  13483. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  13484. $requestData = [
  13485. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  13486. 'messages' => $params['messages'] ?? [],
  13487. ];
  13488. if (!in_array($originalModel, $this->valid_text_models)) {
  13489. Utils::throwError('20003:该模型不支持!');
  13490. }
  13491. // 添加可选参数
  13492. if (isset($params['stream'])) {
  13493. $requestData['stream'] = $params['stream'];
  13494. }
  13495. if (isset($params['stream_options'])) {
  13496. $requestData['stream_options'] = $params['stream_options'];
  13497. }
  13498. if (isset($params['max_tokens'])) {
  13499. $requestData['max_tokens'] = $params['max_tokens'];
  13500. }else if (isset($params['max_completion_tokens'])) {
  13501. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  13502. }else {
  13503. $requestData['max_completion_tokens'] = 100000;
  13504. }
  13505. if (isset($params['temperature'])) {
  13506. $requestData['temperature'] = $params['temperature'];
  13507. }
  13508. if (isset($params['top_p'])) {
  13509. $requestData['top_p'] = $params['top_p'];
  13510. }
  13511. if (isset($params['frequency_penalty'])) {
  13512. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  13513. }
  13514. if (isset($params['presence_penalty'])) {
  13515. $requestData['presence_penalty'] = $params['presence_penalty'];
  13516. }
  13517. if (isset($params['stop'])) {
  13518. $requestData['stop'] = $params['stop'];
  13519. }
  13520. if (isset($params['tools'])) {
  13521. $requestData['tools'] = $params['tools'];
  13522. }
  13523. if (isset($params['tool_choice'])) {
  13524. $requestData['tool_choice'] = $params['tool_choice'];
  13525. }
  13526. if (isset($params['response_format'])) {
  13527. $requestData['response_format'] = $params['response_format'];
  13528. }
  13529. if (isset($params['thinking'])) {
  13530. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  13531. if (is_array($params['thinking'])) {
  13532. $requestData['thinking'] = $params['thinking'];
  13533. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  13534. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13535. }
  13536. } else {
  13537. $requestData['thinking'] = ['type' => $params['thinking']];
  13538. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  13539. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13540. }
  13541. }
  13542. } else {
  13543. $requestData['thinking'] = ['type' => 'disabled'];
  13544. }
  13545. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  13546. $client = new Client(['verify' => false, 'timeout' => 1800]);
  13547. try {
  13548. // 判断是否为流式输出
  13549. $isStream = isset($params['stream']) && $params['stream'] === true;
  13550. if ($isStream) {
  13551. // 流式输出
  13552. // 流式请求默认声明返回 usage(未显式传参时)
  13553. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  13554. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  13555. } else {
  13556. // 非流式输出
  13557. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13558. 'headers' => [
  13559. 'Authorization' => 'Bearer ' . $apiKey,
  13560. 'Content-Type' => 'application/json',
  13561. ],
  13562. 'json' => $requestData
  13563. ]);
  13564. $responseData = json_decode($response->getBody(), true);
  13565. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  13566. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  13567. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  13568. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  13569. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  13570. }
  13571. return [
  13572. 'fullContent' => $fullContent,
  13573. 'fullReasoningContent' => $fullReasoningContent,
  13574. 'usage' => $usage
  13575. ];
  13576. }
  13577. } catch (\Exception $e) {
  13578. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  13579. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  13580. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  13581. }
  13582. }
  13583. /**
  13584. * 火山引擎对话API流式输出
  13585. *
  13586. * @param Client $client HTTP客户端
  13587. * @param string $apiKey API密钥
  13588. * @param array $requestData 请求数据
  13589. * @return Generator
  13590. */
  13591. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  13592. {
  13593. try {
  13594. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13595. 'headers' => [
  13596. 'Authorization' => 'Bearer ' . $apiKey,
  13597. 'Content-Type' => 'application/json',
  13598. ],
  13599. 'json' => $requestData,
  13600. 'stream' => true
  13601. ]);
  13602. $body = $response->getBody();
  13603. $buffer = '';
  13604. $fullContent = '';
  13605. $fullReasoningContent = '';
  13606. $usage = [];
  13607. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  13608. // 逐行读取流式响应
  13609. while (!$body->eof()) {
  13610. $chunk = $body->read(1024);
  13611. $buffer .= $chunk;
  13612. // 按行分割
  13613. $lines = explode("\n", $buffer);
  13614. $buffer = array_pop($lines);
  13615. foreach ($lines as $line) {
  13616. $line = trim($line);
  13617. if (empty($line)) {
  13618. continue;
  13619. }
  13620. // 检查是否是SSE数据行
  13621. if (strpos($line, 'data: ') !== 0) {
  13622. continue;
  13623. }
  13624. $data = substr($line, 6);
  13625. if ($data === '[DONE]') {
  13626. dLog('deepseek')->info('收到结束标记');
  13627. break 2;
  13628. }
  13629. try {
  13630. $json = json_decode($data, true);
  13631. if (json_last_error() !== JSON_ERROR_NONE) {
  13632. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  13633. continue;
  13634. }
  13635. if (isset($json['choices'][0]['delta'])) {
  13636. $delta = $json['choices'][0]['delta'];
  13637. // 处理思维链内容
  13638. if (isset($delta['reasoning_content'])) {
  13639. $fullReasoningContent .= $delta['reasoning_content'];
  13640. yield [
  13641. 'type' => 'reasoning',
  13642. 'content' => $delta['reasoning_content'],
  13643. 'full_reasoning' => $fullReasoningContent
  13644. ];
  13645. }
  13646. // 处理回答内容
  13647. if (isset($delta['content'])) {
  13648. $fullContent .= $delta['content'];
  13649. yield [
  13650. 'type' => 'content',
  13651. 'content' => $delta['content'],
  13652. ];
  13653. }
  13654. }
  13655. // 获取使用统计信息
  13656. if (isset($json['usage'])) {
  13657. $usage = $json['usage'];
  13658. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  13659. }
  13660. } catch (\Exception $e) {
  13661. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  13662. continue;
  13663. }
  13664. }
  13665. }
  13666. dLog('deepseek')->info('流式读取完成', [
  13667. 'content_length' => strlen($fullContent),
  13668. 'reasoning_length' => strlen($fullReasoningContent)
  13669. ]);
  13670. yield [
  13671. 'type' => 'done',
  13672. 'full_content' => $fullContent,
  13673. 'full_reasoning' => $fullReasoningContent,
  13674. 'usage' => $usage
  13675. ];
  13676. } catch (\Exception $e) {
  13677. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  13678. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  13679. throw $e;
  13680. }
  13681. }
  13682. /**
  13683. * 检查并创建图片生成任务
  13684. *
  13685. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  13686. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  13687. * @param string $nameKey 资源名称字段('role' 或 'scene')
  13688. * @param string $art_style 美术风格
  13689. * @return array 更新后的资源列表
  13690. */
  13691. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  13692. {
  13693. // 确保参数为数组
  13694. $merged_items = is_array($merged_items) ? $merged_items : [];
  13695. $global_items = is_array($global_items) ? $global_items : [];
  13696. // 构建全局资源映射表,用于快速查找
  13697. $global_map = [];
  13698. foreach ($global_items as $item) {
  13699. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13700. if ($itemKey === '') {
  13701. continue;
  13702. }
  13703. $global_map[$itemKey] = $item;
  13704. }
  13705. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  13706. foreach ($merged_items as &$item) {
  13707. $item_name = getProp($item, $nameKey);
  13708. $item_description = getProp($item, 'description');
  13709. // $item_url = getProp($item, 'url');
  13710. // // 如果已有图片URL,跳过
  13711. // if (!empty($item_url)) {
  13712. // continue;
  13713. // }
  13714. // 如果是旁白角色,跳过
  13715. if ($nameKey === 'role' && $item_name === '旁白') {
  13716. continue;
  13717. }
  13718. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13719. if ($itemKey === '') {
  13720. continue;
  13721. }
  13722. $need_create_task = false;
  13723. // 条件1:在全局资源中找不到匹配的名称
  13724. if (!isset($global_map[$itemKey])) {
  13725. $need_create_task = true;
  13726. } else {
  13727. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13728. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13729. $current_description = trim((string)$item_description);
  13730. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13731. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13732. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13733. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13734. $need_create_task = true;
  13735. }
  13736. }
  13737. // 如果需要创建任务,调用图片生成服务
  13738. if ($need_create_task) {
  13739. try {
  13740. // 优先使用 pic_prompt,如果没有则使用 description
  13741. $pic_prompt = getProp($item, 'pic_prompt');
  13742. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13743. // 添加美术风格前缀
  13744. if ($art_style) {
  13745. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13746. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13747. $description = "{$prefix}:{$description}";
  13748. }
  13749. $params = [
  13750. 'prompt' => $description,
  13751. 'ref_img_urls' => []
  13752. ];
  13753. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13754. $task_id = $task->id;
  13755. if ($task_id) {
  13756. $item['task_id'] = $task_id;
  13757. $item['task_status'] = 'processing';
  13758. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13759. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13760. }
  13761. } catch (\Exception $e) {
  13762. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13763. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13764. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13765. // 不抛出异常,继续处理其他资源
  13766. }
  13767. }
  13768. }
  13769. return $merged_items;
  13770. }
  13771. /**
  13772. * 同步新出现的主体和场景到全局
  13773. *
  13774. * @param int $anime_id 动漫ID
  13775. * @param array $merged_roles 合并后的角色列表
  13776. * @param array $merged_scenes 合并后的场景列表
  13777. * @param array $global_roles 全局角色列表
  13778. * @param array $global_scenes 全局场景列表
  13779. * @return void
  13780. */
  13781. private function syncNewResourcesToGlobal(
  13782. int $anime_id,
  13783. array $merged_roles,
  13784. array $merged_scenes,
  13785. array $global_roles,
  13786. array $global_scenes
  13787. ): void {
  13788. // 构建全局角色映射表
  13789. $global_role_map = [];
  13790. foreach ($global_roles as $role) {
  13791. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13792. if ($roleKey !== '') {
  13793. $global_role_map[$roleKey] = $role;
  13794. }
  13795. }
  13796. // 构建全局场景映射表
  13797. $global_scene_map = [];
  13798. foreach ($global_scenes as $scene) {
  13799. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13800. if ($sceneKey !== '') {
  13801. $global_scene_map[$sceneKey] = $scene;
  13802. }
  13803. }
  13804. $need_update = false;
  13805. $new_global_roles = $global_roles;
  13806. $new_global_scenes = $global_scenes;
  13807. // 检查并添加新角色到全局
  13808. foreach ($merged_roles as $role) {
  13809. $role_name = getProp($role, 'role');
  13810. // 跳过旁白
  13811. if ($role_name === '旁白') {
  13812. continue;
  13813. }
  13814. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13815. if ($roleKey === '') {
  13816. continue;
  13817. }
  13818. // 如果全局中不存在该角色,添加到全局
  13819. if (!isset($global_role_map[$roleKey])) {
  13820. $new_global_roles[] = [
  13821. 'role' => $role_name,
  13822. 'description' => getProp($role, 'description', ''),
  13823. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13824. 'voice_name' => getProp($role, 'voice_name', ''),
  13825. 'voice_type' => getProp($role, 'voice_type', ''),
  13826. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13827. 'url' => getProp($role, 'url', ''),
  13828. 'task_id' => getProp($role, 'task_id', ''),
  13829. 'task_status' => getProp($role, 'task_status', ''),
  13830. ];
  13831. $global_role_map[$roleKey] = true; // 标记已添加
  13832. $need_update = true;
  13833. dLog('deepseek')->info("新角色同步到全局", [
  13834. 'anime_id' => $anime_id,
  13835. 'role' => $role_name,
  13836. 'task_id' => getProp($role, 'task_id', ''),
  13837. ]);
  13838. }
  13839. // else {
  13840. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13841. // $global_role = $global_role_map[$roleKey];
  13842. // if (is_array($global_role)) {
  13843. // $updated = false;
  13844. // $update_fields = [];
  13845. // // 检查描述是否更新
  13846. // $current_description = trim((string)getProp($role, 'description'));
  13847. // $global_description = trim((string)getProp($global_role, 'description'));
  13848. // if ($current_description !== '' && $current_description !== $global_description) {
  13849. // $updated = true;
  13850. // $update_fields[] = 'description';
  13851. // }
  13852. // // 检查pic_prompt是否更新
  13853. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13854. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13855. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13856. // $updated = true;
  13857. // $update_fields[] = 'pic_prompt';
  13858. // }
  13859. // // 检查图片任务信息是否更新
  13860. // $current_task_id = getProp($role, 'task_id');
  13861. // $global_task_id = getProp($global_role, 'task_id');
  13862. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13863. // $updated = true;
  13864. // $update_fields[] = 'task_id';
  13865. // }
  13866. // // 如果有更新,同步到全局
  13867. // if ($updated) {
  13868. // foreach ($new_global_roles as &$global_role_item) {
  13869. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  13870. // if ($global_role_key === $roleKey) {
  13871. // if (in_array('description', $update_fields)) {
  13872. // $global_role_item['description'] = $current_description;
  13873. // }
  13874. // if (in_array('pic_prompt', $update_fields)) {
  13875. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  13876. // }
  13877. // if (in_array('task_id', $update_fields)) {
  13878. // $global_role_item['task_id'] = $current_task_id;
  13879. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  13880. // $global_role_item['url'] = getProp($role, 'url', '');
  13881. // }
  13882. // break;
  13883. // }
  13884. // }
  13885. // $need_update = true;
  13886. // dLog('deepseek')->info("角色信息更新到全局", [
  13887. // 'anime_id' => $anime_id,
  13888. // 'role' => $role_name,
  13889. // 'update_fields' => implode(',', $update_fields),
  13890. // ]);
  13891. // }
  13892. // }
  13893. // }
  13894. }
  13895. // 检查并添加新场景到全局
  13896. foreach ($merged_scenes as $scene) {
  13897. $scene_name = getProp($scene, 'scene');
  13898. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  13899. if ($sceneKey === '') {
  13900. continue;
  13901. }
  13902. // 如果全局中不存在该场景,添加到全局
  13903. if (!isset($global_scene_map[$sceneKey])) {
  13904. $new_global_scenes[] = [
  13905. 'scene' => $scene_name,
  13906. 'description' => getProp($scene, 'description', ''),
  13907. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  13908. 'url' => getProp($scene, 'url', ''),
  13909. 'task_id' => getProp($scene, 'task_id', ''),
  13910. 'task_status' => getProp($scene, 'task_status', ''),
  13911. ];
  13912. $global_scene_map[$sceneKey] = true; // 标记已添加
  13913. $need_update = true;
  13914. dLog('deepseek')->info("新场景同步到全局", [
  13915. 'anime_id' => $anime_id,
  13916. 'scene' => $scene_name,
  13917. 'task_id' => getProp($scene, 'task_id', ''),
  13918. ]);
  13919. }
  13920. // else {
  13921. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13922. // $global_scene = $global_scene_map[$sceneKey];
  13923. // if (is_array($global_scene)) {
  13924. // $updated = false;
  13925. // $update_fields = [];
  13926. // // 检查描述是否更新
  13927. // $current_description = trim((string)getProp($scene, 'description'));
  13928. // $global_description = trim((string)getProp($global_scene, 'description'));
  13929. // if ($current_description !== '' && $current_description !== $global_description) {
  13930. // $updated = true;
  13931. // $update_fields[] = 'description';
  13932. // }
  13933. // // 检查pic_prompt是否更新
  13934. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  13935. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  13936. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13937. // $updated = true;
  13938. // $update_fields[] = 'pic_prompt';
  13939. // }
  13940. // // 检查图片任务信息是否更新
  13941. // $current_task_id = getProp($scene, 'task_id');
  13942. // $global_task_id = getProp($global_scene, 'task_id');
  13943. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13944. // $updated = true;
  13945. // $update_fields[] = 'task_id';
  13946. // }
  13947. // // 如果有更新,同步到全局
  13948. // if ($updated) {
  13949. // foreach ($new_global_scenes as &$global_scene_item) {
  13950. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  13951. // if ($global_scene_key === $sceneKey) {
  13952. // if (in_array('description', $update_fields)) {
  13953. // $global_scene_item['description'] = $current_description;
  13954. // }
  13955. // if (in_array('pic_prompt', $update_fields)) {
  13956. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  13957. // }
  13958. // if (in_array('task_id', $update_fields)) {
  13959. // $global_scene_item['task_id'] = $current_task_id;
  13960. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  13961. // $global_scene_item['url'] = getProp($scene, 'url', '');
  13962. // }
  13963. // break;
  13964. // }
  13965. // }
  13966. // $need_update = true;
  13967. // dLog('deepseek')->info("场景信息更新到全局", [
  13968. // 'anime_id' => $anime_id,
  13969. // 'scene' => $scene_name,
  13970. // 'update_fields' => implode(',', $update_fields),
  13971. // ]);
  13972. // }
  13973. // }
  13974. // }
  13975. }
  13976. // 如果有新增或更新,更新数据库
  13977. if ($need_update) {
  13978. $update_data = [
  13979. 'roles' => json_encode($new_global_roles, 256),
  13980. 'scenes' => json_encode($new_global_scenes, 256),
  13981. 'updated_at' => date('Y-m-d H:i:s'),
  13982. ];
  13983. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13984. if ($result !== false) {
  13985. dLog('deepseek')->info("全局角色和场景更新成功", [
  13986. 'anime_id' => $anime_id,
  13987. 'roles_count' => count($new_global_roles),
  13988. 'scenes_count' => count($new_global_scenes),
  13989. ]);
  13990. } else {
  13991. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  13992. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  13993. }
  13994. }
  13995. }
  13996. }