DeepSeekService.php 952 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498
  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\JsonSafeRepair;
  7. use App\Libs\Utils;
  8. use GuzzleHttp\Client;
  9. use DateTime;
  10. use DateTimeZone;
  11. use App\Models\MpTaskCenter;
  12. use App\Models\MpUserPointsDetail;
  13. use App\Services\AIGeneration\AIImageGenerationService;
  14. use App\Services\PointsService;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. use Illuminate\Support\Facades\Redis;
  18. use OSS\Core\OssException;
  19. use OSS\OssClient;
  20. use Smalot\PdfParser\Parser as PdfParser;
  21. use TCPDF;
  22. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  23. use Predis\Command\Traits\Get\Get;
  24. class DeepSeekService
  25. {
  26. private $url;
  27. private $api_key;
  28. private $sys_message;
  29. private $headers;
  30. private $valid_text_models;
  31. private $gpt_text_models;
  32. private $gemini_text_models;
  33. private $baidu_glm_text_models;
  34. protected $aiImageGenerationService;
  35. protected $pointsService;
  36. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  37. $this->aiImageGenerationService = $aiImageGenerationService;
  38. $this->pointsService = $pointsService;
  39. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  40. $this->api_key = env('DEEPSEEK_API_KEY');
  41. $this->headers = [
  42. 'Authorization' => 'Bearer '.$this->api_key,
  43. 'Content-Type' => 'application/json; charset=UTF-8'
  44. ];
  45. // 火山引擎模型列表
  46. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  47. // GPT文本模型列表
  48. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  49. // Gemini文本模型列表
  50. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  51. // 百度 AI 网关 GLM 文本模型列表
  52. $this->baidu_glm_text_models = BaseConst::BAIDU_GLM_TEXT_MODELS;
  53. $this->sys_message = [
  54. 'role' => 'system',
  55. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  56. 强制要求:\n
  57. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  58. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  59. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  60. 普通要求:\n
  61. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  62. 2.<分集剧本>的要求如下:
  63.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  64.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  65.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  66.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  67. \n\n
  68. 示例如下:\n
  69. ###剧本名:西昆仑
  70. ###故事梗概
  71. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  72. ###剧本亮点
  73. 亮点1:绝境奇药,生死一线
  74. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  75. 亮点2:结拜兄妹,化解尴尬
  76. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  77. 亮点3:纤发夺命,情愫暗涌
  78. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  79. ###人物关系
  80. 阿雪与梁萧之间存在兄妹之情。
  81. ###核心矛盾
  82. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  83. ###主体列表
  84. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  85. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  86. 阴阳球:天地异宝,能化生精气,救人于危难。
  87. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  88. ###美术风格
  89. 基础画风风格词:厚涂古风
  90. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  91. ###场景列表
  92. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  93. ###分集剧本
  94. ##分集01
  95. 第1集: 第一集的标题
  96. 场景描述:地点、时间、场景
  97. 运镜:固定近距离
  98. 出场角色:男主、女主
  99. 台词内容:
  100. 女主: 女主对话
  101. 男主:男主对话
  102. 女主: 女主对话
  103. 男主: 男主对话
  104. ##分集02
  105. 第2集: 第二集的标题
  106. 场景描述:地点、时间、场景
  107. 运镜:固定近距离
  108. 出场角色:男主、女主
  109. 台词内容:
  110. 女主: 女主对话
  111. 男主:男主对话
  112. 女主: 女主对话
  113. 男主: 男主对话"
  114. ];
  115. }
  116. /**
  117. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  118. *
  119. * @param array $data 请求参数
  120. * @return \Generator 返回生成器,用于流式输出
  121. */
  122. public function generateText($data) {
  123. // 获取请求参数
  124. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  125. $messages = getProp($data, 'messages', []);
  126. $systemPrompt = getProp($data, 'system_prompt', '');
  127. $prompt = getProp($data, 'prompt', '');
  128. $images = getProp($data, 'images', []); // 支持多张图片
  129. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  130. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  131. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  132. $isGeminiModel = in_array($model, $this->gemini_text_models);
  133. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  134. Utils::throwError('20003:仅Gemini模型支持视频输入');
  135. }
  136. // 计费预检:纯文生文按 normal 档(3);有参考图/视频输入按模型固定价格(图生文)
  137. $uid = Site::getUid();
  138. $chargeModality = '';
  139. $chargePoints = 0;
  140. $hasImageMedia = !empty($images) || !empty($imageUrls)
  141. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  142. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  143. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  144. if ($hasImageMedia || $hasVideoMedia) {
  145. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  146. $chargePoints = $this->pointsService->getImageChatChargePoints($model);
  147. } else {
  148. $chargeModality = 'text';
  149. $chargePoints = $this->pointsService->getChatChargePoints('', 'normal');
  150. }
  151. if ($chargePoints > 0) {
  152. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  153. }
  154. // 如果没有提供messages,则根据system_prompt、content和images构建
  155. if (empty($messages)) {
  156. $messages = [];
  157. // 添加系统提示词
  158. if (!empty($systemPrompt)) {
  159. $messages[] = [
  160. 'role' => 'system',
  161. 'content' => $systemPrompt
  162. ];
  163. }
  164. // 构建用户消息内容(支持文本+图片)
  165. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  166. $userMessage = [
  167. 'role' => 'user',
  168. 'content' => []
  169. ];
  170. // 添加文本内容
  171. if (!empty($prompt)) {
  172. $userMessage['content'][] = [
  173. 'type' => 'text',
  174. 'text' => $prompt
  175. ];
  176. }
  177. // 处理上传的图片文件
  178. if (!empty($images)) {
  179. if (!is_array($images)) {
  180. $images = [$images];
  181. }
  182. foreach ($images as $image) {
  183. $imageBase64 = $this->processImageToBase64($image);
  184. if ($imageBase64) {
  185. $userMessage['content'][] = [
  186. 'type' => 'image_url',
  187. 'image_url' => [
  188. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  189. ]
  190. ];
  191. }
  192. }
  193. }
  194. // 处理图片URL
  195. if (!empty($imageUrls)) {
  196. if (!is_array($imageUrls)) {
  197. $imageUrls = [$imageUrls];
  198. }
  199. foreach ($imageUrls as $url) {
  200. if (!empty($url)) {
  201. $userMessage['content'][] = [
  202. 'type' => 'image_url',
  203. 'image_url' => [
  204. 'url' => $url
  205. ]
  206. ];
  207. }
  208. }
  209. }
  210. // 处理上传的视频文件(仅 Gemini)
  211. if (!empty($videos) && $isGeminiModel) {
  212. if (!is_array($videos)) {
  213. $videos = [$videos];
  214. }
  215. foreach ($videos as $video) {
  216. $inlineData = $this->processMediaToInlineData($video);
  217. if ($inlineData) {
  218. $userMessage['content'][] = [
  219. 'type' => 'video',
  220. 'inline_data' => $inlineData
  221. ];
  222. }
  223. }
  224. }
  225. // 处理视频URL(仅 Gemini)
  226. if (!empty($videoUrls) && $isGeminiModel) {
  227. if (!is_array($videoUrls)) {
  228. $videoUrls = [$videoUrls];
  229. }
  230. foreach ($videoUrls as $url) {
  231. if (!empty($url)) {
  232. $userMessage['content'][] = [
  233. 'type' => 'video_url',
  234. 'video_url' => ['url' => $url]
  235. ];
  236. }
  237. }
  238. }
  239. // 如果只有文本内容,简化为字符串格式
  240. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  241. $userMessage['content'] = $userMessage['content'][0]['text'];
  242. }
  243. $messages[] = $userMessage;
  244. }
  245. }
  246. // 验证messages不为空
  247. if (empty($messages)) {
  248. Utils::throwError('20003:请提供有效的对话内容');
  249. }
  250. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  251. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  252. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  253. if ($model === 'deepseek-chat') {
  254. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'disabled';
  257. } elseif ($model === 'deepseek-reasoner') {
  258. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  259. $model = 'deepseek-v4-flash';
  260. $thinkingMode = 'enabled';
  261. }
  262. // 构建请求参数
  263. $post_data = [
  264. 'model' => $model,
  265. 'messages' => $messages,
  266. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  267. 'temperature' => getProp($data, 'temperature', 1),
  268. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  269. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  270. 'thinking' => ['type' => $thinkingMode],
  271. 'stream' => true // 启用流式输出
  272. ];
  273. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  274. // 添加可选参数
  275. if (isset($data['top_p'])) {
  276. $post_data['top_p'] = $data['top_p'];
  277. }
  278. if (isset($data['response_format'])) {
  279. $post_data['response_format'] = $data['response_format'];
  280. }
  281. // 根据模型类型选择流式实现
  282. $streamGenerator = $this->dispatchStreamByModel($post_data);
  283. if ($chargePoints > 0) {
  284. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  285. }
  286. // 免费场景(0 积分):流式生成成功后仅记录 token 使用明细
  287. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  288. }
  289. /**
  290. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  291. *
  292. * @param \Generator $generator
  293. * @param int $uid
  294. * @param string $model
  295. * @return \Generator
  296. */
  297. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  298. {
  299. $recorded = false;
  300. foreach ($generator as $chunk) {
  301. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  302. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  303. 'model' => $model,
  304. 'source' => $source,
  305. ], $model);
  306. $recorded = true;
  307. }
  308. yield $chunk;
  309. }
  310. }
  311. /**
  312. * 流式生成成功后再按档位/模型规则扣费(文生文 normal 档 / 图生文按模型固定价格)
  313. *
  314. * @param \Generator $generator
  315. * @param int $uid
  316. * @param string $model
  317. * @param int $points
  318. * @param string $modality
  319. * @return \Generator
  320. */
  321. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  322. {
  323. $charged = false;
  324. foreach ($generator as $chunk) {
  325. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  326. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  327. if ($fullContent !== '') {
  328. $this->chargeMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  329. $charged = true;
  330. }
  331. }
  332. yield $chunk;
  333. }
  334. }
  335. /**
  336. * AI 对话(含图片/视频 -> 文本)成功后扣费并记录积分与 token 明细
  337. *
  338. * @param int $uid
  339. * @param string $model
  340. * @param int $points
  341. * @param string $modality
  342. * @param mixed $usage
  343. * @return void
  344. */
  345. private function chargeMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  346. {
  347. $result = $this->pointsService->recordChatCharge(
  348. $uid,
  349. $points,
  350. $this->pointsService->getTokensFromUsage($usage),
  351. [
  352. 'model' => $model,
  353. 'modality' => $modality,
  354. 'source' => 'generateText',
  355. ],
  356. '',
  357. $model
  358. );
  359. if (empty($result['charged'])) {
  360. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  361. }
  362. }
  363. /**
  364. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  365. *
  366. * @param array $messages
  367. * @param array $mediaTypes
  368. * @return bool
  369. */
  370. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  371. {
  372. foreach ($messages as $message) {
  373. $content = getProp($message, 'content', '');
  374. if (!is_array($content)) {
  375. continue;
  376. }
  377. foreach ($content as $part) {
  378. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  379. return true;
  380. }
  381. }
  382. }
  383. return false;
  384. }
  385. public function createGenerateText($data) {
  386. $file = getProp($data, 'file');
  387. $episode_num = getProp($data, 'episode_num');
  388. $uid = Site::getUid();
  389. $cpid = Site::getCpid();
  390. if (!$file) {
  391. Utils::throwError('20003:请上传文件');
  392. }
  393. // 提取文件内容
  394. $content = $this->extractFileContent($file);
  395. if (!$content) {
  396. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  397. }
  398. // 拆分章节并校验章节总数、标题连续性
  399. if ($episode_num) {
  400. $this->validateGenerateTextChapters($content, (int)$episode_num);
  401. }
  402. // 获取原始文件名(不含扩展名)作为script_name
  403. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  404. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  405. // 字节安全剥离,不依赖服务器locale设置
  406. $originalName = $file->getClientOriginalName();
  407. $extension = $file->getClientOriginalExtension();
  408. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  409. ? substr($originalName, 0, -strlen($extension) - 1)
  410. : $originalName;
  411. if ($script_name === '') {
  412. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  413. }
  414. // 如果同一用户的剧本名存在则提示
  415. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  416. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  417. }
  418. // 插入数据到mp_scripts表
  419. $script_id = DB::table('mp_scripts')->insertGetId([
  420. 'script_name' => $script_name,
  421. 'user_id' => $uid,
  422. 'cpid' => $cpid,
  423. 'content' => $content,
  424. 'created_at' => date('Y-m-d H:i:s'),
  425. 'updated_at' => date('Y-m-d H:i:s')
  426. ]);
  427. return [
  428. 'script_id' => $script_id,
  429. 'script_name' => $script_name
  430. ];
  431. }
  432. /**
  433. * AI对话调用成功后的积分扣费(返回结果前调用)
  434. *
  435. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  436. *
  437. * @param int $uid
  438. * @param int $tokens
  439. * @param array $chargeInfo
  440. * @return void
  441. */
  442. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo, string $chargeType = 'special'): void
  443. {
  444. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  445. $model = (string)getProp($chargeInfo, 'model', '');
  446. $result = $this->pointsService->recordChatCharge(
  447. $uid,
  448. $this->pointsService->getChatChargePoints($model, $chargeType),
  449. $tokens,
  450. $chargeInfo,
  451. '',
  452. $model !== '' ? $model : 'deepseek'
  453. );
  454. if (empty($result['charged'])) {
  455. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  456. }
  457. }
  458. /**
  459. * 安全获取当前登录用户ID
  460. *
  461. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  462. *
  463. * @return int
  464. */
  465. private function getCurrentUid(): int
  466. {
  467. try {
  468. return (int)Site::getUid();
  469. } catch (\Throwable $e) {
  470. return 0;
  471. }
  472. }
  473. /**
  474. * 记录文生文 token 使用明细(仅记录,不扣积分)
  475. *
  476. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  477. *
  478. * @param int $uid 用户ID(0 时跳过)
  479. * @param int $tokens 消耗 token 数
  480. * @param array $chargeInfo 计费/来源信息(model、source 等)
  481. * @param string $apiType API 类型/模型标识
  482. * @return void
  483. */
  484. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  485. {
  486. try {
  487. $this->pointsService->recordTokenOnlyDetail(
  488. $uid,
  489. $tokens,
  490. $chargeInfo,
  491. MpUserPointsDetail::TYPE_CHAT,
  492. $apiType,
  493. ''
  494. );
  495. } catch (\Throwable $e) {
  496. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  497. 'uid' => $uid,
  498. 'source' => $chargeInfo['source'] ?? '',
  499. ]);
  500. }
  501. }
  502. /**
  503. * 拆分剧本内容并校验章节总数与标题连续性
  504. *
  505. * @param string $content
  506. * @param int $episodeNum
  507. * @return void
  508. */
  509. private function validateGenerateTextChapters($content, $episodeNum)
  510. {
  511. $chapters = splitContent($content);
  512. if (count($chapters) !== $episodeNum) {
  513. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  514. }
  515. if (empty($chapters)) {
  516. return;
  517. }
  518. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  519. $numbers = [];
  520. $unparsedIndex = null;
  521. foreach ($chapters as $index => $chapter) {
  522. $num = $this->parseChapterNumber($chapter['title']);
  523. if ($num === null) {
  524. $unparsedIndex = $index;
  525. break;
  526. }
  527. $numbers[] = $num;
  528. }
  529. if ($unparsedIndex === null) {
  530. $expected = 1;
  531. foreach ($numbers as $index => $num) {
  532. if ($num !== $expected) {
  533. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  534. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  535. }
  536. $expected++;
  537. }
  538. return;
  539. }
  540. // 标题格式无法用正则确认时,交给模型分析
  541. $titles = array_column($chapters, 'title');
  542. $aiResult = $this->validateChapterSequenceByAI($titles);
  543. if ($aiResult['valid'] === false) {
  544. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  545. if (isset($chapters[$badIndex - 1])) {
  546. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  547. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  548. }
  549. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  550. }
  551. if ($aiResult['valid'] === null) {
  552. if (isset($chapters[$unparsedIndex])) {
  553. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  554. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  555. }
  556. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  557. }
  558. }
  559. /**
  560. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  561. *
  562. * @param string $title
  563. * @return int|null
  564. */
  565. private function parseChapterNumber($title)
  566. {
  567. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  568. return null;
  569. }
  570. return $this->convertChineseNumber($match[1]);
  571. }
  572. /**
  573. * 中文数字转阿拉伯数字(支持到千)
  574. *
  575. * @param string $numStr
  576. * @return int
  577. */
  578. private function convertChineseNumber($numStr)
  579. {
  580. if (preg_match('/^\d+$/', $numStr)) {
  581. return (int)$numStr;
  582. }
  583. $map = [
  584. '零' => 0,
  585. '一' => 1,
  586. '二' => 2,
  587. '两' => 2,
  588. '三' => 3,
  589. '四' => 4,
  590. '五' => 5,
  591. '六' => 6,
  592. '七' => 7,
  593. '八' => 8,
  594. '九' => 9
  595. ];
  596. $total = 0;
  597. $section = 0;
  598. $length = mb_strlen($numStr);
  599. for ($i = 0; $i < $length; $i++) {
  600. $char = mb_substr($numStr, $i, 1);
  601. if (isset($map[$char])) {
  602. $section = $map[$char];
  603. } elseif ($char === '十') {
  604. $total += $section === 0 ? 10 : $section * 10;
  605. $section = 0;
  606. } elseif ($char === '百') {
  607. $total += $section === 0 ? 100 : $section * 100;
  608. $section = 0;
  609. } elseif ($char === '千') {
  610. $total += $section === 0 ? 1000 : $section * 1000;
  611. $section = 0;
  612. }
  613. }
  614. return $total + $section;
  615. }
  616. /**
  617. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  618. *
  619. * @param array $titles
  620. * @return array{valid: bool|null, invalid_index: int|null}
  621. */
  622. private function validateChapterSequenceByAI($titles)
  623. {
  624. $titleLines = [];
  625. foreach (array_slice($titles, 0, 200) as $index => $title) {
  626. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  627. }
  628. $result = [
  629. 'valid' => null,
  630. 'invalid_index' => null
  631. ];
  632. $post_data = [
  633. 'model' => 'deepseek-v4-flash',
  634. 'messages' => [
  635. [
  636. 'role' => 'system',
  637. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  638. ],
  639. [
  640. 'role' => 'user',
  641. 'content' => implode("\n", $titleLines),
  642. ],
  643. ],
  644. 'temperature' => 0,
  645. 'frequency_penalty' => 0,
  646. 'presence_penalty' => 0,
  647. 'stream' => false,
  648. ];
  649. try {
  650. $result = $this->chatOnly($post_data, 8);
  651. $content = trim((string)($result['fullContent'] ?? ''));
  652. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  653. $result['valid'] = strtolower($match[1]) === 'true';
  654. }
  655. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  656. $result['invalid_index'] = (int)$match[1];
  657. }
  658. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  659. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  660. 'model' => 'deepseek-v4-flash',
  661. 'source' => 'validateChapterSequenceByAI',
  662. ], 'deepseek-v4-flash');
  663. } catch (\Exception $e) {
  664. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  665. }
  666. return $result;
  667. }
  668. /**
  669. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  670. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  671. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  672. *
  673. * @param array $data 请求参数
  674. * @return \Generator
  675. */
  676. public function newGenerateTextStream($data, $existingTask = null) {
  677. $model = getProp($data, 'model', 'deepseek-v4-pro');
  678. $messages = getProp($data, 'messages', []);
  679. $systemPrompt = getProp($data, 'system_prompt', '');
  680. $prompt = getProp($data, 'prompt', '');
  681. $images = getProp($data, 'images', []);
  682. $imageUrls = getProp($data, 'image_urls', []);
  683. $responseFormat = getProp($data, 'response_format', 'text');
  684. $templateId = getProp($data, 'template_id', 0);
  685. $script_id = getProp($data, 'script_id', 0);
  686. $sequence = getProp($data, 'sequence', 0);
  687. $generateTaskId = 0;
  688. // 异步 worker 场景直接使用任务记录中的用户,避免命令行下无登录上下文
  689. $uid = $existingTask ? (int)$existingTask->uid : (int)Site::getUid();
  690. if ($script_id > 0 && !$existingTask) {
  691. $runningTask = DB::table('mp_script_generate_tasks')
  692. ->where('uid', $uid)
  693. ->where('script_id', $script_id)
  694. ->orderByDesc('id')
  695. ->first();
  696. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  697. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  698. }
  699. }
  700. // 如果提供了script_id,从数据库获取剧本内容作为原文
  701. $originalContent = '';
  702. $hasValidScript = false;
  703. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  704. if ($script_id > 0) {
  705. $script = DB::table('mp_scripts')
  706. ->where('id', $script_id)
  707. ->where('is_deleted', 0)
  708. ->first();
  709. if (!$script) {
  710. Utils::throwError('20003:剧本不存在或已删除');
  711. }
  712. $originalContent = $script->content ?? '';
  713. if (empty($originalContent)) {
  714. Utils::throwError('20003:剧本内容为空');
  715. }
  716. $hasValidScript = true;
  717. if (!empty($prompt)) {
  718. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  719. } else {
  720. $prompt = "原文内容:\n" . $originalContent;
  721. }
  722. }
  723. // 如果提供了template_id,从数据库获取template_prompt
  724. if ($templateId > 0) {
  725. $template = DB::table('mp_prompt_templates')
  726. ->where('id', $templateId)
  727. ->where('is_deleted', 0)
  728. ->first();
  729. if (!$template) {
  730. Utils::throwError('20003:模板不存在或已删除');
  731. }
  732. $templatePrompt = $template->template_prompt ?? '';
  733. if (!empty($templatePrompt)) {
  734. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  735. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  736. $trimmedRawPrompt = trim((string)$rawPrompt);
  737. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  738. if (!$hasValidScript) {
  739. $prompt = $templatePrompt;
  740. }
  741. } elseif (!empty($prompt)) {
  742. $prompt = $templatePrompt . "\n\n" . $prompt;
  743. } else {
  744. $prompt = $templatePrompt;
  745. }
  746. }
  747. }
  748. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  749. if (empty($messages)) {
  750. $messages = [];
  751. if (!empty($systemPrompt)) {
  752. $messages[] = [
  753. 'role' => 'system',
  754. 'content' => $systemPrompt
  755. ];
  756. }
  757. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  758. $userMessage = [
  759. 'role' => 'user',
  760. 'content' => []
  761. ];
  762. if (!empty($prompt)) {
  763. $userMessage['content'][] = [
  764. 'type' => 'text',
  765. 'text' => $prompt
  766. ];
  767. }
  768. if (!empty($images)) {
  769. if (!is_array($images)) {
  770. $images = [$images];
  771. }
  772. foreach ($images as $image) {
  773. $imageBase64 = $this->processImageToBase64($image);
  774. if ($imageBase64) {
  775. $userMessage['content'][] = [
  776. 'type' => 'image_url',
  777. 'image_url' => [
  778. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  779. ]
  780. ];
  781. }
  782. }
  783. }
  784. if (!empty($imageUrls)) {
  785. if (!is_array($imageUrls)) {
  786. $imageUrls = [$imageUrls];
  787. }
  788. foreach ($imageUrls as $url) {
  789. if (!empty($url)) {
  790. $userMessage['content'][] = [
  791. 'type' => 'image_url',
  792. 'image_url' => [
  793. 'url' => $url
  794. ]
  795. ];
  796. }
  797. }
  798. }
  799. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  800. $userMessage['content'] = $userMessage['content'][0]['text'];
  801. }
  802. $messages[] = $userMessage;
  803. }
  804. }
  805. if (empty($messages)) {
  806. Utils::throwError('20003:请提供有效的对话内容');
  807. }
  808. // 模型兼容性处理
  809. $thinkingMode = getProp($data, 'thinking', 'disabled');
  810. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  811. if ($model === 'deepseek-chat') {
  812. $model = 'deepseek-v4-flash';
  813. $thinkingMode = 'disabled';
  814. } elseif ($model === 'deepseek-reasoner') {
  815. $model = 'deepseek-v4-flash';
  816. $thinkingMode = 'enabled';
  817. }
  818. // 构建请求参数(流式)
  819. $post_data = [
  820. 'model' => $model,
  821. 'messages' => $messages,
  822. 'temperature' => getProp($data, 'temperature', 1),
  823. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  824. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  825. 'thinking' => ['type' => $thinkingMode],
  826. 'stream' => true
  827. ];
  828. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  829. if (isset($data['top_p'])) {
  830. $post_data['top_p'] = $data['top_p'];
  831. }
  832. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  833. if ($responseFormat === 'json') {
  834. $hasJsonKeyword = false;
  835. foreach ($post_data['messages'] as $message) {
  836. if (isset($message['content'])) {
  837. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  838. if (stripos($content, 'json') !== false) {
  839. $hasJsonKeyword = true;
  840. break;
  841. }
  842. }
  843. }
  844. if (!$hasJsonKeyword) {
  845. $lastMessageIndex = count($post_data['messages']) - 1;
  846. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  847. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  848. if (is_string($lastContent)) {
  849. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  850. } elseif (is_array($lastContent)) {
  851. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  852. if ($contentPart['type'] === 'text') {
  853. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  854. break;
  855. }
  856. }
  857. }
  858. }
  859. }
  860. $post_data['response_format'] = ['type' => 'json_object'];
  861. }
  862. // 如果提供了script_id,创建剧本资产生成任务
  863. if ($script_id > 0) {
  864. if ($existingTask) {
  865. // 异步 worker:接管已创建的 pending 任务,不再新建
  866. $generateTaskId = (int)$existingTask->id;
  867. } else {
  868. // 同步调用:保持原行为,创建 processing 任务
  869. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  870. 'uid' => $uid,
  871. 'script_id' => $script_id,
  872. 'sequence' => $sequence,
  873. 'status' => 'processing',
  874. 'prompt' => getProp($data, 'prompt', ''),
  875. 'started_at' => date('Y-m-d H:i:s'),
  876. 'created_at' => date('Y-m-d H:i:s'),
  877. 'updated_at' => date('Y-m-d H:i:s')
  878. ]);
  879. }
  880. }
  881. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  882. if ($hasValidScript) {
  883. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  884. }
  885. // 根据模型类型选择流式实现
  886. $streamGenerator = $this->dispatchStreamByModel($post_data);
  887. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  888. return $this->wrapNewGenerateTextStream($streamGenerator, [
  889. 'uid' => $uid,
  890. 'model' => $model,
  891. 'generate_task_id' => $generateTaskId,
  892. 'has_valid_script' => $hasValidScript,
  893. 'script_id' => $script_id,
  894. 'sequence' => $sequence,
  895. 'original_prompt' => getProp($data, 'prompt', ''),
  896. 'response_format' => $responseFormat,
  897. ]);
  898. }
  899. /**
  900. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  901. *
  902. * @param \Generator $generator
  903. * @param array $ctx
  904. * @return \Generator
  905. */
  906. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  907. {
  908. $fullContent = '';
  909. $usage = [];
  910. $finished = false;
  911. try {
  912. foreach ($generator as $chunk) {
  913. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  914. $fullContent .= (string)getProp($chunk, 'content', '');
  915. }
  916. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  917. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  918. $usage = getProp($chunk, 'usage', []);
  919. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  920. if (($ctx['response_format'] ?? 'text') === 'json') {
  921. $fullContent = $this->extractJsonContent($fullContent);
  922. }
  923. $finished = true;
  924. // 保存对话记录并将 records 附加到 done 消息(无论 script_id 是否有值都返回 records 数组)
  925. $chunk['records'] = [];
  926. if (!empty($ctx['script_id'])) {
  927. try {
  928. $now = now();
  929. // 两条对话记录(user/assistant)在同一事务内写入,保证原子性
  930. $chunk['records'] = DB::transaction(function () use ($ctx, $fullContent, $now) {
  931. DB::table('mp_script_records')->insert([
  932. [
  933. 'uid' => $ctx['uid'],
  934. 'script_id' => $ctx['script_id'],
  935. 'sequence' => $ctx['sequence'],
  936. 'role' => 'user',
  937. 'content' => $ctx['original_prompt'],
  938. 'created_at' => $now,
  939. 'updated_at' => $now,
  940. ],
  941. [
  942. 'uid' => $ctx['uid'],
  943. 'script_id' => $ctx['script_id'],
  944. 'sequence' => $ctx['sequence'],
  945. 'role' => 'assistant',
  946. 'content' => $fullContent,
  947. 'created_at' => $now,
  948. 'updated_at' => $now,
  949. ],
  950. ]);
  951. return DB::table('mp_script_records')
  952. ->where('uid', $ctx['uid'])
  953. ->where('script_id', $ctx['script_id'])
  954. ->where('sequence', $ctx['sequence'])
  955. ->orderBy('id', 'desc')
  956. ->limit(2)
  957. ->get()
  958. ->map(function ($record) {
  959. return [
  960. 'rid' => $record->id,
  961. 'script_id' => $record->script_id,
  962. 'sequence' => $record->sequence,
  963. 'role' => $record->role,
  964. 'content' => $record->content,
  965. 'created_at' => $record->created_at,
  966. ];
  967. })
  968. ->reverse()
  969. ->values()
  970. ->toArray();
  971. });
  972. } catch (\Exception $e) {
  973. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  974. $chunk['records'] = [];
  975. }
  976. }
  977. }
  978. yield $chunk;
  979. }
  980. if ($finished) {
  981. // 任务状态与扣费在同一事务内:扣费失败则任务状态一并回滚,由外层 catch 置为 failed
  982. DB::transaction(function () use ($ctx, $fullContent, $usage) {
  983. if (!empty($ctx['generate_task_id'])) {
  984. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  985. 'status' => 'success',
  986. 'result' => $fullContent,
  987. 'completed_at' => date('Y-m-d H:i:s'),
  988. 'updated_at' => date('Y-m-d H:i:s'),
  989. ]);
  990. }
  991. if ($ctx['has_valid_script'] && $fullContent !== '') {
  992. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  993. 'model' => $ctx['model'],
  994. 'script_id' => $ctx['script_id'],
  995. 'sequence' => $ctx['sequence'],
  996. 'source' => 'newGenerateText',
  997. ]);
  998. }
  999. });
  1000. // JSON 输出结果的安全校验/修复与观察(事务外执行,不改变 result 与 SSE 推送内容)
  1001. if (!empty($ctx['generate_task_id'])) {
  1002. $this->guardScriptGenerateJsonResult(
  1003. (int)$ctx['generate_task_id'],
  1004. (int)($ctx['script_id'] ?? 0),
  1005. (int)($ctx['uid'] ?? 0),
  1006. (string)$fullContent,
  1007. (string)($ctx['response_format'] ?? '')
  1008. );
  1009. }
  1010. }
  1011. } catch (\Throwable $e) {
  1012. if (!empty($ctx['generate_task_id'])) {
  1013. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  1014. 'status' => 'failed',
  1015. 'error_message' => $e->getMessage(),
  1016. 'completed_at' => date('Y-m-d H:i:s'),
  1017. 'updated_at' => date('Y-m-d H:i:s'),
  1018. ]);
  1019. }
  1020. yield [
  1021. 'type' => 'error',
  1022. 'message' => $e->getMessage(),
  1023. ];
  1024. }
  1025. }
  1026. /**
  1027. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1028. *
  1029. * @param string $content
  1030. * @return string
  1031. */
  1032. private function extractJsonContent(string $content): string
  1033. {
  1034. $content = trim($content);
  1035. if ($content === '') {
  1036. return $content;
  1037. }
  1038. // 剥离 ```json ... ``` 代码块
  1039. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1040. $content = trim($m[1]);
  1041. }
  1042. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1043. $first = strpos($content, '{');
  1044. $last = strrpos($content, '}');
  1045. if ($first !== false && $last !== false && $last > $first) {
  1046. $content = substr($content, $first, $last - $first + 1);
  1047. }
  1048. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1049. json_decode($content, true);
  1050. if (json_last_error() !== JSON_ERROR_NONE) {
  1051. return trim($content);
  1052. }
  1053. return $content;
  1054. }
  1055. /**
  1056. * 剧本资产生成结果的 JSON 安全校验/修复与观察
  1057. *
  1058. * 规则:
  1059. * - result 永远保留模型原文,本方法不修改 result;
  1060. * - 仅当原文非法 JSON 且 JsonSafeRepair 安全修复成功时,才把修复后的标准
  1061. * JSON 写入 mp_script_generate_tasks.json_result;
  1062. * - 每次生成结果都写一条 system_logs(channel=script_generate_json),
  1063. * 用于观察非法 JSON 的发生率与修复率。
  1064. *
  1065. * @param int $taskId 剧本资产生成任务 ID
  1066. * @param int $scriptId 剧本 ID
  1067. * @param int $uid 用户 ID
  1068. * @param string $raw 已落库的 result 原文
  1069. * @param string $responseFormat 请求的 response_format
  1070. * @return void
  1071. */
  1072. private function guardScriptGenerateJsonResult(int $taskId, int $scriptId, int $uid, string $raw, string $responseFormat): void
  1073. {
  1074. if ($taskId <= 0 || $raw === '') {
  1075. return;
  1076. }
  1077. // 仅对"要求 JSON 输出"或"内容明显是 JSON"的结果做校验,避免误伤普通文本结果
  1078. $trimmed = ltrim($raw);
  1079. $looksLikeJson = $responseFormat === 'json'
  1080. || (isset($trimmed[0]) && ($trimmed[0] === '{' || $trimmed[0] === '['));
  1081. if (!$looksLikeJson) {
  1082. return;
  1083. }
  1084. $repair = JsonSafeRepair::repair($raw);
  1085. $common = [
  1086. 'task_id' => $taskId,
  1087. 'script_id' => $scriptId,
  1088. 'uid' => $uid,
  1089. 'raw_length' => strlen($raw),
  1090. ];
  1091. if ($repair['ok'] && $repair['json'] !== $raw) {
  1092. // 原文非法但安全修复成功:修复版另存 json_result,result 仍保留原文
  1093. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1094. 'json_result' => $repair['json'],
  1095. 'updated_at' => date('Y-m-d H:i:s'),
  1096. ]);
  1097. logDB('script_generate_json', 'warning', '生成JSON修复成功', $common + [
  1098. 'json_state' => 'repaired',
  1099. 'json_length' => strlen((string)$repair['json']),
  1100. 'removed_count' => count($repair['removed_positions']),
  1101. 'removed_positions' => $repair['removed_positions'],
  1102. ]);
  1103. return;
  1104. }
  1105. if ($repair['ok']) {
  1106. // 原文本身就是合法 JSON
  1107. logDB('script_generate_json', 'info', '生成JSON校验通过', $common + [
  1108. 'json_state' => 'valid',
  1109. ]);
  1110. return;
  1111. }
  1112. // 非法 JSON 且不在安全修复范围内:保留原文,只记录观察日志
  1113. logDB('script_generate_json', 'error', '生成JSON修复失败', $common + [
  1114. 'json_state' => 'repair_failed',
  1115. 'reason' => $repair['reason'],
  1116. ]);
  1117. }
  1118. /**
  1119. * 创建剧本资产生成异步任务(stream=1 + script_id 走异步任务模式)
  1120. *
  1121. * @param array $data 原请求参数
  1122. * @return int 任务ID
  1123. */
  1124. public function createScriptGenerateAsyncTask(array $data): int
  1125. {
  1126. $script_id = (int)getProp($data, 'script_id', 0);
  1127. if ($script_id <= 0) {
  1128. Utils::throwError('20003:缺少剧本ID');
  1129. }
  1130. $uid = (int)Site::getUid();
  1131. // 与同步逻辑一致:同一剧本存在生成中任务时直接拒绝
  1132. $runningTask = DB::table('mp_script_generate_tasks')
  1133. ->where('uid', $uid)
  1134. ->where('script_id', $script_id)
  1135. ->orderByDesc('id')
  1136. ->first();
  1137. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  1138. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1139. }
  1140. // 前置校验剧本存在且内容非空,避免创建无效任务
  1141. $script = DB::table('mp_scripts')
  1142. ->where('id', $script_id)
  1143. ->where('is_deleted', 0)
  1144. ->first();
  1145. if (!$script) {
  1146. Utils::throwError('20003:剧本不存在或已删除');
  1147. }
  1148. if (empty($script->content)) {
  1149. Utils::throwError('20003:剧本内容为空');
  1150. }
  1151. // newGenerateText 请求不含上传文件对象,images/image_urls 以字符串形式传入,可直接序列化
  1152. $paramsJson = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  1153. if ($paramsJson === false) {
  1154. Utils::throwError('20003:请求参数序列化失败');
  1155. }
  1156. $now = date('Y-m-d H:i:s');
  1157. return (int)DB::table('mp_script_generate_tasks')->insertGetId([
  1158. 'uid' => $uid,
  1159. 'script_id' => $script_id,
  1160. 'sequence' => (int)getProp($data, 'sequence', 0),
  1161. 'status' => 'pending',
  1162. 'prompt' => (string)getProp($data, 'prompt', ''),
  1163. 'request_params' => $paramsJson,
  1164. 'started_at' => $now,
  1165. 'created_at' => $now,
  1166. 'updated_at' => $now,
  1167. ]);
  1168. }
  1169. /**
  1170. * 供 SSE 轮询:查询任务状态与增量 chunks
  1171. *
  1172. * @param int $taskId
  1173. * @param int $uid 当前登录用户,防越权
  1174. * @param int $afterSeq 已推送的最大 seq
  1175. * @return array{found:bool, task:?object, chunks:array, status:?string, error_message:?string}
  1176. */
  1177. public function pollScriptGenerateTask(int $taskId, int $uid, int $afterSeq = -1): array
  1178. {
  1179. $task = DB::table('mp_script_generate_tasks')
  1180. ->where('id', $taskId)
  1181. ->where('uid', $uid)
  1182. ->first();
  1183. if (!$task) {
  1184. return ['found' => false, 'task' => null, 'chunks' => [], 'status' => null, 'error_message' => null];
  1185. }
  1186. $rows = DB::table('mp_script_generate_task_chunks')
  1187. ->where('task_id', $taskId)
  1188. ->where('seq', '>', $afterSeq)
  1189. ->orderBy('seq')
  1190. ->get();
  1191. $chunks = [];
  1192. foreach ($rows as $row) {
  1193. $payload = json_decode((string)$row->payload, true);
  1194. if (is_array($payload)) {
  1195. $chunks[] = $payload;
  1196. }
  1197. }
  1198. return [
  1199. 'found' => true,
  1200. 'task' => $task,
  1201. 'chunks' => $chunks,
  1202. 'status' => (string)$task->status,
  1203. 'error_message' => (string)($task->error_message ?? ''),
  1204. ];
  1205. }
  1206. /**
  1207. * 异步 worker 执行入口:抢占 pending 任务并流式请求大模型
  1208. *
  1209. * 由 text:generate:run 命令调用;worker 内完成 chunks 落库,模型结束后
  1210. * 由流式包装(wrapNewGenerateTextStream)完成 records/扣费/任务状态/json 修复收尾。
  1211. *
  1212. * @param int $taskId
  1213. * @return array{ok:bool, task_id:int, status:?string, seq:int, error:?string}
  1214. */
  1215. public function runScriptGenerateTaskAsync(int $taskId): array
  1216. {
  1217. // 原子抢占:只允许 pending -> processing,避免重复执行
  1218. $claimed = DB::table('mp_script_generate_tasks')
  1219. ->where('id', $taskId)
  1220. ->where('status', 'pending')
  1221. ->update([
  1222. 'status' => 'processing',
  1223. 'started_at' => date('Y-m-d H:i:s'),
  1224. 'updated_at' => date('Y-m-d H:i:s'),
  1225. ]);
  1226. if (!$claimed) {
  1227. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务已被处理或状态异常'];
  1228. }
  1229. $task = DB::table('mp_script_generate_tasks')->where('id', $taskId)->first();
  1230. if (!$task) {
  1231. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务不存在'];
  1232. }
  1233. $params = json_decode((string)getProp($task, 'request_params', ''), true);
  1234. if (!is_array($params)) {
  1235. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1236. 'status' => 'failed',
  1237. 'error_message' => '任务请求参数缺失',
  1238. 'completed_at' => date('Y-m-d H:i:s'),
  1239. 'updated_at' => date('Y-m-d H:i:s'),
  1240. ]);
  1241. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => 0, 'error' => '任务请求参数缺失'];
  1242. }
  1243. // 兼容旧参数未带 stream 的情况
  1244. $params['stream'] = 1;
  1245. $seq = 0;
  1246. try {
  1247. $generator = $this->newGenerateTextStream($params, $task);
  1248. foreach ($generator as $chunk) {
  1249. DB::table('mp_script_generate_task_chunks')->insert([
  1250. 'task_id' => $taskId,
  1251. 'seq' => $seq,
  1252. 'chunk_type' => (string)getProp($chunk, 'type', 'content'),
  1253. 'payload' => json_encode($chunk, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
  1254. 'created_at' => date('Y-m-d H:i:s'),
  1255. ]);
  1256. $seq++;
  1257. }
  1258. $finalStatus = (string)DB::table('mp_script_generate_tasks')->where('id', $taskId)->value('status');
  1259. return ['ok' => $finalStatus === 'success', 'task_id' => $taskId, 'status' => $finalStatus, 'seq' => $seq, 'error' => null];
  1260. } catch (\Throwable $e) {
  1261. // 兜底:正常流程中 wrap 会自行把任务置为 failed,这里防止未知异常导致任务卡死
  1262. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1263. 'status' => 'failed',
  1264. 'error_message' => $e->getMessage(),
  1265. 'completed_at' => date('Y-m-d H:i:s'),
  1266. 'updated_at' => date('Y-m-d H:i:s'),
  1267. ]);
  1268. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => $seq, 'error' => $e->getMessage()];
  1269. }
  1270. }
  1271. /**
  1272. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1273. *
  1274. * @param array $data 请求参数
  1275. * @return array 返回结果数组
  1276. */
  1277. public function newGenerateText($data) {
  1278. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1279. if ((int)getProp($data, 'stream', 0) === 1) {
  1280. return $this->newGenerateTextStream($data);
  1281. }
  1282. // 获取请求参数
  1283. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1284. $messages = getProp($data, 'messages', []);
  1285. $systemPrompt = getProp($data, 'system_prompt', '');
  1286. $prompt = getProp($data, 'prompt', '');
  1287. $images = getProp($data, 'images', []); // 支持多张图片
  1288. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1289. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1290. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1291. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1292. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1293. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1294. $generateTaskId = 0;
  1295. $uid = Site::getUid();
  1296. if ($script_id > 0) {
  1297. $existingTask = DB::table('mp_script_generate_tasks')
  1298. ->where('uid', $uid)
  1299. ->where('script_id', $script_id)
  1300. ->orderByDesc('id')
  1301. ->first();
  1302. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1303. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1304. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1305. }
  1306. }
  1307. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1308. $originalContent = '';
  1309. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1310. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  1311. if ($script_id > 0) {
  1312. $script = DB::table('mp_scripts')
  1313. ->where('id', $script_id)
  1314. ->where('is_deleted', 0)
  1315. ->first();
  1316. if (!$script) {
  1317. Utils::throwError('20003:剧本不存在或已删除');
  1318. }
  1319. $originalContent = $script->content ?? '';
  1320. if (empty($originalContent)) {
  1321. Utils::throwError('20003:剧本内容为空');
  1322. }
  1323. $hasValidScript = true;
  1324. // 将剧本内容添加到提示词前面
  1325. if (!empty($originalContent)) {
  1326. if (!empty($prompt)) {
  1327. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1328. } else {
  1329. $prompt = "原文内容:\n" . $originalContent;
  1330. }
  1331. }
  1332. }
  1333. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1334. if ($templateId > 0) {
  1335. $template = DB::table('mp_prompt_templates')
  1336. ->where('id', $templateId)
  1337. ->where('is_deleted', 0)
  1338. ->first();
  1339. if (!$template) {
  1340. Utils::throwError('20003:模板不存在或已删除');
  1341. }
  1342. $templatePrompt = $template->template_prompt ?? '';
  1343. // 将模板提示词和用户输入的prompt组合
  1344. // 模板为准,用户输入作为补充要求
  1345. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  1346. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  1347. if (!empty($templatePrompt)) {
  1348. $trimmedRawPrompt = trim((string)$rawPrompt);
  1349. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  1350. if (!$hasValidScript) {
  1351. $prompt = $templatePrompt;
  1352. }
  1353. } elseif (!empty($prompt)) {
  1354. $prompt = $templatePrompt . "\n\n" . $prompt;
  1355. } else {
  1356. $prompt = $templatePrompt;
  1357. }
  1358. }
  1359. }
  1360. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1361. if (empty($messages)) {
  1362. $messages = [];
  1363. // 添加系统提示词
  1364. if (!empty($systemPrompt)) {
  1365. $messages[] = [
  1366. 'role' => 'system',
  1367. 'content' => $systemPrompt
  1368. ];
  1369. }
  1370. // 构建用户消息内容(支持文本+图片)
  1371. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1372. $userMessage = [
  1373. 'role' => 'user',
  1374. 'content' => []
  1375. ];
  1376. // 添加文本内容
  1377. if (!empty($prompt)) {
  1378. $userMessage['content'][] = [
  1379. 'type' => 'text',
  1380. 'text' => $prompt
  1381. ];
  1382. }
  1383. // 处理上传的图片文件
  1384. if (!empty($images)) {
  1385. if (!is_array($images)) {
  1386. $images = [$images];
  1387. }
  1388. foreach ($images as $image) {
  1389. $imageBase64 = $this->processImageToBase64($image);
  1390. if ($imageBase64) {
  1391. $userMessage['content'][] = [
  1392. 'type' => 'image_url',
  1393. 'image_url' => [
  1394. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1395. ]
  1396. ];
  1397. }
  1398. }
  1399. }
  1400. // 处理图片URL
  1401. if (!empty($imageUrls)) {
  1402. if (!is_array($imageUrls)) {
  1403. $imageUrls = [$imageUrls];
  1404. }
  1405. foreach ($imageUrls as $url) {
  1406. if (!empty($url)) {
  1407. $userMessage['content'][] = [
  1408. 'type' => 'image_url',
  1409. 'image_url' => [
  1410. 'url' => $url
  1411. ]
  1412. ];
  1413. }
  1414. }
  1415. }
  1416. // 如果只有文本内容,简化为字符串格式
  1417. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1418. $userMessage['content'] = $userMessage['content'][0]['text'];
  1419. }
  1420. $messages[] = $userMessage;
  1421. }
  1422. }
  1423. // 验证messages不为空
  1424. if (empty($messages)) {
  1425. Utils::throwError('20003:请提供有效的对话内容');
  1426. }
  1427. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1428. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1429. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1430. if ($model === 'deepseek-chat') {
  1431. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1432. $model = 'deepseek-v4-flash';
  1433. $thinkingMode = 'disabled';
  1434. } elseif ($model === 'deepseek-reasoner') {
  1435. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1436. $model = 'deepseek-v4-flash';
  1437. $thinkingMode = 'enabled';
  1438. }
  1439. // 构建请求参数(非流式)
  1440. $post_data = [
  1441. 'model' => $model,
  1442. 'messages' => $messages,
  1443. 'temperature' => getProp($data, 'temperature', 1),
  1444. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1445. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1446. 'thinking' => ['type' => $thinkingMode],
  1447. 'stream' => false // 非流式输出
  1448. ];
  1449. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1450. // 添加可选参数
  1451. if (isset($data['top_p'])) {
  1452. $post_data['top_p'] = $data['top_p'];
  1453. }
  1454. // 新增: 根据response_format设置响应格式
  1455. if ($responseFormat === 'json') {
  1456. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1457. $hasJsonKeyword = false;
  1458. foreach ($post_data['messages'] as $message) {
  1459. if (isset($message['content'])) {
  1460. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1461. if (stripos($content, 'json') !== false) {
  1462. $hasJsonKeyword = true;
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1468. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1469. if (!$hasJsonKeyword) {
  1470. $lastMessageIndex = count($post_data['messages']) - 1;
  1471. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1472. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1473. // 如果content是字符串,直接追加
  1474. if (is_string($lastContent)) {
  1475. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1476. }
  1477. // 如果content是数组(包含文本和图片),在文本部分追加
  1478. else if (is_array($lastContent)) {
  1479. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1480. if ($contentPart['type'] === 'text') {
  1481. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1482. break;
  1483. }
  1484. }
  1485. }
  1486. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1487. }
  1488. }
  1489. // 设置response_format参数(所有支持的模型)
  1490. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1491. // DeepSeek模型
  1492. $post_data['response_format'] = ['type' => 'json_object'];
  1493. } else if (in_array($model, $this->gpt_text_models)) {
  1494. // GPT模型
  1495. $post_data['response_format'] = ['type' => 'json_object'];
  1496. } else if (in_array($model, $this->valid_text_models)) {
  1497. // 火山引擎模型
  1498. $post_data['response_format'] = ['type' => 'json_object'];
  1499. }
  1500. }
  1501. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1502. if ($script_id > 0) {
  1503. $uid = Site::getUid();
  1504. // 创建新的生成任务
  1505. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1506. 'uid' => $uid,
  1507. 'script_id' => $script_id,
  1508. 'sequence' => $sequence,
  1509. 'status' => 'processing',
  1510. 'prompt' => getProp($data, 'prompt', ''),
  1511. 'started_at' => date('Y-m-d H:i:s'),
  1512. 'created_at' => date('Y-m-d H:i:s'),
  1513. 'updated_at' => date('Y-m-d H:i:s')
  1514. ]);
  1515. }
  1516. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1517. if ($hasValidScript) {
  1518. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1519. }
  1520. // 统一分模型调用非流式实现
  1521. try {
  1522. $aiResult = null;
  1523. $result = $this->dispatchChatOnlyByModel($post_data);
  1524. dLog('deepseek')->info('newGenerateText模型调用完成', ['requested_model' => $model]);
  1525. $aiResult = [
  1526. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1527. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1528. 'usage' => $result['usage'] ?? [],
  1529. 'model' => $model,
  1530. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1531. ];
  1532. } catch (\Exception $e) {
  1533. // 生成失败,更新任务状态
  1534. if ($generateTaskId) {
  1535. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1536. 'status' => 'failed',
  1537. 'error_message' => $e->getMessage(),
  1538. 'completed_at' => date('Y-m-d H:i:s'),
  1539. 'updated_at' => date('Y-m-d H:i:s')
  1540. ]);
  1541. }
  1542. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1543. }
  1544. // 生成成功,更新任务状态
  1545. if ($generateTaskId && $aiResult) {
  1546. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1547. 'status' => 'success',
  1548. 'result' => getProp($aiResult, 'content', ''),
  1549. 'completed_at' => date('Y-m-d H:i:s'),
  1550. 'updated_at' => date('Y-m-d H:i:s')
  1551. ]);
  1552. $aiResult['generate_task_id'] = $generateTaskId;
  1553. // JSON 输出结果的安全校验/修复与观察(不改变 result)
  1554. $this->guardScriptGenerateJsonResult(
  1555. (int)$generateTaskId,
  1556. (int)$script_id,
  1557. (int)$uid,
  1558. (string)getProp($aiResult, 'content', ''),
  1559. (string)$responseFormat
  1560. );
  1561. }
  1562. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1563. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1564. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1565. 'model' => $model,
  1566. 'script_id' => $script_id,
  1567. 'sequence' => $sequence,
  1568. 'source' => 'newGenerateText',
  1569. ]);
  1570. }
  1571. // 新增: 如果提供了script_id,保存对话记录
  1572. if ($script_id > 0 && $aiResult) {
  1573. try {
  1574. $uid = Site::getUid();
  1575. $now = now();
  1576. // 获取用户原始的prompt(不包含剧本内容)
  1577. $originalPrompt = getProp($data, 'prompt', '');
  1578. $recordsToInsert = [
  1579. [
  1580. 'uid' => $uid,
  1581. 'script_id' => $script_id,
  1582. 'sequence' => $sequence,
  1583. 'role' => 'user',
  1584. 'content' => $originalPrompt,
  1585. 'created_at' => $now,
  1586. 'updated_at' => $now,
  1587. ],
  1588. [
  1589. 'uid' => $uid,
  1590. 'script_id' => $script_id,
  1591. 'sequence' => $sequence,
  1592. 'role' => 'assistant',
  1593. 'content' => $aiResult['content'],
  1594. 'created_at' => $now,
  1595. 'updated_at' => $now,
  1596. ]
  1597. ];
  1598. DB::table('mp_script_records')->insert($recordsToInsert);
  1599. // 获取刚插入的记录ID(假设按插入顺序返回)
  1600. $insertedRecords = DB::table('mp_script_records')
  1601. ->where('uid', $uid)
  1602. ->where('script_id', $script_id)
  1603. ->where('sequence', $sequence)
  1604. ->orderBy('id', 'desc')
  1605. ->limit(2)
  1606. ->get()
  1607. ->map(function ($record) {
  1608. return [
  1609. 'rid' => $record->id,
  1610. 'script_id' => $record->script_id,
  1611. 'sequence' => $record->sequence,
  1612. 'role' => $record->role,
  1613. 'content' => $record->content,
  1614. 'created_at' => $record->created_at,
  1615. ];
  1616. })
  1617. ->reverse()
  1618. ->values()
  1619. ->toArray();
  1620. // 将记录信息添加到返回结果中
  1621. $aiResult['records'] = $insertedRecords;
  1622. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1623. } catch (\Exception $e) {
  1624. // 记录错误但不影响主流程
  1625. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1626. }
  1627. }
  1628. // 未提供 script_id 或保存失败时,也返回 records 数组(保持返回结构一致)
  1629. if (!isset($aiResult['records'])) {
  1630. $aiResult['records'] = [];
  1631. }
  1632. return $aiResult;
  1633. }
  1634. /**
  1635. * 通用 Gemini 文生文方法(支持流式和非流式)
  1636. *
  1637. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1638. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1639. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1640. * system_prompt 系统提示词(可选)
  1641. * prompt 用户提示词(可选)
  1642. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1643. * image_urls 图片/视频URL列表(可选,同上)
  1644. * temperature 温度(可选,默认 1)
  1645. * top_p 核采样(可选)
  1646. * max_tokens 最大输出 token(可选,默认 8192)
  1647. * response_format text/json(可选)
  1648. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1649. * thinking_budget 思考预算(可选,默认 20)
  1650. * stream 是否流式(可选,默认 false)
  1651. *
  1652. * @param array $data 请求参数
  1653. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1654. */
  1655. public function geminiGenerateText($data) {
  1656. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1657. $isStream = (bool)getProp($data, 'stream', false);
  1658. if (!in_array($model, $this->gemini_text_models)) {
  1659. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1660. }
  1661. $requestData = $this->buildGeminiRequestBody($data, $model);
  1662. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1663. if ($isStream) {
  1664. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1665. return $this->wrapGenerateTextTokenRecord(
  1666. $this->geminiStreamResponse($requestData, $model),
  1667. $this->getCurrentUid(),
  1668. $model,
  1669. 'geminiGenerateText'
  1670. );
  1671. }
  1672. // 非流式:成功后记录 token 使用明细(不扣积分)
  1673. $result = $this->geminiChatOnly($requestData, $model);
  1674. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1675. 'model' => $model,
  1676. 'source' => 'geminiGenerateText',
  1677. ], $model);
  1678. return $result;
  1679. }
  1680. /**
  1681. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1682. */
  1683. private function geminiMediaMaxBytes() {
  1684. return 14 * 1024 * 1024;
  1685. }
  1686. /**
  1687. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1688. */
  1689. private function buildGeminiRequestBody($data, $model) {
  1690. $messages = getProp($data, 'messages', []);
  1691. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1692. if (empty($messages)) {
  1693. $systemPrompt = getProp($data, 'system_prompt', '');
  1694. $prompt = getProp($data, 'prompt', '');
  1695. $images = getProp($data, 'images', []);
  1696. $imageUrls = getProp($data, 'image_urls', []);
  1697. $messages = [];
  1698. if (!empty($systemPrompt)) {
  1699. $messages[] = [
  1700. 'role' => 'system',
  1701. 'content' => $systemPrompt
  1702. ];
  1703. }
  1704. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1705. $userMessage = ['role' => 'user', 'content' => []];
  1706. if (!empty($prompt)) {
  1707. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1708. }
  1709. if (!empty($images)) {
  1710. if (!is_array($images)) {
  1711. $images = [$images];
  1712. }
  1713. foreach ($images as $image) {
  1714. $inlineData = $this->processMediaToInlineData($image);
  1715. if ($inlineData) {
  1716. $userMessage['content'][] = [
  1717. 'type' => 'image',
  1718. 'inline_data' => $inlineData
  1719. ];
  1720. }
  1721. }
  1722. }
  1723. if (!empty($imageUrls)) {
  1724. if (!is_array($imageUrls)) {
  1725. $imageUrls = [$imageUrls];
  1726. }
  1727. foreach ($imageUrls as $url) {
  1728. if (!empty($url)) {
  1729. $inlineData = $this->processMediaToInlineData($url);
  1730. if ($inlineData) {
  1731. $userMessage['content'][] = [
  1732. 'type' => 'image',
  1733. 'inline_data' => $inlineData
  1734. ];
  1735. }
  1736. }
  1737. }
  1738. }
  1739. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1740. $userMessage['content'] = $userMessage['content'][0]['text'];
  1741. }
  1742. $messages[] = $userMessage;
  1743. }
  1744. }
  1745. if (empty($messages)) {
  1746. Utils::throwError('20003:请提供有效的对话内容');
  1747. }
  1748. // 转换为 Gemini contents 格式
  1749. $systemInstruction = '';
  1750. $contents = [];
  1751. foreach ($messages as $message) {
  1752. $role = getProp($message, 'role', 'user');
  1753. $content = getProp($message, 'content', '');
  1754. if ($role === 'system') {
  1755. if (is_array($content)) {
  1756. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1757. } else {
  1758. $systemInstruction = (string)$content;
  1759. }
  1760. continue;
  1761. }
  1762. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1763. $parts = [];
  1764. if (is_array($content)) {
  1765. foreach ($content as $part) {
  1766. $partType = getProp($part, 'type', 'text');
  1767. if ($partType === 'text') {
  1768. $text = (string)getProp($part, 'text', '');
  1769. if ($text !== '') {
  1770. $parts[] = ['text' => $text];
  1771. }
  1772. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1773. if (in_array($partType, ['image_url', 'video_url'])) {
  1774. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1775. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1776. } elseif (isset($part['inline_data'])) {
  1777. // 已处理过的 inline_data 直接使用
  1778. $parts[] = ['inline_data' => $part['inline_data']];
  1779. continue;
  1780. } else {
  1781. $url = '';
  1782. }
  1783. $inlineData = $this->processMediaToInlineData($url);
  1784. if ($inlineData) {
  1785. $parts[] = ['inline_data' => $inlineData];
  1786. }
  1787. }
  1788. }
  1789. } else {
  1790. $text = (string)$content;
  1791. if ($text !== '') {
  1792. $parts[] = ['text' => $text];
  1793. }
  1794. }
  1795. if (!empty($parts)) {
  1796. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1797. }
  1798. }
  1799. if (empty($contents)) {
  1800. Utils::throwError('20003:请提供有效的对话内容');
  1801. }
  1802. // 构建生成配置
  1803. $generationConfig = [];
  1804. if (getProp($data, 'temperature', null) !== null) {
  1805. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1806. }
  1807. if (getProp($data, 'top_p', null) !== null) {
  1808. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1809. }
  1810. if (getProp($data, 'frequency_penalty', null) !== null) {
  1811. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1812. }
  1813. if (getProp($data, 'presence_penalty', null) !== null) {
  1814. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1815. }
  1816. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1817. if ($maxOutputTokens <= 0) {
  1818. $maxOutputTokens = 8192;
  1819. }
  1820. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1821. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1822. $maxOutputTokens = 32768;
  1823. }
  1824. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1825. // response_format 映射:text -> text/plain,json -> application/json
  1826. $responseFormat = getProp($data, 'response_format', 'text');
  1827. if (is_array($responseFormat)) {
  1828. $responseFormat = getProp($responseFormat, 'type', 'text');
  1829. }
  1830. if (in_array($responseFormat, ['json', 'json_object'])) {
  1831. $generationConfig['responseMimeType'] = 'application/json';
  1832. } else {
  1833. $generationConfig['responseMimeType'] = 'text/plain';
  1834. }
  1835. $requestData = [
  1836. 'contents' => $contents,
  1837. 'generationConfig' => $generationConfig,
  1838. ];
  1839. if ($systemInstruction !== '') {
  1840. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1841. }
  1842. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1843. $thinkingMode = getProp($data, 'thinking', null);
  1844. if (is_array($thinkingMode)) {
  1845. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1846. }
  1847. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1848. if ($thinkingMode === null) {
  1849. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1850. }
  1851. if ($thinkingMode === 'enabled') {
  1852. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1853. if ($thinkingBudget <= 0) {
  1854. $thinkingBudget = 20;
  1855. }
  1856. $requestData['generationConfig']['thinkingConfig'] = [
  1857. 'thinkingBudget' => $thinkingBudget
  1858. ];
  1859. } elseif ($defaultThinking) {
  1860. // 该模型仅支持思考模式,传 0 会返回 400
  1861. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1862. } else {
  1863. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1864. }
  1865. return $requestData;
  1866. }
  1867. /**
  1868. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1869. *
  1870. * 模型名 -> env 变量名映射:
  1871. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1872. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1873. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1874. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1875. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1876. */
  1877. private function getGeminiApiKey($model) {
  1878. $map = [
  1879. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1880. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1881. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1882. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1883. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1884. ];
  1885. if (isset($map[$model])) {
  1886. $key = env($map[$model]);
  1887. if (!empty($key)) {
  1888. return $key;
  1889. }
  1890. }
  1891. return env('GEMINI_API_KEY', '');
  1892. }
  1893. /**
  1894. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1895. */
  1896. private function geminiChatOnly($requestData, $model) {
  1897. $apiKey = $this->getGeminiApiKey($model);
  1898. if (empty($apiKey)) {
  1899. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1900. }
  1901. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1902. if (isset($requestData['messages'])) {
  1903. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1904. }
  1905. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1906. . '/models/' . $model . ':generateContent';
  1907. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1908. $headers = [
  1909. 'Authorization' => 'Bearer ' . $apiKey,
  1910. 'Content-Type' => 'application/json'
  1911. ];
  1912. $maxRetries = $this->gptRetryTimes();
  1913. $interval = $this->gptRetryInterval();
  1914. $attempt = 0;
  1915. while (true) {
  1916. try {
  1917. $response = $client->post($url, [
  1918. 'json' => $requestData,
  1919. 'headers' => $headers
  1920. ]);
  1921. $responseArr = json_decode($response->getBody()->getContents(), true);
  1922. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1923. $fullContent = $this->extractGeminiContent($responseArr);
  1924. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1925. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1926. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1927. ? $responseArr['candidates'][0]['finishReason']
  1928. : '';
  1929. return [
  1930. 'fullContent' => $fullContent,
  1931. 'fullReasoningContent' => $fullReasoningContent,
  1932. 'usage' => $usage,
  1933. 'finish_reason' => $finishReason
  1934. ];
  1935. } catch (\Exception $e) {
  1936. $retryable = true;
  1937. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1938. $status = $e->getResponse()->getStatusCode();
  1939. $retryable = $status >= 500 || $status == 429;
  1940. }
  1941. if (!$retryable || $attempt >= $maxRetries) {
  1942. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1943. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1944. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1945. }
  1946. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1947. 'retry' => $attempt + 1,
  1948. 'max_retries' => $maxRetries,
  1949. 'error' => $e->getMessage()
  1950. ]);
  1951. sleep($interval);
  1952. $attempt++;
  1953. }
  1954. }
  1955. }
  1956. /**
  1957. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1958. */
  1959. private function geminiStreamResponse($requestData, $model) {
  1960. $apiKey = $this->getGeminiApiKey($model);
  1961. if (empty($apiKey)) {
  1962. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1963. }
  1964. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1965. if (isset($requestData['messages'])) {
  1966. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1967. }
  1968. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1969. . '/models/' . $model . ':generateContent?alt=sse';
  1970. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1971. $headers = [
  1972. 'Authorization' => 'Bearer ' . $apiKey,
  1973. 'Content-Type' => 'application/json'
  1974. ];
  1975. try {
  1976. $response = $client->post($url, [
  1977. 'json' => $requestData,
  1978. 'headers' => $headers,
  1979. 'stream' => true
  1980. ]);
  1981. $body = $response->getBody();
  1982. $fullContent = '';
  1983. $fullReasoningContent = '';
  1984. $usage = [];
  1985. $buffer = '';
  1986. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1987. while (!$body->eof()) {
  1988. $chunk = $body->read(1024);
  1989. $buffer .= $chunk;
  1990. $lines = explode("\n", $buffer);
  1991. $buffer = array_pop($lines);
  1992. foreach ($lines as $line) {
  1993. $line = trim($line);
  1994. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1995. continue;
  1996. }
  1997. $data = substr($line, 6);
  1998. if ($data === '[DONE]') {
  1999. break 2;
  2000. }
  2001. try {
  2002. $json = json_decode($data, true);
  2003. if (json_last_error() !== JSON_ERROR_NONE) {
  2004. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2005. continue;
  2006. }
  2007. // 思考内容(thoughts)
  2008. $thoughts = $this->extractGeminiThoughts($json);
  2009. if ($thoughts !== '') {
  2010. $fullReasoningContent .= $thoughts;
  2011. yield [
  2012. 'type' => 'reasoning',
  2013. 'content' => $thoughts,
  2014. 'full_reasoning' => $fullReasoningContent
  2015. ];
  2016. }
  2017. // 回答内容
  2018. $partText = $this->extractGeminiContent($json);
  2019. if ($partText !== '') {
  2020. $fullContent .= $partText;
  2021. yield [
  2022. 'type' => 'content',
  2023. 'content' => $partText,
  2024. ];
  2025. }
  2026. // 使用统计
  2027. if (isset($json['usageMetadata'])) {
  2028. $usage = $json['usageMetadata'];
  2029. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  2030. }
  2031. } catch (\Exception $e) {
  2032. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2033. continue;
  2034. }
  2035. }
  2036. }
  2037. dLog('deepseek')->info('Gemini流式读取完成', [
  2038. 'content_length' => strlen($fullContent),
  2039. 'reasoning_length' => strlen($fullReasoningContent)
  2040. ]);
  2041. yield [
  2042. 'type' => 'done',
  2043. 'full_content' => $fullContent,
  2044. 'full_reasoning' => $fullReasoningContent,
  2045. 'usage' => $usage
  2046. ];
  2047. } catch (\Exception $e) {
  2048. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  2049. yield [
  2050. 'type' => 'error',
  2051. 'msg' => $e->getMessage(),
  2052. 'code' => $e->getCode()
  2053. ];
  2054. }
  2055. }
  2056. /**
  2057. * 从 Gemini 响应中提取回答文本
  2058. */
  2059. private function extractGeminiContent($responseArr) {
  2060. $text = '';
  2061. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  2062. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  2063. if (isset($part['text'])) {
  2064. $text .= $part['text'];
  2065. }
  2066. }
  2067. }
  2068. return $text;
  2069. }
  2070. /**
  2071. * 从 Gemini 响应中提取思考内容
  2072. */
  2073. private function extractGeminiReasoningContent($responseArr) {
  2074. $reasoning = '';
  2075. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2076. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2077. if (isset($thought['text'])) {
  2078. $reasoning .= $thought['text'];
  2079. }
  2080. }
  2081. }
  2082. return $reasoning;
  2083. }
  2084. /**
  2085. * 从 Gemini 流式响应中提取本次增量思考内容
  2086. */
  2087. private function extractGeminiThoughts($responseArr) {
  2088. $thoughts = '';
  2089. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2090. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2091. if (isset($thought['text'])) {
  2092. $thoughts .= $thought['text'];
  2093. }
  2094. }
  2095. }
  2096. return $thoughts;
  2097. }
  2098. /**
  2099. * 提取消息数组中的纯文本
  2100. */
  2101. private function extractGeminiTextFromParts($parts) {
  2102. $text = '';
  2103. if (is_array($parts)) {
  2104. foreach ($parts as $part) {
  2105. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  2106. $text .= (string)getProp($part, 'text', '');
  2107. }
  2108. }
  2109. }
  2110. return $text;
  2111. }
  2112. /**
  2113. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  2114. *
  2115. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  2116. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  2117. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  2118. *
  2119. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  2120. * @return array|null ['mime_type' => string, 'data' => string]
  2121. */
  2122. private function processMediaToInlineData($media) {
  2123. if (empty($media)) {
  2124. return null;
  2125. }
  2126. $localPath = null;
  2127. $isTempFile = false;
  2128. try {
  2129. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  2130. if (is_string($media) && strpos($media, 'data:') === 0) {
  2131. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  2132. return [
  2133. 'mime_type' => $matches[1],
  2134. 'data' => $matches[2]
  2135. ];
  2136. }
  2137. return null;
  2138. }
  2139. // 2. 获取本地文件路径
  2140. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  2141. $localPath = $this->downloadMediaToTemp($media);
  2142. $isTempFile = true;
  2143. } elseif (is_string($media)) {
  2144. $localPath = $media;
  2145. } else {
  2146. // Laravel UploadedFile 对象
  2147. $localPath = $media->getRealPath();
  2148. }
  2149. if (!$localPath || !file_exists($localPath)) {
  2150. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  2151. return null;
  2152. }
  2153. $fileSize = filesize($localPath);
  2154. $maxBytes = $this->geminiMediaMaxBytes();
  2155. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  2156. $mimeType = $this->detectMediaMime($localPath);
  2157. $isVideo = strpos($mimeType, 'video/') === 0;
  2158. $needCompress = $fileSize > $maxBytes;
  2159. $duration = 0;
  2160. if ($isVideo) {
  2161. $duration = $this->getMediaDuration($localPath);
  2162. if ($duration > 300) {
  2163. $needCompress = true;
  2164. }
  2165. }
  2166. $finalPath = $localPath;
  2167. $compressedPath = null;
  2168. if ($needCompress && $this->ffmpegAvailable()) {
  2169. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  2170. if ($compressed && file_exists($compressed)) {
  2171. $compressedPath = $compressed;
  2172. if (filesize($compressed) < $fileSize || $isVideo) {
  2173. $finalPath = $compressed;
  2174. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  2175. } else {
  2176. @unlink($compressed);
  2177. $compressedPath = null;
  2178. }
  2179. }
  2180. }
  2181. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  2182. $finalSize = filesize($finalPath);
  2183. if ($finalSize > $maxBytes) {
  2184. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  2185. 'path' => $localPath,
  2186. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  2187. 'limit_mb' => 14
  2188. ]);
  2189. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  2190. }
  2191. // 兜底校验:视频时长超过5分钟且未能压缩成功
  2192. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  2193. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  2194. }
  2195. $data = base64_encode(file_get_contents($finalPath));
  2196. return [
  2197. 'mime_type' => $mimeType,
  2198. 'data' => $data
  2199. ];
  2200. } catch (\App\Exceptions\ApiException $e) {
  2201. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  2202. throw $e;
  2203. } catch (\Exception $e) {
  2204. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  2205. return null;
  2206. } finally {
  2207. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  2208. @unlink($compressedPath);
  2209. }
  2210. if ($isTempFile && $localPath && file_exists($localPath)) {
  2211. @unlink($localPath);
  2212. }
  2213. }
  2214. }
  2215. /**
  2216. * 下载远程多媒体到临时目录
  2217. *
  2218. * @return string|null 本地临时文件路径
  2219. */
  2220. private function downloadMediaToTemp($url) {
  2221. try {
  2222. $tempDir = storage_path('app/temp/gemini');
  2223. if (!is_dir($tempDir)) {
  2224. mkdir($tempDir, 0775, true);
  2225. }
  2226. $extension = 'tmp';
  2227. $pathInfo = parse_url($url, PHP_URL_PATH);
  2228. if ($pathInfo) {
  2229. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2230. if ($ext && strlen($ext) <= 10) {
  2231. $extension = strtolower($ext);
  2232. }
  2233. }
  2234. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2235. $client = new Client(['timeout' => 300, 'verify' => false]);
  2236. $response = $client->get($url, ['sink' => $tmpFile]);
  2237. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2238. @unlink($tmpFile);
  2239. return null;
  2240. }
  2241. return $tmpFile;
  2242. } catch (\Exception $e) {
  2243. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2244. return null;
  2245. }
  2246. }
  2247. /**
  2248. * 检测多媒体文件 MIME 类型
  2249. */
  2250. private function detectMediaMime($filePath) {
  2251. $imageInfo = @getimagesize($filePath);
  2252. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2253. return $imageInfo['mime'];
  2254. }
  2255. // 视频按扩展名粗略判断
  2256. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2257. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2258. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2259. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2260. if (isset($videoExts[$ext])) {
  2261. return $videoExts[$ext];
  2262. }
  2263. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2264. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2265. if (isset($imageExts[$ext])) {
  2266. return $imageExts[$ext];
  2267. }
  2268. return 'application/octet-stream';
  2269. }
  2270. /**
  2271. * 获取多媒体时长(秒),非视频或失败返回 0
  2272. */
  2273. private function getMediaDuration($filePath) {
  2274. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2275. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2276. $output = trim((string)shell_exec($cmd));
  2277. $duration = (float)$output;
  2278. return $duration > 0 ? $duration : 0;
  2279. }
  2280. /**
  2281. * 检查 ffmpeg 是否可用
  2282. */
  2283. private function ffmpegAvailable() {
  2284. static $available = null;
  2285. if ($available !== null) {
  2286. return $available;
  2287. }
  2288. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2289. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2290. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2291. $available = false;
  2292. return $available;
  2293. }
  2294. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2295. $output = shell_exec($cmd);
  2296. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2297. return $available;
  2298. }
  2299. /**
  2300. * 使用 ffmpeg 压缩多媒体文件
  2301. *
  2302. * @param string $inputFile 输入文件路径
  2303. * @param bool $isVideo 是否为视频
  2304. * @param float $duration 视频时长(秒),非视频传 0
  2305. * @return string|null 压缩后的文件路径,失败返回 null
  2306. */
  2307. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2308. try {
  2309. $tempDir = storage_path('app/temp/gemini');
  2310. if (!is_dir($tempDir)) {
  2311. mkdir($tempDir, 0775, true);
  2312. }
  2313. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2314. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2315. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2316. if ($isVideo) {
  2317. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2318. $speedFactor = 1.0;
  2319. if ($duration > 300) {
  2320. $speedFactor = $duration / 300;
  2321. }
  2322. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2323. $finalDuration = $duration / max(1.0, $speedFactor);
  2324. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2325. $targetBitrate = max(300, min(6000, $targetBitrate));
  2326. $filters = [];
  2327. $filters[] = 'scale=min(1280,iw):-2';
  2328. $filters[] = 'fps=24';
  2329. if ($speedFactor > 1.0) {
  2330. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2331. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2332. $fullCount = (int)ceil($speedFactor / 2.0);
  2333. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2334. if ($lastTempo < 0.5) {
  2335. $fullCount++;
  2336. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2337. }
  2338. for ($i = 0; $i < $fullCount; $i++) {
  2339. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2340. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2341. }
  2342. }
  2343. $filterStr = implode(',', $filters);
  2344. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2345. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2346. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2347. } else {
  2348. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2349. $imageInfo = @getimagesize($inputFile);
  2350. $scaleW = 2048;
  2351. $scaleH = 2048;
  2352. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2353. if ($imageInfo[0] >= $imageInfo[1]) {
  2354. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2355. $scaleW = 2048;
  2356. } else {
  2357. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2358. $scaleH = 2048;
  2359. }
  2360. }
  2361. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2362. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2363. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2364. }
  2365. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2366. $output = shell_exec($cmd);
  2367. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2368. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2369. 'input' => $inputFile,
  2370. 'output' => $output
  2371. ]);
  2372. @unlink($outputFile);
  2373. return null;
  2374. }
  2375. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2376. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2377. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2378. ]);
  2379. return $outputFile;
  2380. } catch (\Exception $e) {
  2381. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2382. return null;
  2383. }
  2384. }
  2385. /**
  2386. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2387. *
  2388. * @param array $data
  2389. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2390. */
  2391. public function getScriptGenerateTasks($data) {
  2392. $uid = Site::getUid();
  2393. return DB::table('mp_script_generate_tasks as t')
  2394. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2395. ->where('t.uid', $uid)
  2396. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2397. ->orderByDesc('t.id')
  2398. ->paginate(15);
  2399. }
  2400. public function saveScriptChatHistory($data) {
  2401. $uid = Site::getUid();
  2402. $rid = getProp($data, 'rid');
  2403. $script_id = getProp($data, 'script_id');
  2404. $sequence = getProp($data, 'sequence', 0);
  2405. $content = getProp($data, 'content');
  2406. if (!$rid) {
  2407. Utils::throwError('20003:请选择对话记录ID');
  2408. }
  2409. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2410. if (!$record) {
  2411. Utils::throwError('20003:对话记录不存在');
  2412. }
  2413. if (!$script_id) {
  2414. Utils::throwError('20003:请选择剧本');
  2415. }
  2416. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2417. if (!$script) {
  2418. Utils::throwError('20003:剧本不存在');
  2419. }
  2420. // 批量插入数据
  2421. return DB::table('mp_script_records')->where('id', $rid)->update([
  2422. 'content' => $content,
  2423. 'updated_at' => date('Y-m-d H:i:s')
  2424. ]);
  2425. }
  2426. /**
  2427. * 获取剧本的历史对话记录
  2428. *
  2429. * @param array $data 请求参数
  2430. * @return array 返回历史记录数组
  2431. */
  2432. public function getScriptChatHistory($data) {
  2433. $uid = Site::getUid();
  2434. $script_id = getProp($data, 'script_id');
  2435. $rid = getProp($data, 'rid');
  2436. $sequence = getProp($data, 'sequence', null);
  2437. if (!$script_id) {
  2438. Utils::throwError('20003:请提供剧本ID');
  2439. }
  2440. // 验证剧本是否存在
  2441. $script = DB::table('mp_scripts')
  2442. ->where('id', $script_id)
  2443. ->where('is_deleted', 0)
  2444. ->first();
  2445. if (!$script) {
  2446. Utils::throwError('20003:剧本不存在');
  2447. }
  2448. // 构建查询
  2449. $query = DB::table('mp_script_records')
  2450. ->where('script_id', $script_id);
  2451. // ->where('uid', $uid);
  2452. // 如果提供了 sequence,则过滤指定剧集
  2453. if ($sequence !== null) {
  2454. $query->where('sequence', $sequence);
  2455. }
  2456. // 记录ID筛选
  2457. if ($rid) {
  2458. $query->where('id', $rid);
  2459. }
  2460. // 查询记录并按 id 正序排序
  2461. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2462. ->orderBy('created_at', 'asc')
  2463. ->orderBy('id', 'asc')
  2464. ->get()
  2465. ->map(function ($record) {
  2466. return [
  2467. 'rid' => $record->id,
  2468. 'script_id' => $record->script_id,
  2469. 'sequence' => $record->sequence,
  2470. 'role' => $record->role,
  2471. 'content' => $record->content,
  2472. 'products' => $record->products ? json_decode($record->products) : [],
  2473. 'created_at' => $record->created_at,
  2474. ];
  2475. })
  2476. ->toArray();
  2477. return $records;
  2478. }
  2479. /**
  2480. * 处理图片转换为base64
  2481. *
  2482. * @param mixed $image 图片文件对象或文件路径
  2483. * @return string|null base64编码的图片数据
  2484. */
  2485. private function processImageToBase64($image) {
  2486. try {
  2487. // 获取文件路径
  2488. if (is_string($image)) {
  2489. $filePath = $image;
  2490. } else {
  2491. // Laravel UploadedFile 对象
  2492. $filePath = $image->getRealPath();
  2493. }
  2494. if (!file_exists($filePath)) {
  2495. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2496. return null;
  2497. }
  2498. // 验证是否为图片文件
  2499. $imageInfo = @getimagesize($filePath);
  2500. if ($imageInfo === false) {
  2501. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2502. return null;
  2503. }
  2504. // 读取图片并转换为base64
  2505. $imageData = file_get_contents($filePath);
  2506. $base64Image = base64_encode($imageData);
  2507. dLog('deepseek')->info('图片转换成功', [
  2508. 'size' => strlen($imageData),
  2509. 'type' => $imageInfo['mime']
  2510. ]);
  2511. return $base64Image;
  2512. } catch (\Exception $e) {
  2513. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2514. return null;
  2515. }
  2516. }
  2517. private function getArtStylePromptMappings($art_style='')
  2518. {
  2519. // 优先从画风表读取(入库后以表数据为准,保持原返回结构:['画风名' => ['aliases' => [...], 'prompt' => "..."]]
  2520. $dbRows = DB::table('mp_art_styles')
  2521. ->where('is_deleted', 0)
  2522. ->orderBy('id')
  2523. ->get(['art_style', 'aliases', 'prompt']);
  2524. if ($dbRows->isNotEmpty()) {
  2525. $arr = [];
  2526. foreach ($dbRows as $row) {
  2527. $arr[$row->art_style] = [
  2528. 'aliases' => is_string($row->aliases) ? json_decode($row->aliases, true) : [],
  2529. 'prompt' => (string)$row->prompt,
  2530. ];
  2531. }
  2532. if ($art_style) {
  2533. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2534. }
  2535. return $arr;
  2536. }
  2537. $arr = [
  2538. '唯美真人风格' => [
  2539. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2540. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2541. ],
  2542. '真人古风风格' => [
  2543. 'aliases' => ['真人古风风格', '真人古风'],
  2544. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2545. ],
  2546. '日系动漫风格' => [
  2547. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2548. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2549. ],
  2550. '国漫风格' => [
  2551. 'aliases' => ['国漫风格', '国漫'],
  2552. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2553. ],
  2554. 'Q版卡通风格' => [
  2555. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2556. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2557. ],
  2558. '简约扁平风格' => [
  2559. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2560. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2561. ],
  2562. '武侠风格' => [
  2563. 'aliases' => ['武侠风格', '武侠'],
  2564. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2565. ],
  2566. '古风仙侠风格' => [
  2567. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2568. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2569. ],
  2570. '新中式水墨风格' => [
  2571. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2572. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2573. ],
  2574. '写实插画风格' => [
  2575. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2576. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2577. ],
  2578. '3D卡通风格' => [
  2579. 'aliases' => ['3D卡通风格', '3D卡通'],
  2580. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2581. ],
  2582. '条漫风格' => [
  2583. 'aliases' => ['条漫风格', '条漫'],
  2584. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2585. ],
  2586. '赛博朋克风格' => [
  2587. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2588. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2589. ],
  2590. '暗黑悬疑风格' => [
  2591. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2592. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2593. ],
  2594. '治愈清新风格' => [
  2595. 'aliases' => ['治愈清新风格', '治愈清新'],
  2596. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2597. ],
  2598. '3D真人风格' => [
  2599. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2600. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2601. ],
  2602. ];
  2603. if($art_style) {
  2604. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2605. }
  2606. return $arr;
  2607. $arr = [
  2608. '唯美真人风格' => [
  2609. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2610. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2611. 2. 色彩色调
  2612. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2613. 3. 画质精度
  2614. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2615. 4. 画面观感
  2616. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2617. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2618. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2619. ],
  2620. '真人古风风格' => [
  2621. 'aliases' => ['真人古风风格', '真人古风'],
  2622. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2623. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2624. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2625. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2626. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2627. ],
  2628. '日系动漫风格' => [
  2629. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2630. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2631. 正向提示词(中文)
  2632. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2633. 必须遵守规则
  2634. • 全程保持日系动漫风格,不混入其他画风
  2635. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2636. • 画面适配所选画面比例,构图居中,主体突出
  2637. • 线条干净、色彩统一,不杂乱、不突兀
  2638. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2639. ],
  2640. '国漫风格' => [
  2641. 'aliases' => ['国漫风格', '国漫'],
  2642. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2643. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2644. 必须遵守规则
  2645. • 严格保持国漫画风,不串风格、不混画风
  2646. • 角色形象统一,不随意改变五官、身材、服饰
  2647. • 画面构图稳定,适合漫剧叙事展示
  2648. • 色调统一,不出现脏色、杂色
  2649. 禁止/避免词汇
  2650. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2651. ],
  2652. 'Q版卡通风格' => [
  2653. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2654. 'prompt' => "风格说明
  2655. 头大身小,造型可爱圆润,简约干净
  2656. 正向提示词(中文)
  2657. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2658. 必须遵守规则
  2659. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2660. • 角色造型统一,表情可爱,不诡异
  2661. • 画面简洁清爽,无多余复杂元素
  2662. • 色彩明亮柔和,不刺眼
  2663. 禁止/避免词汇
  2664. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2665. ],
  2666. '简约扁平风格' => [
  2667. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2668. 'prompt' => "风格说明
  2669. 色块简洁、无复杂渐变,现代极简风
  2670. 正向提示词(中文)
  2671. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2672. 必须遵守规则
  2673. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2674. • 构图简洁,主体突出,无多余装饰
  2675. • 色彩统一、干净,不杂乱
  2676. 禁止/避免词汇
  2677. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2678. ],
  2679. '武侠风格' => [
  2680. 'aliases' => ['武侠风格', '武侠'],
  2681. 'prompt' => "风格说明
  2682. 江湖气息,线条硬朗,动作感强
  2683. 正向提示词(中文)
  2684. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2685. 必须遵守规则
  2686. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2687. • 角色形象、服饰、身材比例统一
  2688. • 画面动作自然,不扭曲、不畸形
  2689. 禁止/避免词汇
  2690. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2691. ],
  2692. '古风仙侠风格' => [
  2693. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2694. 'prompt' => "风格说明
  2695. 飘逸汉服、云雾仙气、唯美空灵
  2696. 正向提示词(中文)
  2697. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2698. 必须遵守规则
  2699. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2700. • 角色服饰、发型、形象前后一致
  2701. • 场景仙气飘逸,色调清雅统一
  2702. • 画面唯美柔和,不阴暗、不诡异
  2703. 禁止/避免词汇
  2704. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2705. ],
  2706. '新中式水墨风格' => [
  2707. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2708. 'prompt' => "风格说明
  2709. 淡墨渲染,毛笔笔触,留白意境
  2710. 正向提示词(中文)
  2711. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2712. 必须遵守规则
  2713. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2714. • 色调淡雅统一,不浓艳杂乱
  2715. • 画面干净有意境,不堆砌元素
  2716. 禁止/避免词汇
  2717. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2718. ],
  2719. '写实插画风格' => [
  2720. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2721. 'prompt' => "风格说明
  2722. 接近真人比例,光影真实,质感细腻
  2723. 正向提示词(中文)
  2724. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2725. 必须遵守规则
  2726. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2727. • 角色五官、身材、服饰高度统一
  2728. • 画面清晰、光影自然、不扭曲
  2729. 禁止/避免词汇
  2730. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2731. ],
  2732. '3D卡通风格' => [
  2733. 'aliases' => ['3D卡通风格', '3D卡通'],
  2734. 'prompt' => "风格说明
  2735. 3D建模质感,柔和渲染,圆润可爱
  2736. 正向提示词(中文)
  2737. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2738. 必须遵守规则
  2739. • 保持3D卡通统一质感,不出现2D杂乱线条
  2740. • 角色模型、比例、形象前后一致
  2741. • 画面干净,不模糊、不穿模
  2742. 禁止/避免词汇
  2743. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2744. ],
  2745. '条漫风格' => [
  2746. 'aliases' => ['条漫风格', '条漫'],
  2747. 'prompt' => "风格说明
  2748. 纵向分镜,上下滑动阅读,轻量化
  2749. 正向提示词(中文)
  2750. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2751. 必须遵守规则
  2752. • 保持条漫纵向阅读逻辑,构图简洁
  2753. • 画风统一,不混写实、3D、水墨
  2754. • 画面干净,不杂乱
  2755. 禁止/避免词汇
  2756. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2757. ],
  2758. '赛博朋克风格' => [
  2759. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2760. 'prompt' => "风格说明
  2761. 霓虹灯光、未来都市、暗色调、科技机械
  2762. 正向提示词(中文)
  2763. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2764. 必须遵守规则
  2765. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2766. • 色调以暗调+霓虹为主,色彩统一
  2767. • 画面科技感强,不杂乱
  2768. 禁止/避免词汇
  2769. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2770. ],
  2771. '暗黑悬疑风格' => [
  2772. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2773. 'prompt' => "风格说明
  2774. 低饱和、冷色调、阴影重、神秘压抑
  2775. 正向提示词(中文)
  2776. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2777. 必须遵守规则
  2778. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2779. • 画面氛围压抑神秘,但不低俗、不血腥
  2780. • 角色形象统一,不崩坏
  2781. 禁止/避免词汇
  2782. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2783. ],
  2784. '治愈清新风格' => [
  2785. 'aliases' => ['治愈清新风格', '治愈清新'],
  2786. 'prompt' => "风格说明
  2787. 马卡龙色系、柔光、温暖干净
  2788. 正向提示词(中文)
  2789. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2790. 必须遵守规则
  2791. • 保持治愈清新统一色调,不阴暗、不诡异
  2792. • 画面柔和干净,无杂乱元素
  2793. • 角色形象柔和可爱,不狰狞
  2794. 禁止/避免词汇
  2795. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2796. ],
  2797. ];
  2798. return $arr;
  2799. }
  2800. public function getArtStylePromptByInput($inputArtStyle): string
  2801. {
  2802. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2803. if ($normalizedInput === '') {
  2804. return '';
  2805. }
  2806. // 按归一化画风名匹配(去除中英文空格等差异),表数据与内置映射通用
  2807. $mappings = $this->getArtStylePromptMappings();
  2808. if (!is_array($mappings)) {
  2809. return '';
  2810. }
  2811. foreach ($mappings as $artStyleName => $mapping) {
  2812. if ($this->normalizeArtStyleInput($artStyleName) === $normalizedInput) {
  2813. return (string)getProp($mapping, 'prompt', '');
  2814. }
  2815. }
  2816. return '';
  2817. }
  2818. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2819. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2820. if ($normalizedInput === '') {
  2821. return [];
  2822. }
  2823. // 优先从画风表读取(按归一化画风名匹配,停用画风保持可用);
  2824. // character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2825. $row = null;
  2826. $dbRows = DB::table('mp_art_styles')
  2827. ->where('is_deleted', 0)
  2828. ->get(['art_style', 'character_prefix', 'scene_prefix', 'prompt']);
  2829. foreach ($dbRows as $dbRow) {
  2830. if ($this->normalizeArtStyleInput($dbRow->art_style) === $normalizedInput) {
  2831. $row = $dbRow;
  2832. break;
  2833. }
  2834. }
  2835. if ($row) {
  2836. $prompt = (string)$row->prompt;
  2837. $result = [
  2838. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2839. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2840. ];
  2841. // 前缀与通用提示词均不存在时返回空数组
  2842. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2843. return [];
  2844. }
  2845. return $result;
  2846. }
  2847. $stylePrefixes = [
  2848. '唯美真人风格' => [
  2849. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2850. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2851. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2852. ],
  2853. '真人古风风格' => [
  2854. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2855. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2856. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2857. ],
  2858. '日系动漫风格' => [
  2859. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2860. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2861. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2862. ],
  2863. '国漫风格' => [
  2864. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2865. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2866. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2867. ],
  2868. 'Q版卡通风格' => [
  2869. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2870. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2871. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2872. ],
  2873. '简约扁平风格' => [
  2874. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2875. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2876. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2877. ],
  2878. '武侠风格' => [
  2879. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2880. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2881. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2882. ],
  2883. '古风仙侠风格' => [
  2884. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2885. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2886. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2887. ],
  2888. '新中式水墨风格' => [
  2889. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2890. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2891. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2892. ],
  2893. '写实插画风格' => [
  2894. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2895. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2896. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2897. ],
  2898. '3D卡通风格' => [
  2899. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2900. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2901. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2902. ],
  2903. '条漫风格' => [
  2904. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2905. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2906. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2907. ],
  2908. '赛博朋克风格' => [
  2909. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2910. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2911. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2912. ],
  2913. '暗黑悬疑风格' => [
  2914. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2915. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2916. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2917. ],
  2918. '治愈清新风格' => [
  2919. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2920. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2921. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2922. ]
  2923. ];
  2924. // 内置映射同样按归一化画风名匹配
  2925. foreach ($stylePrefixes as $artStyleName => $item) {
  2926. if ($this->normalizeArtStyleInput($artStyleName) !== $normalizedInput) {
  2927. continue;
  2928. }
  2929. $prompt = (string)($item['prompt'] ?? '');
  2930. // 前缀缺失时用通用 prompt 兜底
  2931. $result = [
  2932. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2933. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2934. ];
  2935. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2936. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2937. return [];
  2938. }
  2939. return $result;
  2940. }
  2941. return [];
  2942. }
  2943. private function normalizeArtStyleInput($value): string
  2944. {
  2945. $value = trim((string)$value);
  2946. if ($value === '') {
  2947. return '';
  2948. }
  2949. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2950. return mb_strtolower($value, 'UTF-8');
  2951. }
  2952. private function replaceArtStyleSection(string $content, string $artStyle): string
  2953. {
  2954. if ($content === '' || $artStyle === '') {
  2955. return $content;
  2956. }
  2957. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2958. if (!preg_match($pattern, $content)) {
  2959. return $content;
  2960. }
  2961. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2962. }
  2963. /**
  2964. * 解开模型偶发返回的 JSON 包装内容
  2965. *
  2966. * @param mixed $content 模型返回的原始内容
  2967. * @return mixed 解开后的内容(若无法解开则原样返回)
  2968. */
  2969. private function unwrapJsonWrappedContent($content) {
  2970. $trimmed = ltrim((string)$content);
  2971. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2972. return $content;
  2973. }
  2974. $decoded = json_decode($trimmed, true);
  2975. if (!is_array($decoded)) {
  2976. return $content;
  2977. }
  2978. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2979. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2980. return $decoded[$key];
  2981. }
  2982. }
  2983. return $content;
  2984. }
  2985. /**
  2986. * 流式文生文统一分发:根据模型路由到对应提供商的流式实现
  2987. *
  2988. * @param array $post_data 请求参数(含 model / messages / stream 等)
  2989. * @return \Generator
  2990. */
  2991. public function dispatchStreamByModel($post_data) {
  2992. // 强制按流式模式分发
  2993. $post_data['stream'] = true;
  2994. $model = (string)getProp($post_data, 'model', '');
  2995. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2996. // DeepSeek 官方模型
  2997. return $this->deepSeekStreamResponse($post_data);
  2998. } else if (in_array($model, $this->gpt_text_models)) {
  2999. // GPT 模型
  3000. return $this->gpt54StreamResponse($post_data);
  3001. } else if (in_array($model, $this->gemini_text_models)) {
  3002. // Gemini 模型
  3003. return $this->geminiStreamResponse($post_data, $model);
  3004. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3005. // 百度 AI 网关 GLM 模型
  3006. return $this->baiduGLMStreamResponse($post_data);
  3007. } else if (in_array($model, $this->valid_text_models)) {
  3008. // 火山引擎等其他模型
  3009. return $this->volcEngineChatCompletion($post_data);
  3010. }
  3011. Utils::throwError('20003:不支持的模型: ' . $model);
  3012. }
  3013. /**
  3014. * 非流式文生文统一分发:根据模型路由到对应提供商的非流式实现
  3015. *
  3016. * @param array $post_data 请求参数(含 model / messages / stream 等)
  3017. * @return array
  3018. */
  3019. public function dispatchChatOnlyByModel($post_data) {
  3020. // 强制按非流式模式分发
  3021. $post_data['stream'] = false;
  3022. $model = (string)getProp($post_data, 'model', '');
  3023. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3024. // DeepSeek 官方模型
  3025. return $this->chatOnly($post_data);
  3026. } else if (in_array($model, $this->gpt_text_models)) {
  3027. // GPT 模型
  3028. return $this->gpt54ChatOnly($post_data);
  3029. } else if (in_array($model, $this->gemini_text_models)) {
  3030. // Gemini 模型
  3031. return $this->geminiChatOnly($post_data, $model);
  3032. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3033. // 百度 AI 网关 GLM 模型
  3034. return $this->baiduGLMChatOnly($post_data);
  3035. } else if (in_array($model, $this->valid_text_models)) {
  3036. // 火山引擎等其他模型
  3037. return $this->volcEngineChatCompletion($post_data);
  3038. }
  3039. Utils::throwError('20003:不支持的模型: ' . $model);
  3040. }
  3041. /**
  3042. * 百度 AI 网关 GLM 流式实现(OpenAI Chat Completions 协议)
  3043. *
  3044. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3045. * @return \Generator
  3046. */
  3047. private function baiduGLMStreamResponse($post_data) {
  3048. $payload = $this->buildBaiduGLMPayload($post_data, true);
  3049. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3050. try {
  3051. $response = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3052. 'json' => $payload,
  3053. 'headers' => $this->baiduGLMHeaders(),
  3054. 'stream' => true,
  3055. ]);
  3056. } catch (\Exception $e) {
  3057. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3058. dLog('deepseek')->error('百度GLM流式请求建立失败: ' . $e->getMessage(), [
  3059. 'payload' => $payload,
  3060. 'detail' => $errorDetail,
  3061. ]);
  3062. Utils::throwError('20003:百度GLM流式请求失败: ' . $errorDetail);
  3063. }
  3064. $body = $response->getBody();
  3065. $buffer = '';
  3066. $fullContent = '';
  3067. $fullReasoning = '';
  3068. $usage = [];
  3069. dLog('deepseek')->info('开始读取百度GLM流式响应');
  3070. try {
  3071. while (!$body->eof()) {
  3072. $chunk = $body->read(1024);
  3073. $buffer .= $chunk;
  3074. $lines = explode("\n", $buffer);
  3075. $buffer = array_pop($lines);
  3076. foreach ($lines as $line) {
  3077. $line = trim($line);
  3078. if (empty($line)) {
  3079. continue;
  3080. }
  3081. if (strpos($line, 'data: ') !== 0) {
  3082. dLog('deepseek')->warning('百度GLM非SSE数据行', ['line' => $line]);
  3083. continue;
  3084. }
  3085. $data = substr($line, 6);
  3086. if ($data === '[DONE]') {
  3087. dLog('deepseek')->info('百度GLM收到结束标记');
  3088. break 2;
  3089. }
  3090. try {
  3091. $json = json_decode($data, true);
  3092. if (json_last_error() !== JSON_ERROR_NONE) {
  3093. dLog('deepseek')->warning('百度GLM JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3094. continue;
  3095. }
  3096. if (isset($json['choices'][0]['delta'])) {
  3097. $delta = $json['choices'][0]['delta'];
  3098. // 思考链内容(兼容 reasoning_content / reasoning 两种字段)
  3099. $reasoningDelta = '';
  3100. if (isset($delta['reasoning_content']) && is_string($delta['reasoning_content'])) {
  3101. $reasoningDelta = $delta['reasoning_content'];
  3102. } elseif (isset($delta['reasoning']) && is_string($delta['reasoning'])) {
  3103. $reasoningDelta = $delta['reasoning'];
  3104. }
  3105. if ($reasoningDelta !== '') {
  3106. $fullReasoning .= $reasoningDelta;
  3107. yield [
  3108. 'type' => 'reasoning',
  3109. 'content' => $reasoningDelta,
  3110. 'full_reasoning' => $fullReasoning,
  3111. ];
  3112. }
  3113. // 正文内容
  3114. if (isset($delta['content']) && is_string($delta['content'])) {
  3115. $fullContent .= $delta['content'];
  3116. yield [
  3117. 'type' => 'content',
  3118. 'content' => $delta['content'],
  3119. ];
  3120. }
  3121. }
  3122. if (isset($json['usage'])) {
  3123. $usage = $json['usage'];
  3124. }
  3125. } catch (\Exception $e) {
  3126. dLog('deepseek')->error('百度GLM解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3127. continue;
  3128. }
  3129. }
  3130. }
  3131. } catch (\Exception $e) {
  3132. dLog('deepseek')->error('百度GLM流式读取中断: ' . $e->getMessage());
  3133. throw $e;
  3134. }
  3135. dLog('deepseek')->info('百度GLM流式读取完成', [
  3136. 'content_length' => strlen($fullContent),
  3137. 'reasoning_length' => strlen($fullReasoning),
  3138. ]);
  3139. yield [
  3140. 'type' => 'done',
  3141. 'full_content' => $fullContent,
  3142. 'full_reasoning' => $fullReasoning,
  3143. 'usage' => $usage,
  3144. ];
  3145. }
  3146. /**
  3147. * 百度 AI 网关 GLM 非流式实现(OpenAI Chat Completions 协议)
  3148. *
  3149. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3150. * @return array
  3151. */
  3152. private function baiduGLMChatOnly($post_data) {
  3153. $payload = $this->buildBaiduGLMPayload($post_data, false);
  3154. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3155. try {
  3156. $result = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3157. 'json' => $payload,
  3158. 'headers' => $this->baiduGLMHeaders(),
  3159. ]);
  3160. $response_arr = json_decode($result->getBody()->getContents(), true);
  3161. dLog('deepseek')->info('百度GLM非流式请求完成', ['response' => $response_arr]);
  3162. $fullContent = '';
  3163. $fullReasoningContent = '';
  3164. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  3165. if (isset($response_arr['choices'][0]['message'])) {
  3166. $message = $response_arr['choices'][0]['message'];
  3167. if (isset($message['content']) && is_string($message['content'])) {
  3168. $fullContent = $message['content'];
  3169. }
  3170. if (isset($message['reasoning_content']) && is_string($message['reasoning_content'])) {
  3171. $fullReasoningContent = $message['reasoning_content'];
  3172. } elseif (isset($message['reasoning']) && is_string($message['reasoning'])) {
  3173. $fullReasoningContent = $message['reasoning'];
  3174. }
  3175. }
  3176. return [
  3177. 'fullContent' => $fullContent,
  3178. 'fullReasoningContent' => $fullReasoningContent,
  3179. 'usage' => $usage,
  3180. ];
  3181. } catch (\Exception $e) {
  3182. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3183. dLog('deepseek')->error('百度GLM非流式请求失败: ' . $e->getMessage(), [
  3184. 'payload' => $payload,
  3185. 'detail' => $errorDetail,
  3186. ]);
  3187. Utils::throwError('20003:百度GLM请求失败: ' . $errorDetail);
  3188. }
  3189. }
  3190. /**
  3191. * 组装百度 AI 网关 GLM 请求参数
  3192. *
  3193. * @param array $data 请求参数
  3194. * @param bool $stream 是否流式
  3195. * @return array
  3196. */
  3197. private function buildBaiduGLMPayload(array $data, bool $stream): array
  3198. {
  3199. if (empty(env('BAIDU_GLM_AK'))) {
  3200. Utils::throwError('20003:百度GLM API Key未配置,请检查环境变量BAIDU_GLM_AK');
  3201. }
  3202. $frontModel = (string)getProp($data, 'model', '');
  3203. $externalModel = isset(BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel])
  3204. ? BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel]
  3205. : '';
  3206. if ($externalModel === '') {
  3207. Utils::throwError('20003:不支持的百度GLM模型: ' . $frontModel);
  3208. }
  3209. $messages = getProp($data, 'messages', []);
  3210. if (empty($messages)) {
  3211. Utils::throwError('20003:请提供有效的对话内容');
  3212. }
  3213. // OpenAI Chat Completions 标准参数白名单。
  3214. // 注意:thinking 不在白名单中,由下方按模型单独控制
  3215. // (glm-5.2 支持关闭思考,glm-5.3 强制思考、不接受 thinking 参数)。
  3216. $allowedKeys = [
  3217. 'temperature',
  3218. 'top_p',
  3219. 'max_tokens',
  3220. 'max_completion_tokens',
  3221. 'reasoning_effort',
  3222. 'frequency_penalty',
  3223. 'presence_penalty',
  3224. 'stop',
  3225. 'response_format',
  3226. 'stream_options',
  3227. 'tools',
  3228. 'tool_choice',
  3229. 'user',
  3230. 'seed',
  3231. ];
  3232. $payload = [
  3233. 'model' => $externalModel,
  3234. 'messages' => $messages,
  3235. 'stream' => $stream,
  3236. ];
  3237. foreach ($allowedKeys as $key) {
  3238. if (array_key_exists($key, $data) && $data[$key] !== null && $data[$key] !== '') {
  3239. $payload[$key] = $data[$key];
  3240. }
  3241. }
  3242. // ================= 思考模式策略(仅百度 GLM)=================
  3243. // 规则:调用方传了的参数以其为准,未传则按模型默认策略补齐。
  3244. // glm-5.2:支持关闭思考,默认关闭(thinking.disabled),可显著缩短响应时间
  3245. // glm-5.3:强制思考,网关不接受 thinking 参数(传 disabled 会返回 400),
  3246. // 因此统一不下发 thinking,只下发 reasoning_effort,默认 low
  3247. $validEfforts = ['low', 'high', 'max'];
  3248. // 调用方传入的 thinking(兼容 'enabled' 字符串与 ['type' => 'enabled'] 数组两种写法)
  3249. $inputThinking = null;
  3250. if (array_key_exists('thinking', $data)) {
  3251. $rawThinking = $data['thinking'];
  3252. if (is_array($rawThinking)) {
  3253. $rawThinking = getProp($rawThinking, 'type', null);
  3254. }
  3255. if (in_array($rawThinking, ['enabled', 'disabled'], true)) {
  3256. $inputThinking = $rawThinking;
  3257. }
  3258. }
  3259. // 调用方传入的思考强度;百度网关只接受 low / high / max,其它取值(如 none)视为未传
  3260. $inputEffort = null;
  3261. if (isset($payload['reasoning_effort']) && in_array($payload['reasoning_effort'], $validEfforts, true)) {
  3262. $inputEffort = $payload['reasoning_effort'];
  3263. }
  3264. unset($payload['reasoning_effort']);
  3265. if ($externalModel === 'glm-5.3') {
  3266. // glm-5.3 始终思考:即使传入 disabled(或未传)也强制走 reasoning_effort
  3267. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3268. } else {
  3269. // glm-5.2 支持关闭思考:未显式开启思考时默认关闭
  3270. $thinkingType = ($inputThinking === 'enabled') ? 'enabled' : 'disabled';
  3271. $payload['thinking'] = ['type' => $thinkingType];
  3272. if ($thinkingType === 'enabled') {
  3273. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3274. }
  3275. }
  3276. if ($stream && !isset($payload['stream_options'])) {
  3277. $payload['stream_options'] = ['include_usage' => true];
  3278. }
  3279. if (!isset($payload['max_tokens']) && !isset($payload['max_completion_tokens'])) {
  3280. // GLM-5.x 输出上限较高,给长文生成留足空间
  3281. $payload['max_tokens'] = 100000;
  3282. }
  3283. return $payload;
  3284. }
  3285. /**
  3286. * 百度 AI 网关 GLM 鉴权请求头
  3287. *
  3288. * @return array
  3289. */
  3290. private function baiduGLMHeaders(): array
  3291. {
  3292. return [
  3293. 'Authorization' => 'Bearer ' . env('BAIDU_GLM_AK'),
  3294. 'Content-Type' => 'application/json; charset=UTF-8',
  3295. 'Accept' => 'text/event-stream',
  3296. ];
  3297. }
  3298. /**
  3299. * 从 Guzzle 异常响应体中提取百度 AI 网关返回的错误信息
  3300. *
  3301. * @param \Exception $e
  3302. * @return string
  3303. */
  3304. private function extractBaiduGLMErrorDetail(\Exception $e): string
  3305. {
  3306. $detail = $e->getMessage();
  3307. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3308. try {
  3309. $responseBody = (string)$e->getResponse()->getBody();
  3310. $decoded = json_decode($responseBody, true);
  3311. if (is_array($decoded)) {
  3312. if (isset($decoded['error']['message']) && $decoded['error']['message'] !== '') {
  3313. $detail = $decoded['error']['message'];
  3314. } elseif (isset($decoded['message']) && $decoded['message'] !== '') {
  3315. $detail = $decoded['message'];
  3316. } elseif (isset($decoded['error']) && is_string($decoded['error'])) {
  3317. $detail = $decoded['error'];
  3318. }
  3319. } elseif ($responseBody !== '') {
  3320. $detail = $responseBody;
  3321. }
  3322. } catch (\Throwable $parseError) {
  3323. // 保留原始异常信息
  3324. }
  3325. }
  3326. return mb_substr($detail, 0, 500);
  3327. }
  3328. private function deepSeekStreamResponse($post_data) {
  3329. // 设置最大输出tokens
  3330. $post_data['max_tokens'] = 300000;
  3331. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3332. $post_data['stream_options'] = ['include_usage' => true];
  3333. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3334. $response = $client->post($this->url, [
  3335. 'json' => $post_data,
  3336. 'headers' => $this->headers,
  3337. 'stream' => true // 启用流式响应
  3338. ]);
  3339. $body = $response->getBody();
  3340. $fullContent = '';
  3341. $fullReasoningContent = '';
  3342. $usage = [];
  3343. $buffer = '';
  3344. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  3345. // 逐行读取流式响应
  3346. while (!$body->eof()) {
  3347. $chunk = $body->read(1024); // 每次读取 1KB
  3348. $buffer .= $chunk;
  3349. // 按行分割
  3350. $lines = explode("\n", $buffer);
  3351. // 保留最后一个不完整的行
  3352. $buffer = array_pop($lines);
  3353. foreach ($lines as $line) {
  3354. $line = trim($line);
  3355. // 跳过空行
  3356. if (empty($line)) {
  3357. continue;
  3358. }
  3359. // 检查是否是 SSE 数据行
  3360. if (strpos($line, 'data: ') !== 0) {
  3361. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3362. continue;
  3363. }
  3364. $data = substr($line, 6); // 移除 "data: " 前缀
  3365. if ($data === '[DONE]') {
  3366. dLog('deepseek')->info('收到结束标记');
  3367. break 2; // 跳出两层循环
  3368. }
  3369. try {
  3370. $json = json_decode($data, true);
  3371. if (json_last_error() !== JSON_ERROR_NONE) {
  3372. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3373. continue;
  3374. }
  3375. if (isset($json['choices'][0]['delta'])) {
  3376. $delta = $json['choices'][0]['delta'];
  3377. // 处理思维链内容(仅 deepseek-reasoner 模型)
  3378. if (isset($delta['reasoning_content'])) {
  3379. $fullReasoningContent .= $delta['reasoning_content'];
  3380. yield [
  3381. 'type' => 'reasoning',
  3382. 'content' => $delta['reasoning_content'],
  3383. 'full_reasoning' => $fullReasoningContent
  3384. ];
  3385. }
  3386. // 处理最终回答内容
  3387. if (isset($delta['content'])) {
  3388. $fullContent .= $delta['content'];
  3389. yield [
  3390. 'type' => 'content',
  3391. 'content' => $delta['content'],
  3392. ];
  3393. }
  3394. }
  3395. // 获取使用统计信息
  3396. if (isset($json['usage'])) {
  3397. $usage = $json['usage'];
  3398. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3399. }
  3400. } catch (\Exception $e) {
  3401. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3402. continue;
  3403. }
  3404. }
  3405. }
  3406. dLog('deepseek')->info('流式读取完成', [
  3407. 'content_length' => strlen($fullContent),
  3408. 'reasoning_length' => strlen($fullReasoningContent)
  3409. ]);
  3410. yield [
  3411. 'type' => 'done',
  3412. 'full_content' => $fullContent,
  3413. 'full_reasoning' => $fullReasoningContent,
  3414. 'usage' => $usage
  3415. ];
  3416. }
  3417. /**
  3418. * GPT 重试次数(env 可配置,默认 5 次)
  3419. */
  3420. private function gptRetryTimes()
  3421. {
  3422. return (int)env('GPT_RETRY_TIMES', 5);
  3423. }
  3424. /**
  3425. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  3426. */
  3427. private function gptRetryInterval()
  3428. {
  3429. return (int)env('GPT_RETRY_INTERVAL', 10);
  3430. }
  3431. /**
  3432. * 判断 GPT 请求异常是否可重试
  3433. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  3434. */
  3435. private function isGptRetryableException(\Exception $e)
  3436. {
  3437. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  3438. return false;
  3439. }
  3440. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3441. $status = $e->getResponse()->getStatusCode();
  3442. return $status >= 500 || $status == 429;
  3443. }
  3444. return true;
  3445. }
  3446. /**
  3447. * GPT 中转站探活:GET /v1/models,5 秒短超时
  3448. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  3449. */
  3450. private function checkGptServiceAvailable($apiKey = null)
  3451. {
  3452. if ($apiKey === null) {
  3453. $apiKey = env('GPT_54_API_KEY');
  3454. }
  3455. if (empty($apiKey)) {
  3456. return false;
  3457. }
  3458. try {
  3459. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  3460. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  3461. 'headers' => [
  3462. 'Authorization' => 'Bearer ' . $apiKey,
  3463. 'Content-Type' => 'application/json'
  3464. ]
  3465. ]);
  3466. $status = $response->getStatusCode();
  3467. return $status < 500 && $status != 429;
  3468. } catch (\Exception $e) {
  3469. return false;
  3470. }
  3471. }
  3472. /**
  3473. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  3474. * 全部失败抛出友好错误
  3475. */
  3476. private function ensureGptServiceAvailable($apiKey = null)
  3477. {
  3478. $maxRetries = $this->gptRetryTimes();
  3479. $interval = $this->gptRetryInterval();
  3480. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  3481. if ($this->checkGptServiceAvailable($apiKey)) {
  3482. return;
  3483. }
  3484. if ($attempt < $maxRetries) {
  3485. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  3486. 'retry' => $attempt + 1,
  3487. 'max_retries' => $maxRetries
  3488. ]);
  3489. sleep($interval);
  3490. }
  3491. }
  3492. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  3493. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  3494. 'max_retries' => $maxRetries,
  3495. 'interval' => $interval
  3496. ]);
  3497. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  3498. }
  3499. /**
  3500. * GPT 流式输出处理方法
  3501. *
  3502. * @param array $post_data GPT API请求参数
  3503. * @return \Generator 返回生成器,用于流式输出
  3504. */
  3505. private function gpt54StreamResponse($post_data) {
  3506. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  3507. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  3508. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  3509. if ($modelName === 'gpt-5.4') {
  3510. $modelName = 'gpt-5.6-terra';
  3511. $post_data['model'] = $modelName;
  3512. }
  3513. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  3514. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  3515. $usedLunaFallback = false;
  3516. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  3517. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  3518. if (empty($apiKey)) {
  3519. Utils::throwError('20003:GPT API Key未配置');
  3520. }
  3521. // 先探活,服务不可用时自动重试
  3522. $this->ensureGptServiceAvailable($apiKey);
  3523. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  3524. // 移除 thinking 参数,GPT-5.4 不支持
  3525. if (isset($post_data['thinking'])) {
  3526. unset($post_data['thinking']);
  3527. }
  3528. if (isset($post_data['reasoning_effort'])) {
  3529. unset($post_data['reasoning_effort']);
  3530. }
  3531. // GPT-5.x(推理型上游)只接受默认 temperature(1),传入其他值会返回 400:
  3532. // Unsupported value: 'temperature' does not support 1.35 with this model.
  3533. // Only the default (1) value is supported.
  3534. unset($post_data['temperature']);
  3535. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  3536. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  3537. $post_data['max_completion_tokens'] = 100000;
  3538. // GPT-5.x 上游仅支持 max_completion_tokens,同时携带 max_tokens 会返回 400:
  3539. // Unsupported parameter: 'max_tokens' is not supported with this model.
  3540. // 这里显式移除,防止调用方在 post_data 中残留 max_tokens。
  3541. unset($post_data['max_tokens']);
  3542. // GPT-5.x(推理型上游)不接受 frequency_penalty / presence_penalty:
  3543. // Unsupported parameter: 'frequency_penalty' is not supported with this model.
  3544. // 调用方默认传 0,移除后采样行为不变,显式清理避免 400。
  3545. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  3546. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3547. $post_data['stream_options'] = ['include_usage' => true];
  3548. $maxRetries = $this->gptRetryTimes();
  3549. $interval = $this->gptRetryInterval();
  3550. $attempt = 0;
  3551. while (true) {
  3552. $fullContent = '';
  3553. $usage = [];
  3554. $buffer = '';
  3555. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  3556. $isJsonRequest = isset($post_data['response_format'])
  3557. && is_array($post_data['response_format'])
  3558. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  3559. $suspectJsonWrap = false;
  3560. $pendingContent = '';
  3561. $requestStartedAt = microtime(true);
  3562. $headers = [
  3563. 'Authorization' => 'Bearer ' . $apiKey,
  3564. 'Content-Type' => 'application/json',
  3565. 'Accept' => 'text/event-stream'
  3566. ];
  3567. try {
  3568. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  3569. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  3570. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  3571. 'json' => $post_data,
  3572. 'headers' => $headers,
  3573. 'stream' => true // 启用流式响应
  3574. ]);
  3575. $body = $response->getBody();
  3576. dLog('deepseek')->info('开始读取 GPT 流式响应');
  3577. // 逐行读取流式响应
  3578. while (!$body->eof()) {
  3579. // 长时间没有任何内容返回时,切换备用 Key 重试
  3580. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3581. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3582. }
  3583. $chunk = $body->read(1024); // 每次读取 1KB
  3584. $buffer .= $chunk;
  3585. // 按行分割
  3586. $lines = explode("\n", $buffer);
  3587. // 保留最后一个不完整的行
  3588. $buffer = array_pop($lines);
  3589. foreach ($lines as $line) {
  3590. $line = trim($line);
  3591. // 跳过空行
  3592. if (empty($line)) {
  3593. continue;
  3594. }
  3595. // 检查是否是 SSE 数据行
  3596. if (strpos($line, 'data: ') !== 0) {
  3597. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3598. continue;
  3599. }
  3600. $data = substr($line, 6); // 移除 "data: " 前缀
  3601. if ($data === '[DONE]') {
  3602. dLog('deepseek')->info('收到结束标记');
  3603. break 2; // 跳出 foreach 和流读取循环
  3604. }
  3605. try {
  3606. $json = json_decode($data, true);
  3607. if (json_last_error() !== JSON_ERROR_NONE) {
  3608. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3609. continue;
  3610. }
  3611. if (isset($json['choices'][0]['delta'])) {
  3612. $delta = $json['choices'][0]['delta'];
  3613. // 处理回答内容
  3614. if (isset($delta['content'])) {
  3615. $fullContent .= $delta['content'];
  3616. $trimmed = ltrim($fullContent);
  3617. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3618. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3619. $suspectJsonWrap = true;
  3620. }
  3621. if (!$suspectJsonWrap) {
  3622. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3623. $chunkSize = 256;
  3624. $chunkLength = mb_strlen($delta['content']);
  3625. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3626. yield [
  3627. 'type' => 'content',
  3628. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3629. ];
  3630. }
  3631. } else {
  3632. $pendingContent .= $delta['content'];
  3633. }
  3634. }
  3635. }
  3636. // 获取使用统计信息
  3637. if (isset($json['usage'])) {
  3638. $usage = $json['usage'];
  3639. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3640. }
  3641. } catch (\Exception $e) {
  3642. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3643. continue;
  3644. }
  3645. }
  3646. }
  3647. dLog('deepseek')->info('流式读取完成', [
  3648. 'content_length' => strlen($fullContent)
  3649. ]);
  3650. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3651. if ($suspectJsonWrap) {
  3652. $decoded = json_decode(trim($fullContent), true);
  3653. $unwrapped = null;
  3654. if (is_array($decoded)) {
  3655. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3656. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3657. $unwrapped = $decoded[$key];
  3658. break;
  3659. }
  3660. }
  3661. }
  3662. if ($unwrapped !== null) {
  3663. $fullContent = $unwrapped;
  3664. $chunkSize = 256;
  3665. $contentLength = mb_strlen($fullContent);
  3666. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3667. yield [
  3668. 'type' => 'content',
  3669. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3670. ];
  3671. }
  3672. } elseif ($pendingContent !== '') {
  3673. // 误判:补发暂缓内容,避免内容丢失
  3674. yield [
  3675. 'type' => 'content',
  3676. 'content' => $pendingContent,
  3677. ];
  3678. }
  3679. }
  3680. yield [
  3681. 'type' => 'done',
  3682. 'full_content' => $fullContent,
  3683. 'full_reasoning' => '',
  3684. 'usage' => $usage
  3685. ];
  3686. return;
  3687. } catch (\Exception $e) {
  3688. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3689. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3690. $usedLunaFallback = true;
  3691. $apiKey = $lunaApiKey;
  3692. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3693. continue;
  3694. }
  3695. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3696. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3697. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3698. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3699. throw $e;
  3700. }
  3701. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3702. 'retry' => $attempt + 1,
  3703. 'max_retries' => $maxRetries,
  3704. 'error' => $e->getMessage()
  3705. ]);
  3706. sleep($interval);
  3707. $attempt++;
  3708. }
  3709. }
  3710. }
  3711. // 与推理模型对话
  3712. public function chatWithReasoner($data) {
  3713. // 文生文计费预检(normal 档)
  3714. $uid = Site::getUid();
  3715. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  3716. $content = getProp($data, 'content');
  3717. $model = getProp($data, 'model', 'r1');
  3718. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3719. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3720. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3721. if ($model == 'r1') {
  3722. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3723. $thinkingMode = 'disabled';
  3724. } else {
  3725. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3726. $thinkingMode = 'disabled';
  3727. }
  3728. // 获取可选情感(根据音色可支持情感选)
  3729. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3730. $emotion_list = [];
  3731. foreach ($timbre_emotion as $emotion) {
  3732. $tmp = explode(',', $emotion);
  3733. $emotion_list = array_merge($emotion_list, $tmp);
  3734. }
  3735. $emotion_list = array_unique($emotion_list);
  3736. $emotion_str = implode('、', $emotion_list);
  3737. // // 获取可选情感
  3738. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3739. // $emotion_str = implode('、', $emotion_list);
  3740. // 是否启用情感
  3741. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3742. if ($enable_emotion) {
  3743. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3744. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3745. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3746. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3747. }else {
  3748. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3749. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3750. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3751. }
  3752. $messages = [
  3753. [
  3754. 'role' => 'system',
  3755. 'content' => $sys_content
  3756. ],
  3757. [
  3758. 'role' => 'user',
  3759. 'content' => $content
  3760. ]
  3761. ];
  3762. $post_data = [
  3763. 'model' => $model,
  3764. 'messages' => $messages,
  3765. // 'max_tokens' => 8192,
  3766. 'temperature' => 1,
  3767. 'frequency_penalty' => 0,
  3768. 'presence_penalty' => 0,
  3769. 'thinking' => ['type' => $thinkingMode],
  3770. 'response_format' => [
  3771. 'type' => 'text'
  3772. ],
  3773. 'stream' => false
  3774. ];
  3775. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3776. // 根据模型类型选择调用方法
  3777. $fullContent = '';
  3778. $usage = [];
  3779. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  3780. if (is_array($chatResult)) {
  3781. $fullContent = $chatResult['fullContent'];
  3782. $usage = $chatResult['usage'];
  3783. }
  3784. // 处理获取到的剧本数据
  3785. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3786. $result = [
  3787. 'origin_content' => $fullContent,
  3788. 'roles' => getProp($script_content, 'roles'),
  3789. 'words' => getProp($script_content, 'words'),
  3790. ];
  3791. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  3792. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3793. 'model' => $model,
  3794. 'source' => 'chatWithReasoner',
  3795. ], 'normal');
  3796. return $result;
  3797. }
  3798. public function resetParagraphAudio($data) {
  3799. $bid = getProp($data, 'bid');
  3800. $cid = getProp($data, 'cid');
  3801. $version_id = getProp($data, 'version_id');
  3802. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3803. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3804. 'generate_status' => '待制作',
  3805. 'updated_at' => date('Y-m-d H:i:s')
  3806. ]);
  3807. }
  3808. public function saveParagraphAudio($data) {
  3809. $bid = getProp($data, 'bid');
  3810. $cid = getProp($data, 'cid');
  3811. $version_id = getProp($data, 'version_id');
  3812. $sequence = getProp($data, 'sequence');
  3813. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3814. // 获取所有情感
  3815. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3816. $emotion_list = array_flip($emotion_list);
  3817. // 获取音色支持情感
  3818. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3819. $timbre_emotion = explode(',', $timbre_emotion);
  3820. $emotion = getProp($data, 'emotion');
  3821. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3822. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3823. $list = [
  3824. 'bid' => $bid,
  3825. 'cid' => $cid,
  3826. 'version_id' => $version_id,
  3827. 'sequence' => $sequence,
  3828. 'role' => getProp($data, 'role'),
  3829. 'gender' => getProp($data, 'gender'),
  3830. 'text' => trim(getProp($data, 'text')),
  3831. 'emotion' => $emotion,
  3832. 'emotion_type' => $emotion_type,
  3833. 'voice_type' => getProp($data, 'voice_type'),
  3834. 'voice_name' => getProp($data, 'voice_name'),
  3835. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3836. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3837. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3838. 'pitch' => getProp($data, 'pitch', 0),
  3839. // 'paragraph_audio_url' => '',
  3840. 'generate_status' => '制作中',
  3841. 'error_msg' => '',
  3842. 'updated_at' => date('Y-m-d H:i:s')
  3843. ];
  3844. $continue = false;
  3845. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3846. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3847. $list['generate_status'] = '制作成功';
  3848. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3849. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3850. $continue = true;
  3851. }
  3852. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3853. if ($id) {
  3854. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3855. }else {
  3856. $list['created_at'] = date('Y-m-d H:i:s');
  3857. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3858. $boolen = $id ? true : false;
  3859. }
  3860. // 如果更新成功则加入查询队列
  3861. if ($boolen) {
  3862. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3863. Redis::sadd($redis_key, $id);
  3864. }
  3865. if ($boolen && !$continue) {
  3866. $boolen = false;
  3867. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3868. // 根据ID通过API通知合成音频
  3869. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3870. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3871. $response = $result->getBody()->getContents();
  3872. $response_arr = json_decode($response, true);
  3873. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3874. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3875. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3876. Utils::throwError('20003:通知火山生成段落音频失败');
  3877. }
  3878. $boolen = true;
  3879. }
  3880. return $boolen;
  3881. }
  3882. public function insertAudioEffect($data) {
  3883. $audio_id = getProp($data, 'audio_id');
  3884. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3885. $bid = getProp($chapter_audio, 'bid');
  3886. $version_id = getProp($chapter_audio, 'version_id');
  3887. $cid = getProp($chapter_audio, 'cid');
  3888. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3889. $audio_effect_json = getProp($data, 'audio_effect_json');
  3890. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3891. try {
  3892. DB::beginTransaction();
  3893. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3894. if (!$count) {
  3895. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3896. }else {
  3897. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3898. }
  3899. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3900. 'audio_effect_status' => '添加中',
  3901. 'audio_effect_json' => $audio_effect_json,
  3902. 'updated_at' => date('Y-m-d H:i:s')
  3903. ]);
  3904. if (!$boolen1) {
  3905. DB::rollBack();
  3906. Utils::throwError('20003:更新生成数据失败');
  3907. }
  3908. $id = DB::table('mp_audio_tasks')->insertGetId([
  3909. 'audio_id' => $audio_id,
  3910. 'generate_status' => '执行中',
  3911. 'generate_json' => json_encode([], 256),
  3912. 'bid' => $bid,
  3913. 'book_name' => getProp($chapter_audio, 'book_name'),
  3914. 'version_id' => $version_id,
  3915. 'version_name' => getProp($chapter_audio, 'version_name'),
  3916. 'cid' => $cid,
  3917. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3918. 'task_name' => $task_name,
  3919. 'created_at' => date('Y-m-d H:i:s'),
  3920. 'updated_at' => date('Y-m-d H:i:s')
  3921. ]);
  3922. if (!$id) {
  3923. DB::rollBack();
  3924. Utils::throwError('20003:创建任务失败');
  3925. }
  3926. }catch (\Exception $e) {
  3927. DB::rollBack();
  3928. Utils::throwError('20003:'.$e->getMessage());
  3929. }
  3930. DB::commit();
  3931. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3932. // 根据ID通过API通知合成音频
  3933. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3934. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3935. $response = $result->getBody()->getContents();
  3936. $response_arr = json_decode($response, true);
  3937. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3938. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3939. Log::info('通知火山插入音效失败: '.$error_msg);
  3940. Utils::throwError('20003:通知火山插入音效失败');
  3941. }
  3942. return true;
  3943. }
  3944. public function insertBgm($data) {
  3945. $audio_id = getProp($data, 'audio_id');
  3946. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3947. $bid = getProp($chapter_audio, 'bid');
  3948. $version_id = getProp($chapter_audio, 'version_id');
  3949. $cid = getProp($chapter_audio, 'cid');
  3950. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3951. $bgm_json = getProp($data, 'bgm_json');
  3952. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3953. if (!$bgm_json) {
  3954. $bgm_json = getProp($data, 'audio_effect_json');
  3955. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3956. }
  3957. try {
  3958. DB::beginTransaction();
  3959. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3960. if (!$count) {
  3961. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3962. }else {
  3963. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3964. }
  3965. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3966. 'bgm_status' => '添加中',
  3967. 'bgm_json' => $bgm_json,
  3968. 'updated_at' => date('Y-m-d H:i:s')
  3969. ]);
  3970. if (!$boolen1) {
  3971. DB::rollBack();
  3972. Utils::throwError('20003:更新生成数据失败');
  3973. }
  3974. $id = DB::table('mp_audio_tasks')->insertGetId([
  3975. 'audio_id' => $audio_id,
  3976. 'generate_status' => '执行中',
  3977. 'generate_json' => json_encode([], 256),
  3978. 'bid' => $bid,
  3979. 'book_name' => getProp($chapter_audio, 'book_name'),
  3980. 'version_id' => $version_id,
  3981. 'version_name' => getProp($chapter_audio, 'version_name'),
  3982. 'cid' => $cid,
  3983. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3984. 'task_name' => $task_name,
  3985. 'created_at' => date('Y-m-d H:i:s'),
  3986. 'updated_at' => date('Y-m-d H:i:s')
  3987. ]);
  3988. if (!$id) {
  3989. DB::rollBack();
  3990. Utils::throwError('20003:创建任务失败');
  3991. }
  3992. }catch (\Exception $e) {
  3993. DB::rollBack();
  3994. Utils::throwError('20003:'.$e->getMessage());
  3995. }
  3996. DB::commit();
  3997. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3998. // 根据ID通过API通知合成音频
  3999. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  4000. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  4001. $response = $result->getBody()->getContents();
  4002. $response_arr = json_decode($response, true);
  4003. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4004. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4005. Log::info('通知火山插入bgm失败: '.$error_msg);
  4006. Utils::throwError('20003:通知火山插入bgm失败');
  4007. }
  4008. return true;
  4009. }
  4010. public function getParagraphAudios($data) {
  4011. $bid = getProp($data, 'bid');
  4012. $cid = getProp($data, 'cid');
  4013. $version_id = getProp($data, 'version_id');
  4014. $sequence = getProp($data, 'sequence');
  4015. // 获取已生成的音频
  4016. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  4017. if ($sequence) $query->where('sequence', $sequence);
  4018. $paragraph_audios = $query->orderBy('sequence')->get();
  4019. $result = [];
  4020. foreach($paragraph_audios as $item) {
  4021. $result[] = [
  4022. 'sequence' => getProp($item, 'sequence'),
  4023. 'role' => getProp($item, 'role'),
  4024. 'gender' => getProp($item, 'gender'),
  4025. 'text' => trim(getProp($item, 'text')),
  4026. 'emotion' => getProp($item, 'emotion'),
  4027. 'emotion_type' => getProp($item, 'emotion_type'),
  4028. 'voice_type' => getProp($item, 'voice_type'),
  4029. 'voice_name' => getProp($item, 'voice_name'),
  4030. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4031. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4032. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4033. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4034. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  4035. ];
  4036. }
  4037. return $result;
  4038. }
  4039. // 新增合成任务
  4040. public function addGenerateTask($data) {
  4041. $bid = getProp($data, 'bid');
  4042. $cid = getProp($data, 'cid');
  4043. $version_id = getProp($data, 'version_id');
  4044. $generate_json = getProp($data, 'generate_json');
  4045. // 获取已生成的音频
  4046. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  4047. $paragraph_list = [];
  4048. foreach($paragraph_audios as $item) {
  4049. $paragraph_list[getProp($item, 'sequence')] = [
  4050. 'role' => getProp($item, 'role'),
  4051. 'gender' => getProp($item, 'gender'),
  4052. 'text' => trim(getProp($item, 'text')),
  4053. 'emotion' => getProp($item, 'emotion'),
  4054. 'emotion_type' => getProp($item, 'emotion_type'),
  4055. 'voice_type' => getProp($item, 'voice_type'),
  4056. 'voice_name' => getProp($item, 'voice_name'),
  4057. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4058. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4059. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4060. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4061. ];
  4062. }
  4063. // 更新角色-音色信息
  4064. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  4065. $existed_role_info = json_decode($existed_role_info, true);
  4066. if (!$existed_role_info) $existed_role_info = [];
  4067. // 获取情感信息
  4068. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4069. $emotion_list = array_flip($emotion_list);
  4070. // 获取音色对应情感组
  4071. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  4072. $timbre_emotion_list = [];
  4073. foreach($timbre_emotions as $item) {
  4074. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  4075. }
  4076. // 构造生成音频的json
  4077. $words = json_decode($generate_json, true);
  4078. // 最终合成前的参数组
  4079. $mp_chapter_paragraph_audios = [];
  4080. $sequence = 1;
  4081. $complete_paragraph_sequences = [];
  4082. foreach($words as &$word) {
  4083. 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:参数格式有误');
  4084. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  4085. $role = getProp($word, 'role');
  4086. $word['gender'] = (int)$word['gender'];
  4087. // 判断音色对应情感是否支持,不支持则调整为中性
  4088. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  4089. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  4090. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  4091. if (isset($emotion_list[getProp($word, 'emotion')])) {
  4092. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  4093. }else {
  4094. $word['emotion'] = '中性';
  4095. $word['emotion_type'] = 'neutral';
  4096. }
  4097. $existed_role_info[$role] = [
  4098. 'timbre_type' => $word['voice_type'],
  4099. 'timbre_name' => $word['voice_name'],
  4100. 'emotion' => $word['emotion'],
  4101. 'emotion_type' => $word['emotion_type'],
  4102. 'speed_ratio' => $word['speed_ratio'],
  4103. 'loudness_ratio'=> $word['loudness_ratio'],
  4104. 'emotion_scale' => $word['emotion_scale'],
  4105. 'pitch' => $word['pitch']
  4106. ];
  4107. $word['paragraph_audio_url'] = '';
  4108. // 判断生成参数是否相同,相同则直接使用已生成的音频
  4109. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  4110. // 如果音频存在并且参数都未改变则使用已生成的音频
  4111. if (getProp($paragraph, 'paragraph_audio_url')) {
  4112. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  4113. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  4114. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  4115. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  4116. // {
  4117. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4118. // }
  4119. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4120. }
  4121. $tmp = $word;
  4122. // 组装章节分句音频数据
  4123. // $tmp['sequence'] = getProp($word, 'sequence');
  4124. // $tmp['text'] = getProp($word, 'text');
  4125. // $tmp['emotion'] = getProp($word, 'emotion');
  4126. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  4127. // $tmp['voice_name'] = getProp($word, 'voice_name');
  4128. // $tmp['voice_type'] = getProp($word, 'voice_type');
  4129. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  4130. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  4131. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  4132. $tmp['bid'] = $bid;
  4133. $tmp['version_id'] = $version_id;
  4134. $tmp['cid'] = $cid;
  4135. $tmp['sequence'] = $sequence;
  4136. $tmp['created_at'] = date('Y-m-d H:i:s');
  4137. $tmp['updated_at'] = date('Y-m-d H:i:s');
  4138. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  4139. $mp_chapter_paragraph_audios[] = $tmp;
  4140. $complete_paragraph_sequences[] = $sequence;
  4141. $sequence++;
  4142. }
  4143. $generate_json = json_encode($words, 256);
  4144. // 判断是否有未生成字幕的段落
  4145. $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();
  4146. if ($no_subtitle_sequences) {
  4147. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  4148. }
  4149. try {
  4150. DB::beginTransaction();
  4151. $role_info = json_encode($existed_role_info, 256);
  4152. $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')]);
  4153. if (!$boolen) {
  4154. DB::rollBack();
  4155. Utils::throwError('20003:更新角色信息失败');
  4156. }
  4157. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  4158. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  4159. if (!$count) {
  4160. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4161. }else {
  4162. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4163. }
  4164. $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')]);
  4165. if (!$boolen1) {
  4166. DB::rollBack();
  4167. Utils::throwError('20003:更新生成数据失败');
  4168. }
  4169. $id = DB::table('mp_audio_tasks')->insertGetId([
  4170. 'audio_id' => getProp($chapter_audio, 'id'),
  4171. 'generate_status' => '执行中',
  4172. 'generate_json' => $generate_json,
  4173. 'bid' => $bid,
  4174. 'book_name' => getProp($chapter_audio, 'book_name'),
  4175. 'version_id' => $version_id,
  4176. 'version_name' => getProp($chapter_audio, 'version_name'),
  4177. 'cid' => $cid,
  4178. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4179. 'task_name' => $task_name,
  4180. 'created_at' => date('Y-m-d H:i:s'),
  4181. 'updated_at' => date('Y-m-d H:i:s')
  4182. ]);
  4183. if (!$id) {
  4184. DB::rollBack();
  4185. Utils::throwError('20003:创建任务失败');
  4186. }
  4187. // 删除不在段落序号范围内的其他数据
  4188. if ($complete_paragraph_sequences) {
  4189. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  4190. }
  4191. // // 删除章节分句音频数据并重新插入
  4192. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  4193. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  4194. // if (!$boolen3) {
  4195. // DB::rollBack();
  4196. // Utils::throwError('20003:更新章节分句音频失败');
  4197. // }
  4198. } catch (\Exception $e) {
  4199. DB::rollBack();
  4200. Utils::throwError('20003:'.$e->getMessage());
  4201. }
  4202. DB::commit();
  4203. // 通知火山生成音频
  4204. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4205. // 根据ID通过API通知合成音频
  4206. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  4207. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  4208. $response = $result->getBody()->getContents();
  4209. $response_arr = json_decode($response, true);
  4210. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4211. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4212. Log::info('通知火山生成音频失败: '.$error_msg);
  4213. Utils::throwError('20003:通知火山生成音频失败');
  4214. }
  4215. return true;
  4216. }
  4217. public function timbreList($data) {
  4218. $gender = getProp($data, 'gender');
  4219. $timbre_name = getProp($data, 'voice_name');
  4220. $category_id = getProp($data, 'category_id');
  4221. $age_stage = getProp($data, 'age_stage');
  4222. $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');
  4223. if ($gender) {
  4224. $query->where('gender', $gender);
  4225. }
  4226. if ($timbre_name) {
  4227. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  4228. }
  4229. if ($category_id) {
  4230. $query->where(function ($query) use ($category_id) {
  4231. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  4232. });
  4233. }
  4234. if ($age_stage) {
  4235. $query->where('age_stage', $age_stage);
  4236. }
  4237. $list = $query->get()->map(function ($value) {
  4238. $value = (array)$value;
  4239. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  4240. return $value;
  4241. })->toArray();
  4242. return $list;
  4243. }
  4244. // 生成火山临时token
  4245. public function setStsToken() {
  4246. // ************* 配置参数 *************
  4247. $method = 'GET';
  4248. $service = 'sts';
  4249. $host = 'open.volcengineapi.com';
  4250. $region = env('VOLC_REGION');
  4251. $endpoint = 'https://open.volcengineapi.com';
  4252. // $endpoint = 'https://tos-cn-beijing.volces.com';
  4253. $access_key = env('VOLC_AK');
  4254. $secret_key = env('VOLC_SK');
  4255. // 获取缓存中的token,如果没有则请求接口
  4256. $token = Redis::get('volc_sts_token');
  4257. if (!$token) {
  4258. // 查询参数
  4259. $query_parameters = [
  4260. 'Action' => 'AssumeRole',
  4261. 'RoleSessionName' => 'user@zw',
  4262. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  4263. 'Version' => '2018-01-01'
  4264. ];
  4265. // 生成URL编码的查询字符串
  4266. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  4267. // 获取签名头信息
  4268. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  4269. // 构建完整URL
  4270. $request_url = $endpoint . '?' . $request_parameters;
  4271. $client = new Client(['verify' => false]);
  4272. $response = $client->get($request_url, ['headers' => $headers]);
  4273. $response_arr = json_decode($response->getBody()->getContents(), true);
  4274. $result = [
  4275. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  4276. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  4277. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  4278. 'Region' => env('VOLC_REGION'),
  4279. 'Endpoint' => env('VOLC_END_POINT'),
  4280. 'Bucket' => env('VOLC_BUCKET'),
  4281. ];
  4282. // 缓存token
  4283. Redis::setex('volc_sts_token', 3000, json_encode($result));
  4284. return $result;
  4285. } else {
  4286. return json_decode($token, true);
  4287. }
  4288. // $response = $response['Response'];
  4289. // $access_key = $response['Credentials']['AccessKeyId'];
  4290. // $secret_key = $response['Credentials']['AccessKeySecret'];
  4291. // $security_token = $response['Credentials']['SecurityToken'];
  4292. // $expiration = $response['Credentials']['Expiration'];
  4293. // dd($response_arr);
  4294. }
  4295. public function emotionGroups($data) {
  4296. $id = getProp($data, 'group_id');
  4297. $group_name = getProp($data, 'group_name');
  4298. $voice_type = getProp($data, 'voice_type');
  4299. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  4300. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  4301. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  4302. if ($group_name) {
  4303. $query->where('group_name', 'like', "%{$group_name}%");
  4304. }
  4305. if ($id) {
  4306. $query->where('id', $id);
  4307. }
  4308. if ($voice_type) {
  4309. $query->where('voice_type', $voice_type);
  4310. }
  4311. return $query->orderBy('id')->get()->map(function ($value) {
  4312. return (array)$value;
  4313. })->toArray();
  4314. }
  4315. private function sign($key, $msg) {
  4316. return hash_hmac('sha256', $msg, $key, true);
  4317. }
  4318. // 生成签名密钥
  4319. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  4320. $kDate = $this->sign($key, $dateStamp);
  4321. $kRegion = $this->sign($kDate, $regionName);
  4322. $kService = $this->sign($kRegion, $serviceName);
  4323. $kSigning = $this->sign($kService, 'request');
  4324. return $kSigning;
  4325. }
  4326. // 获取签名头信息
  4327. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  4328. $contenttype = 'application/x-www-form-urlencoded';
  4329. $accept = 'application/json';
  4330. // 获取当前UTC时间
  4331. $t = new DateTime('now', new DateTimeZone('UTC'));
  4332. $xdate = $t->format('Ymd\THis\Z');
  4333. $datestamp = $t->format('Ymd');
  4334. // 1. 拼接规范请求串
  4335. $canonical_uri = '/';
  4336. $canonical_querystring = $request_parameters;
  4337. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  4338. $signed_headers = 'content-type;host;x-date';
  4339. // 空请求体的SHA256哈希
  4340. $payload_hash = hash('sha256', '');
  4341. $canonical_request = implode("\n", [
  4342. $method,
  4343. $canonical_uri,
  4344. $canonical_querystring,
  4345. $canonical_headers,
  4346. $signed_headers,
  4347. $payload_hash
  4348. ]);
  4349. // 2. 拼接待签名字符串
  4350. $algorithm = 'HMAC-SHA256';
  4351. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  4352. $hashed_canonical_request = hash('sha256', $canonical_request);
  4353. $string_to_sign = implode("\n", [
  4354. $algorithm,
  4355. $xdate,
  4356. $credential_scope,
  4357. $hashed_canonical_request
  4358. ]);
  4359. // 3. 计算签名
  4360. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  4361. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  4362. // 4. 添加签名到请求头
  4363. $authorization_header = sprintf(
  4364. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4365. $algorithm,
  4366. $access_key,
  4367. $credential_scope,
  4368. $signed_headers,
  4369. $signature
  4370. );
  4371. return [
  4372. 'Accept' => $accept,
  4373. 'Content-Type' => $contenttype,
  4374. 'X-Date' => $xdate,
  4375. 'Authorization' => $authorization_header
  4376. ];
  4377. }
  4378. // 文字合成语音(火山引擎)
  4379. public function tts($data) {
  4380. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  4381. $headers = [
  4382. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  4383. 'Content-Type' => 'application/json; charset=UTF-8'
  4384. ];
  4385. $post_data = [
  4386. 'app' => [
  4387. 'appid' => env('VOLC_APPID'),
  4388. 'token' => env('VOLC_TOKEN'),
  4389. 'cluster' => 'volcano_tts'
  4390. ],
  4391. 'user' => [
  4392. 'uid' => 'mp_audio'
  4393. ],
  4394. // 'audio' => [
  4395. // 'voice_type' =>
  4396. // ],
  4397. ];
  4398. }
  4399. public function scriptList($data) {
  4400. $uid = Site::getUid();
  4401. $script_id = getProp($data, 'script_id');
  4402. $script_name = getProp($data, 'script_name');
  4403. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  4404. if ($script_id) {
  4405. $query->where('id', $script_id);
  4406. }
  4407. if ($script_name) {
  4408. $query->where('script_name', 'like', "%{$script_name}%");
  4409. }
  4410. return $query->orderBy('created_at', 'desc')->paginate(12);
  4411. }
  4412. public function scripts($data) {
  4413. $uid = Site::getUid();
  4414. $script_id = getProp($data, 'script_id');
  4415. $script_name = getProp($data, 'script_name');
  4416. $is_products = getProp($data, 'is_products');
  4417. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  4418. if ($script_id) {
  4419. $query->where('id', $script_id);
  4420. }
  4421. if ($is_products !== '') {
  4422. $query->where('is_products', $is_products);
  4423. }
  4424. if ($script_name) {
  4425. $query->where('script_name', 'like', "%{$script_name}%");
  4426. }
  4427. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  4428. return (array)$value;
  4429. })->toArray();
  4430. }
  4431. public function scriptInfo($data) {
  4432. $uid = Site::getUid();
  4433. $script_id = getProp($data, 'script_id');
  4434. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  4435. // ->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();
  4436. ->selectRaw('id as script_id, script_name')->first();
  4437. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4438. $script = (array)$script;
  4439. // 获取分集组信息
  4440. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  4441. ->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')
  4442. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  4443. $value = (array)$value;
  4444. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  4445. return (array)$value;
  4446. })->toArray();
  4447. $script['group'] = $groups;
  4448. return $script;
  4449. }
  4450. public function createScript($data) {
  4451. $script_name = getProp($data, 'script_name');
  4452. $uid = Site::getUid(); // 获取当前用户ID
  4453. $cpid = Site::getCpid(); // 获取当前公司组ID
  4454. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  4455. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  4456. $script_name .= '_'.date('YmdHis');
  4457. }
  4458. return DB::table('mp_scripts')->insertGetId([
  4459. 'script_name' => $script_name,
  4460. 'user_id' => $uid,
  4461. 'cpid' => $cpid,
  4462. 'created_at' => date('Y-m-d H:i:s'),
  4463. 'updated_at' => date('Y-m-d H:i:s')
  4464. ]);
  4465. }
  4466. public function editScript($data) {
  4467. $script_id = getProp($data, 'script_id');
  4468. $script_name = getProp($data, 'script_name');
  4469. $uid = Site::getUid(); // 获取当前用户ID
  4470. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  4471. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  4472. if ($id && (int)$id !== (int)$script_id) {
  4473. $script_name .= '_'.date('YmdHis');
  4474. }
  4475. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4476. 'script_name' => $script_name,
  4477. 'updated_at' => date('Y-m-d H:i:s')
  4478. ]);
  4479. }
  4480. public function delScript($data) {
  4481. $script_id = getProp($data, 'script_id');
  4482. $uid = Site::getUid(); // 获取当前用户ID
  4483. if (!$script_id) Utils::throwError('20003:请选择剧本');
  4484. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4485. 'is_deleted' => 1,
  4486. 'updated_at' => date('Y-m-d H:i:s')
  4487. ]);
  4488. }
  4489. public function createEpisode($data) {
  4490. $script_id = getProp($data, 'script_id');
  4491. $group_name = getProp($data, 'group_name');
  4492. $remark = getProp($data, 'remark');
  4493. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  4494. $uid = Site::getUid(); // 获取当前用户ID
  4495. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  4496. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  4497. $group_name .= '_'.date('YmdHis');
  4498. }
  4499. return DB::table('mp_script_episode_group')->insertGetId([
  4500. 'script_id' => $script_id,
  4501. 'group_name' => $group_name,
  4502. 'user_id' => $uid,
  4503. 'remark' => $remark,
  4504. 'created_at' => date('Y-m-d H:i:s'),
  4505. 'updated_at' => date('Y-m-d H:i:s')
  4506. ]);
  4507. }
  4508. public function editEpisode($data) {
  4509. $group_id = getProp($data, 'group_id');
  4510. $start_episode_number = getProp($data, 'start_episode_number');
  4511. $end_episode_number = getProp($data, 'end_episode_number');
  4512. $group_name = getProp($data, 'group_name');
  4513. $uid = Site::getUid(); // 获取当前用户ID
  4514. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  4515. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  4516. if ($id && (int)$id !== (int)$group_id) {
  4517. $group_name .= '_'.date('YmdHis');
  4518. }
  4519. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4520. 'group_name' => $group_name,
  4521. 'start_episode_number' => $start_episode_number,
  4522. 'end_episode_number' => $end_episode_number,
  4523. 'updated_at' => date('Y-m-d H:i:s')
  4524. ]);
  4525. }
  4526. public function delEpisode($data) {
  4527. $group_id = getProp($data, 'group_id');
  4528. $uid = Site::getUid(); // 获取当前用户ID
  4529. if (!$group_id) Utils::throwError('20003:请选择分集');
  4530. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4531. 'is_deleted' => 1,
  4532. 'updated_at' => date('Y-m-d H:i:s')
  4533. ]);
  4534. }
  4535. /**
  4536. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4537. *
  4538. * @param array $data 包含以下参数:
  4539. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4540. * - question: 用户问题(可选)
  4541. * - model: 使用的模型(r1 或 v3,默认 v3)
  4542. * @return \Generator 返回生成器,用于流式输出
  4543. */
  4544. public function generateEpisodes($data) {
  4545. // 文生文计费预检(special 档,每次调用扣 10)
  4546. $uid = Site::getUid();
  4547. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4548. $script_id = getProp($data, 'script_id');
  4549. $group_id = getProp($data, 'group_id');
  4550. // $file = getProp($data, 'file');
  4551. $file = '';
  4552. $content = getProp($data, 'content', '');
  4553. // $bid = getProp($data, 'bid', 0);
  4554. $bid = 0;
  4555. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4556. if (!$group) {
  4557. Utils::throwError('20003:剧本分集不存在');
  4558. }
  4559. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  4560. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  4561. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  4562. $prompt = getProp($data, 'prompt');
  4563. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  4564. $model = getProp($data, 'model');
  4565. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4566. Utils::throwError('20003:该模型不存在!');
  4567. }
  4568. // 检查是否存在重叠的剧集序号范围
  4569. $exists_groups = DB::table('mp_script_episode_group')
  4570. ->where('script_id', $script_id)
  4571. ->where('id', '<>', $group_id) // 排除当前组
  4572. ->where('is_deleted', 0)
  4573. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4574. // 检查新范围是否与现有范围重叠
  4575. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4576. // 新范围的开始在现有范围内
  4577. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4578. ->where('end_episode_number', '>=', $start_episode_sequence);
  4579. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4580. // 新范围的结束在现有范围内
  4581. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4582. ->where('end_episode_number', '>=', $end_episode_sequence);
  4583. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4584. // 新范围完全包含现有范围
  4585. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4586. ->where('end_episode_number', '<=', $end_episode_sequence);
  4587. });
  4588. })
  4589. ->select('start_episode_number', 'end_episode_number')
  4590. ->get();
  4591. if ($exists_groups->isNotEmpty()) {
  4592. $conflict_ranges = [];
  4593. foreach ($exists_groups as $group) {
  4594. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4595. }
  4596. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4597. }
  4598. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4599. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4600. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4601. if ($model === 'deepseek-chat') {
  4602. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4603. $model = 'deepseek-v4-flash';
  4604. $thinkingMode = 'disabled';
  4605. } elseif ($model === 'deepseek-reasoner') {
  4606. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4607. $model = 'deepseek-v4-flash';
  4608. $thinkingMode = 'enabled';
  4609. }
  4610. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4611. if (!$script) {
  4612. Utils::throwError('20003:剧本不存在');
  4613. }
  4614. $content = getProp($group, 'content');
  4615. if (!$file && !$content && !$bid) {
  4616. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4617. }
  4618. // 提取文件内容
  4619. if ($file) {
  4620. $content = $this->extractFileContent($file);
  4621. if (!$content) {
  4622. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4623. }
  4624. } elseif ($bid) {
  4625. $content = $this->getContentByBid($bid);
  4626. if (!$content) {
  4627. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4628. }
  4629. } elseif ($content) {
  4630. $content = filterContent($content);
  4631. } elseif ($prompt) {
  4632. $content = filterContent($prompt);
  4633. } else {
  4634. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4635. }
  4636. // 构建消息
  4637. $messages = [
  4638. $this->sys_message,
  4639. [
  4640. 'role' => 'user',
  4641. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4642. ]
  4643. ];
  4644. $post_data = [
  4645. 'model' => $model,
  4646. 'messages' => $messages,
  4647. // 'max_tokens' => 8192,
  4648. 'temperature' => 0.7,
  4649. 'frequency_penalty' => 0,
  4650. 'presence_penalty' => 0,
  4651. 'thinking' => ['type' => $thinkingMode],
  4652. 'response_format' => ['type' => 'text'],
  4653. 'stream' => true
  4654. ];
  4655. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4656. // 根据模型类型选择调用方法
  4657. $fullContent = '';
  4658. $fullReasoningContent = '';
  4659. $usage = [];
  4660. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4661. // 处理流式输出
  4662. foreach ($streamGenerator as $chunk) {
  4663. if (isset($chunk['type'])) {
  4664. if ($chunk['type'] === 'done') {
  4665. // 最终结果
  4666. $fullContent = $chunk['full_content'];
  4667. $fullReasoningContent = $chunk['full_reasoning'];
  4668. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4669. } else {
  4670. // 逐块yield数据
  4671. yield $chunk;
  4672. }
  4673. }
  4674. }
  4675. dLog('deepseek')->info('完整内容: '.$fullContent);
  4676. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4677. // 处理完整内容并返回最终结果
  4678. $script_arr = [];
  4679. if ($fullContent) {
  4680. $script_arr = extractScriptContent($fullContent);
  4681. }
  4682. logDB('deepseek', 'info', '解析内容', $script_arr);
  4683. if (!$script_arr['episodes']) {
  4684. Utils::throwError('20003:未生成剧本相关信息');
  4685. // yield [
  4686. // 'type' => 'done',
  4687. // 'script' => $script_arr,
  4688. // 'msg' => '未生成剧本相关信息',
  4689. // 'answer' => $fullContent,
  4690. // 'reasoning' => $fullReasoningContent,
  4691. // 'usage' => $usage
  4692. // ];
  4693. // return ;
  4694. }
  4695. try {
  4696. DB::beginTransaction();
  4697. // // 返回前保存剧本内容
  4698. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4699. // 'content' => $content,
  4700. // 'updated_at' => date('Y-m-d H:i:s')
  4701. // ]);
  4702. // if (!$boolen) {
  4703. // Utils::throwError('20003:保存剧本内容失败');
  4704. // }
  4705. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4706. // 'start_episode_number' => $start_episode_sequence,
  4707. // 'end_episode_number' => $end_episode_sequence,
  4708. // 'updated_at' => date('Y-m-d H:i:s')
  4709. // ]);
  4710. // if (!$boolen1) {
  4711. // Utils::throwError('20003:保存分集失败');
  4712. // }
  4713. $episode_content = '';
  4714. $episodes = [];
  4715. foreach ($script_arr['episodes'] as $item) {
  4716. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4717. // $episodes[] = [
  4718. // 'script_id' => $script_id,
  4719. // 'episode_number' => $item['episode_number'],
  4720. // 'episode_name' => $item['episode_name'],
  4721. // 'episode_content' => $item['episode_content'],
  4722. // 'created_at' => date('Y-m-d H:i:s'),
  4723. // 'updated_at' => date('Y-m-d H:i:s'),
  4724. // ];
  4725. }
  4726. if ($episode_content) {
  4727. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4728. 'episode_content' => $episode_content,
  4729. 'updated_at' => date('Y-m-d H:i:s')
  4730. ]);
  4731. if (!$boolen2) {
  4732. Utils::throwError('20003:保存分集内容失败');
  4733. }
  4734. }else {
  4735. Utils::throwError('20003:分集剧本解析失败');
  4736. }
  4737. // 文生文成功计费(special 档):与落库同事务
  4738. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4739. 'model' => $model,
  4740. 'script_id' => $script_id,
  4741. 'group_id' => $group_id,
  4742. 'source' => 'generateEpisodes',
  4743. ]);
  4744. }catch (\Exception $e) {
  4745. DB::rollBack();
  4746. Utils::throwError('20003:'.$e->getMessage());
  4747. }
  4748. DB::commit();
  4749. yield [
  4750. 'type' => 'done',
  4751. 'script' => $script_arr,
  4752. 'episode_content' => $episode_content,
  4753. 'answer' => $fullContent,
  4754. 'reasoning' => $fullReasoningContent,
  4755. 'usage' => $usage
  4756. ];
  4757. }
  4758. public function chatWithFileStream($data) {
  4759. // 剧本解析资产表计费预检(special 档)
  4760. $uid = Site::getUid();
  4761. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4762. $script_id = getProp($data, 'script_id');
  4763. $group_id = getProp($data, 'group_id');
  4764. $file = getProp($data, 'file');
  4765. $content = getProp($data, 'content', '');
  4766. $bid = getProp($data, 'bid', 0);
  4767. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4768. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4769. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4770. $prompt = getProp($data, 'prompt');
  4771. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4772. if (!empty($prompt)) {
  4773. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4774. }
  4775. $question = getProp($data, 'question', $baseQuestion);
  4776. $model = getProp($data, 'model');
  4777. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4778. Utils::throwError('20003:该模型不存在!');
  4779. }
  4780. // 检查是否存在重叠的剧集序号范围
  4781. $exists_groups = DB::table('mp_script_episode_group')
  4782. ->where('script_id', $script_id)
  4783. ->where('id', '<>', $group_id)
  4784. ->where('is_deleted', 0)
  4785. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4786. // 检查新范围是否与现有范围重叠
  4787. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4788. // 新范围的开始在现有范围内
  4789. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4790. ->where('end_episode_number', '>=', $start_episode_sequence);
  4791. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4792. // 新范围的结束在现有范围内
  4793. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4794. ->where('end_episode_number', '>=', $end_episode_sequence);
  4795. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4796. // 新范围完全包含现有范围
  4797. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4798. ->where('end_episode_number', '<=', $end_episode_sequence);
  4799. });
  4800. })
  4801. ->select('start_episode_number', 'end_episode_number')
  4802. ->get();
  4803. if ($exists_groups->isNotEmpty()) {
  4804. $conflict_ranges = [];
  4805. foreach ($exists_groups as $group) {
  4806. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4807. }
  4808. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4809. }
  4810. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4811. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4812. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4813. if ($model === 'deepseek-chat') {
  4814. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4815. $model = 'deepseek-v4-flash';
  4816. $thinkingMode = 'disabled';
  4817. } elseif ($model === 'deepseek-reasoner') {
  4818. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4819. $model = 'deepseek-v4-flash';
  4820. $thinkingMode = 'enabled';
  4821. }
  4822. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4823. if (!$script) {
  4824. Utils::throwError('20003:剧本不存在');
  4825. }
  4826. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4827. if (!$group) {
  4828. Utils::throwError('20003:剧本分集不存在');
  4829. }
  4830. if (!$file && !$content && !$bid) {
  4831. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4832. }
  4833. // 提取文件内容
  4834. if ($file) {
  4835. $content = $this->extractFileContent($file);
  4836. if (!$content) {
  4837. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4838. }
  4839. } elseif ($bid) {
  4840. $content = $this->getContentByBid($bid);
  4841. if (!$content) {
  4842. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4843. }
  4844. } elseif ($content) {
  4845. $content = filterContent($content);
  4846. } elseif ($prompt) {
  4847. $content = filterContent($prompt);
  4848. } else {
  4849. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4850. }
  4851. // 构建消息
  4852. $messages = [
  4853. [
  4854. 'role' => 'system',
  4855. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4856. 强制要求:\n
  4857. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4858. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4859. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4860. 普通要求:\n
  4861. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4862. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4863. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4864. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4865. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4866. 示例如下:\n
  4867. ###剧本名:西昆仑
  4868. ###故事梗概
  4869. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4870. ###剧本亮点
  4871. 亮点1:绝境奇药,生死一线
  4872. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4873. 亮点2:结拜兄妹,化解尴尬
  4874. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4875. 亮点3:纤发夺命,情愫暗涌
  4876. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4877. ###人物关系
  4878. 阿雪与梁萧之间存在兄妹之情。
  4879. ###核心矛盾
  4880. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4881. ###主体列表
  4882. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4883. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4884. 阴阳球:天地异宝,能化生精气,救人于危难。
  4885. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4886. ###美术风格
  4887. 基础画风风格词:厚涂古风
  4888. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4889. ###场景列表
  4890. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4891. [
  4892. 'role' => 'user',
  4893. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4894. ]
  4895. ];
  4896. $post_data = [
  4897. 'model' => $model,
  4898. 'messages' => $messages,
  4899. // 'max_tokens' => 8192,
  4900. 'temperature' => 0.7,
  4901. 'frequency_penalty' => 0,
  4902. 'presence_penalty' => 0,
  4903. 'thinking' => ['type' => $thinkingMode],
  4904. 'response_format' => ['type' => 'text'],
  4905. 'stream' => true
  4906. ];
  4907. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4908. // 根据模型类型选择调用方法
  4909. $fullContent = '';
  4910. $fullReasoningContent = '';
  4911. $usage = [];
  4912. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4913. // 处理流式输出
  4914. foreach ($streamGenerator as $chunk) {
  4915. if (isset($chunk['type'])) {
  4916. if ($chunk['type'] === 'done') {
  4917. // 最终结果
  4918. $fullContent = $chunk['full_content'];
  4919. $fullReasoningContent = $chunk['full_reasoning'];
  4920. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4921. } else {
  4922. // 逐块yield数据
  4923. yield $chunk;
  4924. }
  4925. }
  4926. }
  4927. dLog('deepseek')->info('完整内容: '.$fullContent);
  4928. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4929. // 处理完整内容并返回最终结果
  4930. $script_arr = [];
  4931. if ($fullContent) {
  4932. $script_arr = extractScriptContent($fullContent);
  4933. }
  4934. logDB('deepseek', 'info', '解析内容', $script_arr);
  4935. if (!$script_arr['roles']) {
  4936. Utils::throwError('20003:未生成剧本相关信息');
  4937. // yield [
  4938. // 'type' => 'done',
  4939. // 'script' => $script_arr,
  4940. // 'msg' => '未生成剧本相关信息',
  4941. // 'answer' => $fullContent,
  4942. // 'reasoning' => $fullReasoningContent,
  4943. // 'usage' => $usage
  4944. // ];
  4945. }
  4946. try {
  4947. DB::beginTransaction();
  4948. // // 返回前保存剧本内容
  4949. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4950. // 'content' => $content,
  4951. // 'status' => '解析完成',
  4952. // 'updated_at' => date('Y-m-d H:i:s')
  4953. // ]);
  4954. // if (!$boolen) {
  4955. // Utils::throwError('20003:保存剧本内容失败');
  4956. // }
  4957. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4958. 'start_episode_number' => $start_episode_sequence,
  4959. 'end_episode_number' => $end_episode_sequence,
  4960. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4961. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4962. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4963. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4964. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4965. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4966. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4967. 'status' => '解析完成',
  4968. 'content' => $content,
  4969. 'updated_at' => date('Y-m-d H:i:s')
  4970. ]);
  4971. if (!$boolen1) {
  4972. Utils::throwError('20003:保存分集失败');
  4973. }
  4974. // 剧本解析资产表成功计费(special 档):与落库同事务
  4975. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4976. 'model' => $model,
  4977. 'script_id' => $script_id,
  4978. 'group_id' => $group_id,
  4979. 'source' => 'chatWithFileStream',
  4980. ], 'special');
  4981. // $episodes = [];
  4982. // foreach ($script_arr['episodes'] as $item) {
  4983. // $episodes[] = [
  4984. // 'script_id' => $script_id,
  4985. // 'episode_number' => $item['episode_number'],
  4986. // 'episode_name' => $item['episode_name'],
  4987. // 'episode_content' => $item['episode_content'],
  4988. // 'created_at' => date('Y-m-d H:i:s'),
  4989. // 'updated_at' => date('Y-m-d H:i:s'),
  4990. // ];
  4991. // }
  4992. // if ($episodes) {
  4993. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4994. // if (!$boolen2) {
  4995. // Utils::throwError('20003:保存分集内容失败');
  4996. // }
  4997. // }else {
  4998. // Utils::throwError('20003:分集剧本解析失败');
  4999. // }
  5000. }catch (\Exception $e) {
  5001. DB::rollBack();
  5002. Utils::throwError('20003:'.$e->getMessage());
  5003. }
  5004. DB::commit();
  5005. yield [
  5006. 'type' => 'done',
  5007. 'script' => $script_arr,
  5008. 'answer' => $fullContent,
  5009. 'reasoning' => $fullReasoningContent,
  5010. 'usage' => $usage
  5011. ];
  5012. }
  5013. /**
  5014. * 上传文件识别文字内容并与 DeepSeek 进行对话
  5015. *
  5016. * @param array $data 包含以下参数:
  5017. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5018. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  5019. * - model: 使用的模型(r1 或 v3,默认 v3)
  5020. * @return array
  5021. */
  5022. public function chatWithFile($data) {
  5023. // 剧本解析资产表计费预检(special 档)
  5024. $uid = Site::getUid();
  5025. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  5026. $script_id = getProp($data, 'script_id');
  5027. $file = getProp($data, 'file');
  5028. $content = getProp($data, 'content', '');
  5029. $bid = getProp($data, 'bid', 0);
  5030. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5031. $total_episode_num = getProp($data, 'total_episode_num', 30);
  5032. $prompt = getProp($data, 'prompt');
  5033. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  5034. if (!empty($prompt)) {
  5035. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  5036. }
  5037. $question = getProp($data, 'question', $baseQuestion);
  5038. // 处理文本模型
  5039. $model = getProp($data, 'model');
  5040. if (!$model) {
  5041. // 用户没有输入,使用默认值
  5042. $model = 'doubao-seed-2-0-mini-260215';
  5043. }
  5044. // 验证模型是否在可用模型表中
  5045. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5046. $model = 'doubao-seed-2-0-mini-260215';
  5047. }
  5048. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5049. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5050. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5051. if ($model === 'deepseek-chat') {
  5052. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5053. $model = 'deepseek-v4-flash';
  5054. $thinkingMode = 'disabled';
  5055. } elseif ($model === 'deepseek-reasoner') {
  5056. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5057. $model = 'deepseek-v4-flash';
  5058. $thinkingMode = 'enabled';
  5059. }
  5060. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  5061. if (!$script) {
  5062. Utils::throwError('20003:剧本不存在');
  5063. }
  5064. if (!$file && !$content && !$bid) {
  5065. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5066. }
  5067. // 提取文件内容
  5068. if ($file) {
  5069. $content = $this->extractFileContent($file);
  5070. if (!$content) {
  5071. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5072. }
  5073. } elseif ($bid) {
  5074. $content = $this->getContentByBid($bid);
  5075. if (!$content) {
  5076. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5077. }
  5078. } elseif ($content) {
  5079. $content = filterContent($content);
  5080. } elseif ($prompt) {
  5081. $content = filterContent($prompt);
  5082. } else {
  5083. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5084. }
  5085. // 构建消息
  5086. $messages = [
  5087. $this->sys_message,
  5088. [
  5089. 'role' => 'user',
  5090. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  5091. ]
  5092. ];
  5093. $post_data = [
  5094. 'model' => $model,
  5095. 'messages' => $messages,
  5096. // 'max_tokens' => 8192,
  5097. 'temperature' => 0.7,
  5098. 'frequency_penalty' => 0,
  5099. 'presence_penalty' => 0,
  5100. 'thinking' => ['type' => $thinkingMode],
  5101. 'response_format' => ['type' => 'text'],
  5102. 'stream' => false
  5103. ];
  5104. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5105. // 根据模型类型选择调用方法
  5106. $fullContent = '';
  5107. $usage = [];
  5108. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  5109. if (is_array($chatResult)) {
  5110. $fullContent = $chatResult['fullContent'];
  5111. $usage = $chatResult['usage'];
  5112. }
  5113. $script_arr = [];
  5114. // 处理结果
  5115. if ($fullContent) {
  5116. $script_arr = extractScriptContent($fullContent);
  5117. }
  5118. // 返回前保存剧本内容
  5119. DB::table('mp_scripts')->where('id', $script_id)->update([
  5120. 'content' => $content,
  5121. 'updated_at' => date('Y-m-d H:i:s')
  5122. ]);
  5123. // 剧本解析资产表成功计费(special 档):同时记录积分与 token 明细
  5124. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5125. 'model' => $model,
  5126. 'script_id' => $script_id,
  5127. 'source' => 'chatWithFile',
  5128. ], 'special');
  5129. return [
  5130. 'script' => $script_arr,
  5131. 'answer' => $fullContent,
  5132. 'usage' => $usage
  5133. ];
  5134. }
  5135. public function getEpisodeContent($data) {
  5136. $group_id = getProp($data, 'group_id');
  5137. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  5138. }
  5139. public function saveEpisodeContent($data) {
  5140. $script_id = getProp($data, 'script_id');
  5141. $group_id = getProp($data, 'group_id');
  5142. $start_episode_sequence = getProp($data, 'start_episode_number');
  5143. $end_episode_sequence = getProp($data, 'end_episode_number');
  5144. // 检查是否存在重叠的剧集序号范围
  5145. $exists_groups = DB::table('mp_script_episode_group')
  5146. ->where('script_id', $script_id)
  5147. ->where('id', '<>', $group_id) // 排除当前组
  5148. ->where('is_deleted', 0)
  5149. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  5150. // 检查新范围是否与现有范围重叠
  5151. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5152. // 新范围的开始在现有范围内
  5153. $q->where('start_episode_number', '<=', $start_episode_sequence)
  5154. ->where('end_episode_number', '>=', $start_episode_sequence);
  5155. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5156. // 新范围的结束在现有范围内
  5157. $q->where('start_episode_number', '<=', $end_episode_sequence)
  5158. ->where('end_episode_number', '>=', $end_episode_sequence);
  5159. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5160. // 新范围完全包含现有范围
  5161. $q->where('start_episode_number', '>=', $start_episode_sequence)
  5162. ->where('end_episode_number', '<=', $end_episode_sequence);
  5163. });
  5164. })
  5165. ->select('start_episode_number', 'end_episode_number')
  5166. ->get();
  5167. if ($exists_groups->isNotEmpty()) {
  5168. $conflict_ranges = [];
  5169. foreach ($exists_groups as $group) {
  5170. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  5171. }
  5172. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  5173. }
  5174. $episode_content = getProp($data, 'episode_content');
  5175. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  5176. 'content' => $episode_content,
  5177. 'start_episode_number' => $start_episode_sequence,
  5178. 'end_episode_number' => $end_episode_sequence,
  5179. 'updated_at' => date('Y-m-d H:i:s')
  5180. ]);
  5181. $script_arr =getProp($data, 'script', []);
  5182. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  5183. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5184. $script_id = getProp($data, 'script_id');
  5185. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  5186. try {
  5187. DB::beginTransaction();
  5188. $update_data = [
  5189. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5190. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5191. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5192. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5193. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5194. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5195. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5196. 'status' => 3,
  5197. 'start_episode_sequence' => $start_episode_sequence,
  5198. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  5199. 'episode_num' => count($script_arr['episodes']),
  5200. 'updated_at' => date('Y-m-d H:i:s')
  5201. ];
  5202. // 保存剧本内容
  5203. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  5204. if (!$boolen) {
  5205. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  5206. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  5207. Utils::throwError('20003:剧本内容保存失败');
  5208. }
  5209. // 保存分集内容
  5210. // 删除历史分集内容
  5211. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  5212. $episodes = [];
  5213. $sequence = 1;
  5214. foreach ($script_arr['episodes'] as $episode) {
  5215. $segment_number = 1;
  5216. foreach($episode['segments'] as $segment) {
  5217. $episodes[] = [
  5218. 'script_id' => $script_id,
  5219. 'episode_number' => $episode['episode_number'],
  5220. 'title' => $episode['title'],
  5221. // 'content' => $episode['content'],
  5222. 'content' => '',
  5223. 'segment_number' => $segment_number,
  5224. 'segment_content' => $segment['segment_content'],
  5225. 'sequence' => $sequence,
  5226. 'created_at' => date('Y-m-d H:i:s'),
  5227. 'updated_at' => date('Y-m-d H:i:s')
  5228. ];
  5229. $sequence++;
  5230. $segment_number++;
  5231. }
  5232. }
  5233. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5234. if (!$boolen2) {
  5235. dLog('deepseek')->info('分集内容保存失败', $episodes);
  5236. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  5237. Utils::throwError('20003:分集内容保存失败');
  5238. }
  5239. } catch (\Exception $e) {
  5240. DB::rollBack();
  5241. Utils::throwError('20003:'.$e->getMessage());
  5242. }
  5243. DB::commit();
  5244. return true;
  5245. }
  5246. public function getBookContent($data) {
  5247. $bid = getProp($data, 'bid');
  5248. $start_sequence = getProp($data, 'start_sequence');
  5249. $end_sequence = getProp($data, 'end_sequence');
  5250. $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])
  5251. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  5252. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  5253. return $return_content;
  5254. }
  5255. public function exportScript($data) {
  5256. $filename = getProp($data, 'filename');
  5257. $script_id = getProp($data, 'script_id');
  5258. $group_id = getProp($data, 'group_id');
  5259. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  5260. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  5261. if (!$script) Utils::throwError('20003:该剧本不存在!');
  5262. $script = (array)$script;
  5263. // 获取分集组信息
  5264. if ($group_id) {
  5265. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5266. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5267. ->get()->map(function($value) {
  5268. return (array)$value;
  5269. })->toArray();
  5270. }else {
  5271. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5272. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5273. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  5274. return (array)$value;
  5275. })->toArray();
  5276. }
  5277. if (!$groups) Utils::throwError('20003:分集不存在');
  5278. $script['group'] = $groups;
  5279. $export_type = getProp($data, 'export_type', 'txt');
  5280. // 生成文件名
  5281. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  5282. // 根据导出类型生成不同格式的文件
  5283. switch ($export_type) {
  5284. case 'txt':
  5285. return $this->exportScriptAsTxt($script, $filename);
  5286. case 'pdf':
  5287. return $this->exportScriptAsPdf($script, $filename);
  5288. default:
  5289. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  5290. }
  5291. }
  5292. /**
  5293. * 导出剧本为TXT格式
  5294. */
  5295. private function exportScriptAsTxt($script, $filename) {
  5296. // 构建TXT内容
  5297. $content = $this->buildScriptContent($script);
  5298. // 设置响应头,直接下载
  5299. header('Content-Type: text/plain; charset=utf-8');
  5300. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  5301. header('Content-Length: ' . strlen($content));
  5302. // 输出内容并结束
  5303. echo $content;
  5304. exit();
  5305. }
  5306. /**
  5307. * 导出剧本为PDF格式
  5308. */
  5309. private function exportScriptAsPdf($script, $filename) {
  5310. // 使用HTML转PDF的方式来更好地支持中文
  5311. $htmlContent = $this->buildScriptHtmlForPdf($script);
  5312. // 创建PDF实例
  5313. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  5314. // 设置文档信息
  5315. $pdf->SetCreator('剧本导出系统');
  5316. $pdf->SetAuthor('系统');
  5317. $pdf->SetTitle($script['script_name']);
  5318. $pdf->SetSubject('剧本导出');
  5319. // 设置边距
  5320. $pdf->SetMargins(15, 15, 15);
  5321. $pdf->SetAutoPageBreak(TRUE, 15);
  5322. // 添加页面
  5323. $pdf->AddPage();
  5324. // 注册并使用 simsun.ttf 字体
  5325. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  5326. // 使用HTML内容生成PDF
  5327. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  5328. // 直接输出PDF文件供下载
  5329. header('Content-Type: application/pdf');
  5330. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  5331. // 直接输出PDF内容
  5332. $pdf->Output($filename . '.pdf', 'D');
  5333. exit();
  5334. }
  5335. /**
  5336. * 构建用于PDF的HTML内容
  5337. */
  5338. private function buildScriptHtmlForPdf($script) {
  5339. $html = '<style>
  5340. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  5341. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  5342. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  5343. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  5344. .info { margin-bottom: 8px; }
  5345. .group { margin-bottom: 30px; page-break-inside: avoid; }
  5346. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  5347. .segment { margin-bottom: 10px; margin-left: 20px; }
  5348. .episode-content { white-space: pre-wrap; }
  5349. </style>';
  5350. // 标题
  5351. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  5352. // 处理分组数据
  5353. if (!empty($script['group']) && is_array($script['group'])) {
  5354. $groups = (array)$script['group'];
  5355. foreach ($groups as $group) {
  5356. $html .= '<div class="group">';
  5357. // 分组标题
  5358. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  5359. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  5360. // 故事梗概
  5361. if (!empty($group['intro'])) {
  5362. $html .= '<h3>故事梗概</h3>';
  5363. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  5364. }
  5365. // 剧本亮点
  5366. if (!empty($group['highlights'])) {
  5367. $html .= '<h3>剧本亮点</h3>';
  5368. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  5369. }
  5370. // 人物关系
  5371. if (!empty($group['role_relationship'])) {
  5372. $html .= '<h3>人物关系</h3>';
  5373. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  5374. }
  5375. // 核心矛盾
  5376. if (!empty($group['core_contradiction'])) {
  5377. $html .= '<h3>核心矛盾</h3>';
  5378. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  5379. }
  5380. // 主体列表
  5381. if (!empty($group['roles']) && is_array($group['roles'])) {
  5382. $html .= '<h3>主体列表</h3>';
  5383. $html .= '<ul>';
  5384. foreach ($group['roles'] as $role) {
  5385. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  5386. }
  5387. $html .= '</ul>';
  5388. }
  5389. // 美术风格
  5390. if (!empty($group['art_style'])) {
  5391. $html .= '<h3>美术风格</h3>';
  5392. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  5393. }
  5394. // 场景列表
  5395. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5396. $html .= '<h3>场景列表</h3>';
  5397. $html .= '<ul>';
  5398. foreach ($group['scenes'] as $scene) {
  5399. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  5400. }
  5401. $html .= '</ul>';
  5402. }
  5403. // 分集剧本
  5404. if (!empty($group['episode_content'])) {
  5405. $html .= '<h3>分集剧本</h3>';
  5406. // 去除零宽字符和其他不可见字符
  5407. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  5408. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  5409. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  5410. }
  5411. $html .= '</div>';
  5412. }
  5413. }
  5414. return $html;
  5415. }
  5416. /**
  5417. * 构建PDF内容
  5418. */
  5419. private function buildPdfContent($pdf, $script) {
  5420. // 标题
  5421. $pdf->SetFont('dejavusans', 'B', 18);
  5422. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  5423. $pdf->Ln(5);
  5424. // 基本信息
  5425. $pdf->SetFont('dejavusans', '', 12);
  5426. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  5427. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  5428. $pdf->Ln(5);
  5429. // 剧本简介
  5430. if (!empty($script['intro'])) {
  5431. $pdf->SetFont('dejavusans', 'B', 14);
  5432. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  5433. $pdf->SetFont('dejavusans', '', 12);
  5434. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  5435. $pdf->Ln(3);
  5436. }
  5437. // 亮点
  5438. if (!empty($script['highlights'])) {
  5439. $pdf->SetFont('dejavusans', 'B', 14);
  5440. $pdf->Cell(0, 10, '亮点', 0, 1);
  5441. $pdf->SetFont('dejavusans', '', 12);
  5442. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  5443. $pdf->Ln(3);
  5444. }
  5445. // 核心矛盾
  5446. if (!empty($script['core_contradiction'])) {
  5447. $pdf->SetFont('dejavusans', 'B', 14);
  5448. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  5449. $pdf->SetFont('dejavusans', '', 12);
  5450. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  5451. $pdf->Ln(3);
  5452. }
  5453. // 艺术风格
  5454. if (!empty($script['art_style'])) {
  5455. $pdf->SetFont('dejavusans', 'B', 14);
  5456. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  5457. $pdf->SetFont('dejavusans', '', 12);
  5458. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  5459. $pdf->Ln(3);
  5460. }
  5461. // 备注
  5462. if (!empty($script['remark'])) {
  5463. $pdf->SetFont('dejavusans', 'B', 14);
  5464. $pdf->Cell(0, 10, '备注', 0, 1);
  5465. $pdf->SetFont('dejavusans', '', 12);
  5466. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  5467. $pdf->Ln(3);
  5468. }
  5469. // 角色列表
  5470. if (!empty($script['roles']) && is_array($script['roles'])) {
  5471. $pdf->SetFont('dejavusans', 'B', 14);
  5472. $pdf->Cell(0, 10, '角色列表', 0, 1);
  5473. $pdf->SetFont('dejavusans', '', 12);
  5474. foreach ($script['roles'] as $index => $role) {
  5475. if (is_array($role) || is_object($role)) {
  5476. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  5477. } else {
  5478. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  5479. }
  5480. }
  5481. $pdf->Ln(3);
  5482. }
  5483. // 角色关系
  5484. if (!empty($script['role_relationship'])) {
  5485. $pdf->SetFont('dejavusans', 'B', 14);
  5486. $pdf->Cell(0, 10, '角色关系', 0, 1);
  5487. $pdf->SetFont('dejavusans', '', 12);
  5488. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  5489. $pdf->Ln(3);
  5490. }
  5491. // 场景列表
  5492. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  5493. $pdf->SetFont('dejavusans', 'B', 14);
  5494. $pdf->Cell(0, 10, '场景列表', 0, 1);
  5495. $pdf->SetFont('dejavusans', '', 12);
  5496. foreach ($script['scenes'] as $index => $scene) {
  5497. if (is_array($scene) || is_object($scene)) {
  5498. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  5499. } else {
  5500. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  5501. }
  5502. }
  5503. $pdf->Ln(5);
  5504. }
  5505. // 分集内容
  5506. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  5507. $pdf->SetFont('dejavusans', 'B', 16);
  5508. $pdf->Cell(0, 12, '分集内容', 0, 1);
  5509. $pdf->Ln(3);
  5510. foreach ($script['episodes'] as $episode) {
  5511. // 检查是否需要新页面
  5512. if ($pdf->GetY() > 250) {
  5513. $pdf->AddPage();
  5514. }
  5515. $pdf->SetFont('dejavusans', 'B', 14);
  5516. $episodeTitle = '第' . $episode['episode_number'] . '集';
  5517. if (!empty($episode['title'])) {
  5518. $episodeTitle .= ':' . $episode['title'];
  5519. }
  5520. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  5521. // 处理分段内容
  5522. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  5523. $pdf->SetFont('dejavusans', '', 12);
  5524. foreach ($episode['segments'] as $segment) {
  5525. if (!empty($segment['segment_content'])) {
  5526. // 如果有分段编号,显示分段标题
  5527. if (!empty($segment['segment_number'])) {
  5528. $pdf->SetFont('dejavusans', 'B', 12);
  5529. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  5530. $pdf->SetFont('dejavusans', '', 12);
  5531. }
  5532. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  5533. $pdf->Ln(2);
  5534. }
  5535. }
  5536. }
  5537. $pdf->Ln(5);
  5538. }
  5539. }
  5540. }
  5541. /**
  5542. * 构建剧本文本内容
  5543. */
  5544. private function buildScriptContent($script) {
  5545. $content = '';
  5546. $groups = $script['group'];
  5547. $groups = (array)$groups;
  5548. foreach ($groups as $group) {
  5549. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  5550. // 剧本基本信息
  5551. if (!empty($group['intro'])) {
  5552. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5553. }
  5554. if (!empty($group['highlights'])) {
  5555. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5556. }
  5557. if (!empty($group['role_relationship'])) {
  5558. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5559. }
  5560. if (!empty($group['core_contradiction'])) {
  5561. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5562. }
  5563. if (!empty($group['roles']) && is_array($group['roles'])) {
  5564. $content .= "###主体列表\n";
  5565. foreach ($group['roles'] as $role) {
  5566. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5567. }
  5568. $content .= "\n\n";
  5569. }
  5570. if (!empty($group['art_style'])) {
  5571. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5572. }
  5573. // 场景信息
  5574. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5575. $content .= "###场景列表\n";
  5576. foreach ($group['scenes'] as $scene) {
  5577. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5578. }
  5579. $content .= "\n\n";
  5580. }
  5581. // 分集内容
  5582. if (!empty($group['episode_content'])) {
  5583. $content .= "###分集剧本\n";
  5584. $content .= $group['episode_content'];
  5585. // foreach ($script['episodes'] as $episode) {
  5586. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5587. // // if (!empty($episode['episode_name'])) {
  5588. // // $content .= ":" . $episode['episode_name'];
  5589. // // }
  5590. // // $content .= "\n";
  5591. // $content .= $episode['episode_content'] . "\n\n";
  5592. // }
  5593. }
  5594. }
  5595. return $content;
  5596. }
  5597. /**
  5598. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5599. *
  5600. * @param array $data 包含以下参数:
  5601. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5602. * - question: 用户问题(可选)
  5603. * - model: 使用的模型(r1 或 v3,默认 v3)
  5604. * @return \Generator 返回生成器,用于流式输出
  5605. */
  5606. public function addChat($data) {
  5607. $uid = Site::getUid();
  5608. $anime_id = getProp($data, 'anime_id');
  5609. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5610. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5611. if (!$anime) Utils::throwError('20003:对话不存在');
  5612. $file = getProp($data, 'file');
  5613. $content = getProp($data, 'content', '');
  5614. $bid = getProp($data, 'bid', 0);
  5615. $script_id = getProp($data, 'script_id', 0);
  5616. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5617. $prompt = getProp($data, 'prompt');
  5618. $user_anime_name = getProp($anime, 'anime_name');
  5619. // 处理文本模型
  5620. $model = getProp($data, 'model');
  5621. if (!$model) {
  5622. // 用户没有输入,从anime表获取
  5623. $model = getProp($anime, 'model');
  5624. if (!$model) {
  5625. // anime表也没有,使用默认值
  5626. $model = 'doubao-seed-2-0-mini-260215';
  5627. }
  5628. }
  5629. // 验证模型是否在可用模型表中
  5630. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5631. $model = 'doubao-seed-2-0-mini-260215';
  5632. }
  5633. $is_multi = getProp($anime, 'is_multi');
  5634. $is_single = (int)$is_multi !== 1;
  5635. // 积分余额预检(仅单剧集模式收费)
  5636. if ($is_single) {
  5637. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5638. }
  5639. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5640. if ($prompt) {
  5641. $question .= "本次修改要求如下:\n{$prompt}";
  5642. }
  5643. // if (!$file && !$content && !$bid) {
  5644. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5645. // }
  5646. // 提取文件内容
  5647. if ($file) {
  5648. $content = $this->extractFileContent($file);
  5649. if (!$content) {
  5650. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5651. }
  5652. } elseif ($script_id) {
  5653. $content = $this->getContentByScriptId($script_id);
  5654. if (!$content) {
  5655. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5656. }
  5657. } elseif ($bid) {
  5658. $content = $this->getContentByBid($bid);
  5659. if (!$content) {
  5660. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5661. }
  5662. } elseif ($content) {
  5663. $content = filterContent($content);
  5664. } else {
  5665. $content = getProp($anime, 'content');
  5666. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5667. $need_generate_content = true;
  5668. }
  5669. }
  5670. // 美术风格
  5671. $input_art_style = getProp($data, 'art_style');
  5672. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5673. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5674. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5675. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5676. 中年女:邻居阿姨
  5677. 老年男:幽默大爷
  5678. 老年女:婆婆
  5679. 萌娃:奶气萌娃";
  5680. // 判断是否需要生成原文内容
  5681. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5682. // 如果需要生成原文内容,添加额外的要求
  5683. $content_generation_requirement = $need_generate_content
  5684. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5685. : "";
  5686. // 美术风格
  5687. if (!$mappedArtStyle) {
  5688. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5689. }else {
  5690. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5691. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5692. }else {
  5693. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5694. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5695. }
  5696. }
  5697. $systemPrompt = $is_single
  5698. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5699. 强制要求:
  5700. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5701. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5702. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5703. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5704. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5705. 普通要求:
  5706. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5707. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5708. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5709. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5710. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5711. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5712. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5713. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5714. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5715. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5716. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5717. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5718. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5719. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5720. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5721. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5722. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5723. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5724. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5725. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5726. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5727. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5728. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5729. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5730. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5731. 5.{$mappedArtStyle_prompt}\n\n
  5732. 示例如下:\n
  5733. ###剧本名:西昆仑
  5734. ###故事梗概
  5735. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5736. ###剧本亮点
  5737. 亮点1:绝境奇药,生死一线
  5738. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5739. 亮点2:结拜兄妹,化解尴尬
  5740. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5741. 亮点3:纤发夺命,情愫暗涌
  5742. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5743. ###人物关系
  5744. 阿雪与梁萧之间存在兄妹之情。
  5745. ###核心矛盾
  5746. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5747. ###主体列表
  5748. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5749. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5750. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5751. 姿态:站立。}{{甜心小美}}
  5752. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5753. 全景,正面拍摄,青年女性,亚洲人。
  5754. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5755. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5756. 姿态:站立。}{{阳光青年}}
  5757. ###美术风格
  5758. 基础画风风格词:厚涂古风
  5759. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5760. ###场景列表
  5761. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5762. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5763. 无人物。}
  5764. ###分镜剧本
  5765. ##第1幕:徐家老旧厨房 白天 室内
  5766. 分镜1
  5767. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5768. 场景:徐家老旧厨房
  5769. 构图设计:全景,低角度仰视
  5770. 运镜调度:手持拍摄
  5771. 配音角色:旁白
  5772. 出镜角色:许芸-校服装、徐母
  5773. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5774. 画面类型:普通画面
  5775. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5776. 分镜2
  5777. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5778. 场景:徐家老旧厨房
  5779. 构图设计:近景,徐母面部特写
  5780. 运镜调度:固定镜头
  5781. 配音角色:徐母
  5782. 出镜角色:徐母
  5783. 台词内容:问我夜不归宿死哪儿去了。
  5784. 画面类型:对口型
  5785. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5786. ##第2幕:徐家简陋客厅 黄昏 室内
  5787. 分镜3
  5788. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5789. 场景:徐家简陋客厅
  5790. 构图设计:全景,景深虚化
  5791. 运镜调度:固定镜头
  5792. 配音角色:旁白
  5793. 出镜角色:无
  5794. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5795. 画面类型:普通画面
  5796. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5797. 分镜4
  5798. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5799. 场景:徐家简陋客厅
  5800. 构图设计:特写,火车票
  5801. 运镜调度:固定镜头
  5802. 配音角色:旁白
  5803. 出镜角色:无
  5804. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5805. 画面类型:普通画面
  5806. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5807. "
  5808. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5809. 强制要求:\n
  5810. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5811. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5812. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5813. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5814. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5815. 普通要求:\n
  5816. 1.剧本名(必须生成)必须与文档内容高度相关
  5817. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5818. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5819. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5820. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5821. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5822. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5823. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5824. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5825. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5826. 4.{$mappedArtStyle_prompt}\n\n
  5827. 示例如下:\n
  5828. ###剧本名:西昆仑
  5829. ###故事梗概
  5830. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5831. ###剧本亮点
  5832. 亮点1:绝境奇药,生死一线
  5833. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5834. 亮点2:结拜兄妹,化解尴尬
  5835. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5836. 亮点3:纤发夺命,情愫暗涌
  5837. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5838. ###人物关系
  5839. 阿雪与梁萧之间存在兄妹之情。
  5840. ###核心矛盾
  5841. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5842. ###主体列表
  5843. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5844. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5845. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5846. 姿态:站立。}{{甜心小美}}
  5847. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5848. 全景,正面拍摄,青年女性,亚洲人。
  5849. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5850. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5851. 姿态:站立。}{{阳光青年}}
  5852. ###美术风格
  5853. 基础画风风格词:厚涂古风
  5854. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5855. ###场景列表
  5856. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5857. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5858. 无人物。}";
  5859. // 构建消息
  5860. $messages = [
  5861. [
  5862. 'role' => 'system',
  5863. 'content' => $systemPrompt
  5864. ],
  5865. [
  5866. 'role' => 'user',
  5867. 'content' => "以下是文档内容:
  5868. {$content}
  5869. 用户问题:
  5870. {$question}"
  5871. ]
  5872. ];
  5873. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5874. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5875. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5876. if ($model === 'deepseek-chat') {
  5877. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5878. $model = 'deepseek-v4-flash';
  5879. $thinkingMode = 'disabled';
  5880. } elseif ($model === 'deepseek-reasoner') {
  5881. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5882. $model = 'deepseek-v4-flash';
  5883. $thinkingMode = 'enabled';
  5884. }
  5885. $post_data = [
  5886. 'model' => $model,
  5887. 'messages' => $messages,
  5888. // 'max_tokens' => 8192,
  5889. 'temperature' => 0.7,
  5890. 'frequency_penalty' => 0,
  5891. 'presence_penalty' => 0,
  5892. 'response_format' => ['type' => 'text'],
  5893. 'thinking' => ['type'=>$thinkingMode],
  5894. 'stream' => true // 启用流式输出
  5895. ];
  5896. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5897. // 根据模型类型选择调用方法
  5898. $fullContent = '';
  5899. $fullReasoningContent = '';
  5900. $usage = [];
  5901. try {
  5902. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5903. // 验证返回值类型
  5904. if (!is_iterable($streamGenerator)) {
  5905. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5906. dLog('deepseek')->error('addChat流式生成器无效', [
  5907. 'generator_type' => $errorType,
  5908. 'model' => $model,
  5909. 'anime_id' => $anime_id
  5910. ]);
  5911. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5912. 'type' => $errorType,
  5913. 'model' => $model
  5914. ]);
  5915. yield [
  5916. 'type' => 'error',
  5917. 'script' => [],
  5918. 'episode' => [],
  5919. 'answer' => '',
  5920. 'reasoning' => '',
  5921. 'usage' => [],
  5922. 'error' => '接口返回数据异常,请重新请求'
  5923. ];
  5924. return;
  5925. }
  5926. // 处理流式输出
  5927. foreach ($streamGenerator as $chunk) {
  5928. if (isset($chunk['type'])) {
  5929. if ($chunk['type'] === 'done') {
  5930. // 最终结果
  5931. $fullContent = $chunk['full_content'];
  5932. $fullReasoningContent = $chunk['full_reasoning'];
  5933. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5934. } else {
  5935. // 逐块yield数据
  5936. yield $chunk;
  5937. }
  5938. }
  5939. }
  5940. } catch (\Exception $e) {
  5941. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5942. 'model' => $model,
  5943. 'anime_id' => $anime_id,
  5944. 'trace' => $e->getTraceAsString()
  5945. ]);
  5946. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5947. 'error' => $e->getMessage(),
  5948. 'model' => $model
  5949. ]);
  5950. yield [
  5951. 'type' => 'error',
  5952. 'script' => [],
  5953. 'episode' => [],
  5954. 'answer' => '',
  5955. 'reasoning' => '',
  5956. 'usage' => [],
  5957. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5958. ];
  5959. return;
  5960. }
  5961. dLog('deepseek')->info('完整内容: '.$fullContent);
  5962. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5963. // 处理完整内容并返回最终结果
  5964. $script_arr = [];
  5965. if ($fullContent) {
  5966. $script_arr = handleScriptContent($fullContent);
  5967. dLog('deepseek')->info('解析内容', $script_arr);
  5968. logDB('deepseek', 'info', '解析内容', $script_arr);
  5969. }
  5970. if (empty($script_arr['roles'])) {
  5971. // 未生成剧本相关内容,保存对话记录并返回提示
  5972. dLog('deepseek')->info('未生成剧本相关的内容');
  5973. try {
  5974. DB::beginTransaction();
  5975. $now = date('Y-m-d H:i:s');
  5976. // 保存对话记录
  5977. $records = [
  5978. [
  5979. 'uid' => $uid,
  5980. 'anime_id' => $anime_id,
  5981. 'sequence' => 0,
  5982. 'role' => 'user',
  5983. 'content' => $prompt,
  5984. 'created_at' => $now,
  5985. 'updated_at' => $now
  5986. ],
  5987. [
  5988. 'uid' => $uid,
  5989. 'anime_id' => $anime_id,
  5990. 'sequence' => 0,
  5991. 'role' => 'assistant',
  5992. // 'content' => $fullContent,
  5993. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5994. 'created_at' => $now,
  5995. 'updated_at' => $now
  5996. ]
  5997. ];
  5998. DB::table('mp_anime_records')->insert($records);
  5999. DB::commit();
  6000. } catch (\Exception $e) {
  6001. DB::rollBack();
  6002. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6003. }
  6004. yield [
  6005. 'type' => 'done',
  6006. 'script' => [],
  6007. 'episode' => [],
  6008. 'answer' => $fullContent,
  6009. 'reasoning' => $fullReasoningContent,
  6010. 'usage' => $usage,
  6011. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6012. ];
  6013. return;
  6014. }
  6015. // 如果需要生成原文内容,从script_arr中提取
  6016. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6017. $content = $script_arr['content'];
  6018. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6019. if (!$content) {
  6020. yield [
  6021. 'type' => 'done',
  6022. 'script' => [],
  6023. 'episode' => [],
  6024. 'answer' => $fullContent,
  6025. 'reasoning' => $fullReasoningContent,
  6026. 'usage' => $usage,
  6027. 'error' => '未生成剧本内容,请调整提示词再试'
  6028. ];
  6029. return;
  6030. }
  6031. }
  6032. // 替换美术风格
  6033. if ($mappedArtStyle !== '') {
  6034. $script_arr['art_style'] = $mappedArtStyle;
  6035. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6036. }
  6037. // 新建动漫
  6038. if ($user_anime_name == '新剧本策划') {
  6039. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6040. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6041. // if (!$anime_name) {
  6042. // // 未识别到剧本名,保存对话记录并返回提示
  6043. // dLog('deepseek')->info('未能识别到剧本名称');
  6044. // try {
  6045. // DB::beginTransaction();
  6046. // $now = date('Y-m-d H:i:s');
  6047. // // 保存对话记录
  6048. // $records = [
  6049. // [
  6050. // 'uid' => $uid,
  6051. // 'anime_id' => $anime_id,
  6052. // 'sequence' => 0,
  6053. // 'role' => 'user',
  6054. // 'content' => $prompt,
  6055. // 'created_at' => $now,
  6056. // 'updated_at' => $now
  6057. // ],
  6058. // [
  6059. // 'uid' => $uid,
  6060. // 'anime_id' => $anime_id,
  6061. // 'sequence' => 0,
  6062. // 'role' => 'assistant',
  6063. // 'content' => '未能生成剧本名称,请重试',
  6064. // 'created_at' => $now,
  6065. // 'updated_at' => $now
  6066. // ]
  6067. // ];
  6068. // DB::table('mp_anime_records')->insert($records);
  6069. // DB::commit();
  6070. // } catch (\Exception $e) {
  6071. // DB::rollBack();
  6072. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6073. // }
  6074. // yield [
  6075. // 'type' => 'done',
  6076. // 'script' => [],
  6077. // 'episode' => [],
  6078. // 'answer' => $fullContent,
  6079. // 'reasoning' => $fullReasoningContent,
  6080. // 'usage' => $usage,
  6081. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6082. // ];
  6083. // return;
  6084. // }
  6085. // 确认对话名称唯一性
  6086. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6087. $anime_name = $anime_name . '_' . date('YmdHis');
  6088. }
  6089. }else {
  6090. $anime_name = $user_anime_name;
  6091. }
  6092. $table_data = [
  6093. 'user_id' => $uid,
  6094. 'anime_name' => $anime_name,
  6095. 'model' => $model,
  6096. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6097. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6098. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6099. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6100. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6101. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6102. 'art_style_type' => $input_art_style,
  6103. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6104. 'status' => '解析完成',
  6105. 'content' => $content,
  6106. 'is_multi' => $is_multi,
  6107. 'ace_mode' => $ace_mode,
  6108. 'generate_status' => '待执行',
  6109. 'updated_at' => date('Y-m-d H:i:s')
  6110. ];
  6111. if ($table_data['content']) {
  6112. $chapters = splitContent($table_data['content']);
  6113. $chapter_count = count($chapters);
  6114. if ($chapter_count > 0) {
  6115. $table_data['start_episode_sequence'] = 1;
  6116. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6117. }
  6118. }
  6119. // 如果有剧本ID则进行绑定
  6120. if ($script_id) {
  6121. $table_data['script_id'] = $script_id;
  6122. }
  6123. $single_episode = [];
  6124. try {
  6125. DB::beginTransaction();
  6126. $now = date('Y-m-d H:i:s');
  6127. // 更新动漫大纲
  6128. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6129. if (!$boolen) {
  6130. dLog('deepseek')->info('动漫保存失败', $table_data);
  6131. Utils::throwError('20003:动漫保存失败');
  6132. }
  6133. // 保存对话记录
  6134. $records = [
  6135. [
  6136. 'uid' => $uid,
  6137. 'anime_id' => $anime_id,
  6138. 'sequence' => 0,
  6139. 'role' => 'user',
  6140. 'content' => $prompt,
  6141. 'created_at' => date('Y-m-d H:i:s'),
  6142. 'updated_at' => date('Y-m-d H:i:s')
  6143. ],
  6144. [
  6145. 'uid' => $uid,
  6146. 'anime_id' => $anime_id,
  6147. 'sequence' => 0,
  6148. 'role' => 'assistant',
  6149. 'content' => $fullContent,
  6150. 'created_at' => date('Y-m-d H:i:s'),
  6151. 'updated_at' => date('Y-m-d H:i:s')
  6152. ]
  6153. ];
  6154. // 保存对话记录
  6155. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6156. if (!$boolen3) {
  6157. Utils::throwError('20003:对话记录保存失败');
  6158. }
  6159. if ($is_single) {
  6160. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6161. if (empty($episode_arr['acts'])) {
  6162. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6163. }
  6164. $saveResult = $this->saveEpisodeVersionData(
  6165. $anime_id,
  6166. 1,
  6167. $episode_arr,
  6168. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6169. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6170. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6171. null,
  6172. null,
  6173. false,
  6174. $content,
  6175. $now
  6176. );
  6177. $single_episode = $saveResult['episode'];
  6178. $episode_id = $saveResult['episode_id'];
  6179. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6180. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6181. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6182. 'props' => json_encode($saveResult['merged_props'], 256),
  6183. 'updated_at' => $now
  6184. ]);
  6185. if ($boolen5 === false) {
  6186. Utils::throwError('20003:单剧集主表资源同步失败');
  6187. }
  6188. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6189. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6190. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6191. $episode_record_content = '确认分镜大纲';
  6192. if ($content !== '') {
  6193. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6194. }
  6195. $episode_records = [
  6196. [
  6197. 'uid' => $uid,
  6198. 'anime_id' => $anime_id,
  6199. 'role' => 'user',
  6200. 'content' => $episode_record_content,
  6201. 'sequence' => 1,
  6202. 'episode_id' => $episode_id,
  6203. 'created_at' => $now,
  6204. 'updated_at' => $now
  6205. ],
  6206. [
  6207. 'uid' => $uid,
  6208. 'anime_id' => $anime_id,
  6209. 'role' => 'assistant',
  6210. 'content' => $fullContent,
  6211. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6212. 'sequence' => 1,
  6213. 'episode_id' => $episode_id,
  6214. 'created_at' => $now,
  6215. 'updated_at' => $now
  6216. ]
  6217. ];
  6218. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6219. if (!$boolen4) {
  6220. Utils::throwError('20003:单剧集分镜记录保存失败');
  6221. }
  6222. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6223. if ($is_single && !empty($single_episode)) {
  6224. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6225. 'anime_id' => $anime_id,
  6226. 'episode_id' => $episode_id ?? 0,
  6227. 'model' => $model,
  6228. 'source' => 'addChat',
  6229. ]);
  6230. }
  6231. }
  6232. }catch (\Exception $e) {
  6233. DB::rollBack();
  6234. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6235. yield [
  6236. 'type' => 'done',
  6237. 'answer' => $fullContent,
  6238. 'reasoning' => $fullReasoningContent,
  6239. 'usage' => $usage,
  6240. 'error' => $e->getMessage(),
  6241. ];
  6242. return;
  6243. }
  6244. DB::commit();
  6245. dLog('deepseek')->info('保存完毕');
  6246. if ($is_single && !empty($single_episode)) {
  6247. // $this->batchSetGlobalRoleImg([
  6248. // 'anime_id' => $anime_id,
  6249. // ]);
  6250. // $this->batchSetGlobalSceneImg([
  6251. // 'anime_id' => $anime_id,
  6252. // ]);
  6253. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6254. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6255. }
  6256. $table_data['anime_id'] = $anime_id;
  6257. $table_data['roles'] = json_decode($table_data['roles'], true);
  6258. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6259. // $table_data['episodes'] = $script_arr['episodes'];
  6260. unset($table_data['created_at']);
  6261. unset($table_data['updated_at']);
  6262. unset($table_data['status']);
  6263. dLog('deepseek')->info('开始返回');
  6264. yield [
  6265. 'type' => 'done',
  6266. 'script' => $table_data,
  6267. 'episode' => $single_episode,
  6268. 'answer' => $fullContent,
  6269. 'reasoning' => $fullReasoningContent,
  6270. 'usage' => $usage
  6271. ];
  6272. }
  6273. public function reGenerateAnime($data) {
  6274. $uid = Site::getUid();
  6275. $file = getProp($data, 'file');
  6276. $content = getProp($data, 'content', '');
  6277. $bid = getProp($data, 'bid', 0);
  6278. $script_id = getProp($data, 'script_id', 0);
  6279. $anime_id = getProp($data, 'anime_id');
  6280. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6281. if (!$anime) {
  6282. Utils::throwError('20003:该对话不存在');
  6283. }
  6284. $user_anime_name = getProp($anime, 'anime_name');
  6285. $prompt = getProp($data, 'prompt');
  6286. // 处理文本模型
  6287. $model = getProp($data, 'model');
  6288. if (!$model) {
  6289. // 用户没有输入,从anime表获取
  6290. $model = getProp($anime, 'model');
  6291. if (!$model) {
  6292. // anime表也没有,使用默认值
  6293. $model = 'doubao-seed-2-0-mini-260215';
  6294. }
  6295. }
  6296. // 验证模型是否在可用模型表中
  6297. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6298. $model = 'doubao-seed-2-0-mini-260215';
  6299. }
  6300. $is_multi = getProp($anime, 'is_multi', 1);
  6301. $is_single = (int)$is_multi !== 1;
  6302. // 积分余额预检(仅单剧集模式收费)
  6303. if ($is_single) {
  6304. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6305. }
  6306. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6307. if ($is_single) {
  6308. $episode_exists = DB::table('mp_anime_episodes')
  6309. ->where('anime_id', $anime_id)
  6310. ->where('sequence', 1)
  6311. ->exists();
  6312. if ($episode_exists) {
  6313. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6314. }
  6315. }
  6316. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  6317. if ($prompt) {
  6318. $question .= "本次修改要求如下:\n{$prompt}";
  6319. }
  6320. // 提取文件内容
  6321. if ($file) {
  6322. $content = $this->extractFileContent($file);
  6323. if (!$content) {
  6324. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6325. }
  6326. } elseif ($script_id) {
  6327. $content = $this->getContentByScriptId($script_id);
  6328. if (!$content) {
  6329. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6330. }
  6331. } elseif ($bid) {
  6332. $content = $this->getContentByBid($bid);
  6333. if (!$content) {
  6334. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6335. }
  6336. } elseif ($content) {
  6337. $content = filterContent($content);
  6338. }else {
  6339. $content = filterContent(getProp($anime, 'content'));
  6340. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6341. $need_generate_content = true;
  6342. }
  6343. }
  6344. // 判断是否需要生成原文内容
  6345. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6346. // 如果需要生成原文内容,添加额外的要求
  6347. $content_generation_requirement = $need_generate_content
  6348. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6349. : "";
  6350. // 美术风格
  6351. $input_art_style = getProp($anime, 'art_style');
  6352. if (!$input_art_style) {
  6353. $input_art_style = getProp($data, 'art_style');
  6354. }
  6355. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6356. // 美术风格
  6357. if (!$mappedArtStyle) {
  6358. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6359. }else {
  6360. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6361. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6362. }else {
  6363. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6364. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6365. }
  6366. }
  6367. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6368. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6369. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6370. 中年女:邻居阿姨
  6371. 老年男:幽默大爷
  6372. 老年女:婆婆
  6373. 萌娃:奶气萌娃";
  6374. $system_message = ['role'=>'system', 'content'=>$is_single
  6375. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6376. 强制要求:
  6377. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6378. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6379. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6380. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6381. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6382. 普通要求:
  6383. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6384. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6385. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6386. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6387. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6388. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6389. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6390. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6391. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6392. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6393. 3.$mappedArtStyle_prompt\n\n
  6394. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6395. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6396. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6397. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6398. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  6399. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6400. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6401. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6402. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6403. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6404. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6405. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6406. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6407. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6408. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  6409. 示例如下:\n
  6410. ###剧本名:西昆仑
  6411. ###故事梗概
  6412. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6413. ###剧本亮点
  6414. 亮点1:绝境奇药,生死一线
  6415. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6416. 亮点2:结拜兄妹,化解尴尬
  6417. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6418. 亮点3:纤发夺命,情愫暗涌
  6419. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6420. ###人物关系
  6421. 阿雪与梁萧之间存在兄妹之情。
  6422. ###核心矛盾
  6423. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6424. ###主体列表
  6425. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6426. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6427. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6428. 姿态:站立。}{{甜心小美}}
  6429. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6430. 全景,正面拍摄,青年女性,亚洲人。
  6431. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6432. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6433. 姿态:站立。}{{阳光青年}}
  6434. ###美术风格
  6435. 基础画风风格词:厚涂古风
  6436. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6437. ###场景列表
  6438. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6439. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6440. 无人物。}
  6441. ###分镜剧本
  6442. ##第1幕:徐家老旧厨房 白天 室内
  6443. 分镜1
  6444. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6445. 场景:徐家老旧厨房
  6446. 构图设计:全景,低角度仰视
  6447. 运镜调度:手持拍摄
  6448. 配音角色:旁白
  6449. 出镜角色:许芸-校服装、徐母
  6450. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6451. 画面类型:普通画面
  6452. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6453. 分镜2
  6454. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6455. 场景:徐家老旧厨房
  6456. 构图设计:近景,徐母面部特写
  6457. 运镜调度:固定镜头
  6458. 配音角色:徐母
  6459. 出镜角色:徐母
  6460. 台词内容:问我夜不归宿死哪儿去了。
  6461. 画面类型:对口型
  6462. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6463. ##第2幕:徐家简陋客厅 黄昏 室内
  6464. 分镜3
  6465. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6466. 场景:徐家简陋客厅
  6467. 构图设计:全景,景深虚化
  6468. 运镜调度:固定镜头
  6469. 配音角色:旁白
  6470. 出镜角色:无
  6471. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6472. 画面类型:普通画面
  6473. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6474. 分镜4
  6475. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6476. 场景:徐家简陋客厅
  6477. 构图设计:特写,火车票
  6478. 运镜调度:固定镜头
  6479. 配音角色:旁白
  6480. 出镜角色:无
  6481. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6482. 画面类型:普通画面
  6483. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  6484. "
  6485. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6486. 强制要求:\n
  6487. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6488. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6489. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6490. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6491. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6492. 普通要求:\n
  6493. 1.剧本名(必须生成)必须与文档内容高度相关
  6494. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6495. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6496. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6497. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6498. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6499. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6500. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6501. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6502. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6503. 4.$mappedArtStyle_prompt\n\n
  6504. 示例如下:\n
  6505. ###剧本名:西昆仑
  6506. ###故事梗概
  6507. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6508. ###剧本亮点
  6509. 亮点1:绝境奇药,生死一线
  6510. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6511. 亮点2:结拜兄妹,化解尴尬
  6512. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6513. 亮点3:纤发夺命,情愫暗涌
  6514. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6515. ###人物关系
  6516. 阿雪与梁萧之间存在兄妹之情。
  6517. ###核心矛盾
  6518. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6519. ###主体列表
  6520. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6521. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6522. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6523. 姿态:站立。}{{甜心小美}}
  6524. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6525. 全景,正面拍摄,青年女性,亚洲人。
  6526. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6527. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6528. 姿态:站立。}{{阳光青年}}
  6529. ###美术风格
  6530. 基础画风风格词:厚涂古风
  6531. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6532. ###场景列表
  6533. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6534. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6535. 无人物。}"];
  6536. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6537. $episode_count = $this->extractEpisodeNumber($prompt);
  6538. if ((int)getProp($anime, 'is_multi') !== 1) {
  6539. yield [
  6540. 'type' => 'done',
  6541. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6542. 'reasoning' => '',
  6543. 'usage' => []
  6544. ];
  6545. return;
  6546. }
  6547. if ($episode_count) {
  6548. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6549. $system_message = [
  6550. 'role' => 'system',
  6551. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6552. 强制要求:\n
  6553. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6554. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6555. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6556. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6557. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6558. 普通要求:\n
  6559. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6560. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6561. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6562. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6563. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6564. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6565. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6566. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6567. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6568. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6569. 示例如下:\n
  6570. ###剧本名:西昆仑
  6571. ###故事梗概
  6572. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6573. ###剧本亮点
  6574. 亮点1:绝境奇药,生死一线
  6575. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6576. 亮点2:结拜兄妹,化解尴尬
  6577. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6578. 亮点3:纤发夺命,情愫暗涌
  6579. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6580. ###人物关系
  6581. 阿雪与梁萧之间存在兄妹之情。
  6582. ###核心矛盾
  6583. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6584. ###主体列表
  6585. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6586. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6587. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6588. 姿态:站立。}{{甜心小美}}
  6589. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6590. 全景,正面拍摄,青年女性,亚洲人。
  6591. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6592. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6593. 姿态:站立。}{{阳光青年}}
  6594. ###美术风格
  6595. 基础画风风格词:厚涂古风
  6596. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6597. ###场景列表
  6598. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6599. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6600. 无人物。}
  6601. ###分集详细内容
  6602. ##第1章 重生
  6603. 我重生了。
  6604. 源于一个男人偏执的暗恋。
  6605. ##第2章 相救
  6606. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6607. 我眼睛扫向站在锅炉后的卞大伟。"
  6608. ];
  6609. // 构建消息
  6610. $messages = [
  6611. $system_message,
  6612. [
  6613. 'role' => 'user',
  6614. 'content' => "以下是文档内容:
  6615. {$content}
  6616. 用户问题:
  6617. {$question}"
  6618. ]
  6619. ];
  6620. }else {
  6621. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6622. // 构建消息
  6623. $messages = [
  6624. $system_message,
  6625. [
  6626. 'role' => 'user',
  6627. 'content' => "以下是文档内容:
  6628. {$content}
  6629. 用户问题:
  6630. {$question}"
  6631. ]
  6632. ];
  6633. }else {
  6634. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6635. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6636. return (array)$value;
  6637. })->toArray();
  6638. array_unshift($messages, $system_message);
  6639. $messages[] = [
  6640. 'role' => 'user',
  6641. 'content' => $prompt
  6642. ];
  6643. }
  6644. }
  6645. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6646. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6647. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6648. if ($model === 'deepseek-chat') {
  6649. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6650. $model = 'deepseek-v4-flash';
  6651. $thinkingMode = 'disabled';
  6652. } elseif ($model === 'deepseek-reasoner') {
  6653. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6654. $model = 'deepseek-v4-flash';
  6655. $thinkingMode = 'enabled';
  6656. }
  6657. $post_data = [
  6658. 'model' => $model,
  6659. 'messages' => $messages,
  6660. // 'max_tokens' => 8192,
  6661. 'temperature' => 0.7,
  6662. 'frequency_penalty' => 0,
  6663. 'presence_penalty' => 0,
  6664. 'response_format' => ['type' => 'text'],
  6665. 'thinking' => ['type' => $thinkingMode],
  6666. 'stream' => true // 启用流式输出
  6667. ];
  6668. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6669. // 根据模型类型选择调用方法
  6670. $fullContent = '';
  6671. $fullReasoningContent = '';
  6672. $usage = [];
  6673. // dd($post_data);
  6674. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6675. try {
  6676. $streamGenerator = $this->dispatchStreamByModel($post_data);
  6677. // 验证返回值类型
  6678. if (!is_iterable($streamGenerator)) {
  6679. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6680. dLog('deepseek')->error('方法名流式生成器无效', [
  6681. 'generator_type' => $errorType,
  6682. 'model' => $model,
  6683. // 添加其他上下文信息
  6684. ]);
  6685. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6686. 'type' => $errorType,
  6687. 'model' => $model
  6688. ]);
  6689. yield [
  6690. 'type' => 'error',
  6691. // 根据方法返回相应的空数据结构
  6692. 'answer' => '',
  6693. 'reasoning' => '',
  6694. 'usage' => [],
  6695. 'error' => '接口返回数据异常,请重新请求'
  6696. ];
  6697. return;
  6698. }
  6699. // 处理流式输出
  6700. foreach ($streamGenerator as $chunk) {
  6701. if (isset($chunk['type'])) {
  6702. if ($chunk['type'] === 'done') {
  6703. $fullContent = $chunk['full_content'];
  6704. $fullReasoningContent = $chunk['full_reasoning'];
  6705. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6706. } else {
  6707. yield $chunk;
  6708. }
  6709. }
  6710. }
  6711. } catch (\Exception $e) {
  6712. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6713. 'model' => $model,
  6714. 'trace' => $e->getTraceAsString()
  6715. ]);
  6716. logDB('deepseek', 'error', '方法名流式处理失败', [
  6717. 'error' => $e->getMessage(),
  6718. 'model' => $model
  6719. ]);
  6720. yield [
  6721. 'type' => 'error',
  6722. // 根据方法返回相应的空数据结构
  6723. 'answer' => '',
  6724. 'reasoning' => '',
  6725. 'usage' => [],
  6726. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6727. ];
  6728. return;
  6729. }
  6730. dLog('deepseek')->info('完整内容: '.$fullContent);
  6731. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6732. // 处理完整内容并返回最终结果
  6733. $script_arr = [];
  6734. if ($fullContent) {
  6735. $script_arr = handleScriptContent($fullContent);
  6736. dLog('deepseek')->info('解析内容', $script_arr);
  6737. logDB('deepseek', 'info', '解析内容', $script_arr);
  6738. }
  6739. if (empty($script_arr['roles'])) {
  6740. // 未生成剧本相关内容,保存对话记录并返回提示
  6741. dLog('deepseek')->info('未生成剧本相关的内容');
  6742. try {
  6743. $now = date('Y-m-d H:i:s');
  6744. // 保存对话记录
  6745. $records = [
  6746. [
  6747. 'uid' => $uid,
  6748. 'anime_id' => $anime_id,
  6749. 'sequence' => 0,
  6750. 'role' => 'user',
  6751. 'content' => $prompt,
  6752. 'created_at' => $now,
  6753. 'updated_at' => $now
  6754. ],
  6755. [
  6756. 'uid' => $uid,
  6757. 'anime_id' => $anime_id,
  6758. 'sequence' => 0,
  6759. 'role' => 'assistant',
  6760. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6761. 'created_at' => $now,
  6762. 'updated_at' => $now
  6763. ]
  6764. ];
  6765. DB::table('mp_anime_records')->insert($records);
  6766. } catch (\Exception $e) {
  6767. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6768. }
  6769. yield [
  6770. 'type' => 'done',
  6771. 'script' => [],
  6772. 'episode' => [],
  6773. 'answer' => $fullContent,
  6774. 'reasoning' => $fullReasoningContent,
  6775. 'usage' => $usage,
  6776. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6777. ];
  6778. return;
  6779. }
  6780. // 替换美术风格
  6781. if ($mappedArtStyle !== '') {
  6782. $script_arr['art_style'] = $mappedArtStyle;
  6783. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6784. }
  6785. if ($user_anime_name != '新剧本策划') {
  6786. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6787. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6788. // 确认对话名称唯一性
  6789. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6790. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6791. }
  6792. }else {
  6793. $anime_name = $user_anime_name;
  6794. }
  6795. $table_data = [
  6796. 'user_id' => $uid,
  6797. 'model' => $model,
  6798. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6799. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6800. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6801. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6802. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6803. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6804. 'art_style_type' => $input_art_style,
  6805. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6806. 'status' => '解析完成',
  6807. 'generate_status' => '待执行',
  6808. 'updated_at' => date('Y-m-d H:i:s')
  6809. ];
  6810. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6811. // 如果是修改集数,则将content内容更新(会改变原文)
  6812. if (isset($episode_count) && $episode_count > 0) {
  6813. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6814. $table_data['start_episode_sequence'] = 1;
  6815. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6816. }else {
  6817. // 如果需要生成原文内容,从script_arr中提取
  6818. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6819. $table_data['content'] = $script_arr['content'];
  6820. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6821. if (!$table_data['content']) {
  6822. yield [
  6823. 'type' => 'done',
  6824. 'script' => [],
  6825. 'episode' => [],
  6826. 'answer' => $fullContent,
  6827. 'reasoning' => $fullReasoningContent,
  6828. 'usage' => $usage,
  6829. 'error' => '未生成剧本内容,请调整提示词再试'
  6830. ];
  6831. return;
  6832. }
  6833. }
  6834. if (isset($table_data['content']) && $table_data['content']) {
  6835. $chapters = splitContent($table_data['content']);
  6836. $chapter_count = count($chapters);
  6837. if ($chapter_count > 0) {
  6838. $table_data['start_episode_sequence'] = 1;
  6839. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6840. }
  6841. }
  6842. }
  6843. $single_episode = [];
  6844. try {
  6845. DB::beginTransaction();
  6846. $now = date('Y-m-d H:i:s');
  6847. // 更新动漫大纲
  6848. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6849. if (!$boolen) {
  6850. dLog('deepseek')->info('对话修改失败', $table_data);
  6851. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6852. Utils::throwError('20003:对话修改失败');
  6853. }
  6854. // 保存对话记录
  6855. $records = [
  6856. [
  6857. 'uid' => $uid,
  6858. 'anime_id' => $anime_id,
  6859. 'sequence' => 0,
  6860. 'role' => 'user',
  6861. 'content' => $prompt,
  6862. 'created_at' => $now,
  6863. 'updated_at' => $now
  6864. ],
  6865. [
  6866. 'uid' => $uid,
  6867. 'anime_id' => $anime_id,
  6868. 'sequence' => 0,
  6869. 'role' => 'assistant',
  6870. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6871. 'content' => $fullContent,
  6872. 'created_at' => $now,
  6873. 'updated_at' => $now
  6874. ]
  6875. ];
  6876. // 保存对话记录
  6877. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6878. if (!$boolen3) {
  6879. Utils::throwError('20003:对话记录保存失败');
  6880. }
  6881. // 单剧集模式:生成并保存剧集信息
  6882. if ($is_single) {
  6883. $anime_name = getProp($anime, 'anime_name', '未命名');
  6884. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6885. if (empty($episode_arr['acts'])) {
  6886. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6887. }
  6888. $saveResult = $this->saveEpisodeVersionData(
  6889. $anime_id,
  6890. 1,
  6891. $episode_arr,
  6892. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6893. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6894. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6895. null,
  6896. null,
  6897. false,
  6898. $content,
  6899. $now
  6900. );
  6901. $single_episode = $saveResult['episode'];
  6902. $episode_id = $saveResult['episode_id'];
  6903. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6904. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6905. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6906. 'props' => json_encode($saveResult['merged_props'], 256),
  6907. 'updated_at' => $now
  6908. ]);
  6909. if ($boolen5 === false) {
  6910. Utils::throwError('20003:单剧集主表资源同步失败');
  6911. }
  6912. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6913. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6914. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6915. $episode_record_content = '确认分镜大纲';
  6916. if ($content !== '') {
  6917. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6918. }
  6919. $episode_records = [
  6920. [
  6921. 'uid' => $uid,
  6922. 'anime_id' => $anime_id,
  6923. 'role' => 'user',
  6924. 'content' => $episode_record_content,
  6925. 'sequence' => 1,
  6926. 'episode_id' => $episode_id,
  6927. 'created_at' => $now,
  6928. 'updated_at' => $now
  6929. ],
  6930. [
  6931. 'uid' => $uid,
  6932. 'anime_id' => $anime_id,
  6933. 'role' => 'assistant',
  6934. 'content' => $fullContent,
  6935. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6936. 'sequence' => 1,
  6937. 'episode_id' => $episode_id,
  6938. 'created_at' => $now,
  6939. 'updated_at' => $now
  6940. ]
  6941. ];
  6942. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6943. if (!$boolen4) {
  6944. Utils::throwError('20003:单剧集分镜记录保存失败');
  6945. }
  6946. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6947. if ($is_single && !empty($single_episode)) {
  6948. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6949. 'anime_id' => $anime_id,
  6950. 'episode_id' => $episode_id ?? 0,
  6951. 'model' => $model,
  6952. 'source' => 'reGenerateAnime',
  6953. ]);
  6954. }
  6955. }
  6956. }catch (\Exception $e) {
  6957. DB::rollBack();
  6958. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6959. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6960. yield [
  6961. 'type' => 'done',
  6962. 'answer' => $fullContent,
  6963. 'reasoning' => $fullReasoningContent,
  6964. 'usage' => $usage,
  6965. 'error' => $e->getMessage(),
  6966. ];
  6967. return;
  6968. }
  6969. DB::commit();
  6970. dLog('deepseek')->info('保存完毕');
  6971. if ($is_single && !empty($single_episode)) {
  6972. // $this->batchSetGlobalRoleImg([
  6973. // 'anime_id' => $anime_id,
  6974. // ]);
  6975. // $this->batchSetGlobalSceneImg([
  6976. // 'anime_id' => $anime_id,
  6977. // ]);
  6978. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6979. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6980. }
  6981. $table_data['anime_id'] = $anime_id;
  6982. $table_data['roles'] = json_decode($table_data['roles'], true);
  6983. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6984. unset($table_data['updated_at']);
  6985. unset($table_data['status']);
  6986. yield [
  6987. 'type' => 'done',
  6988. 'script' => $table_data,
  6989. 'episode' => $single_episode,
  6990. 'answer' => $fullContent,
  6991. 'reasoning' => $fullReasoningContent,
  6992. 'usage' => $usage
  6993. ];
  6994. }
  6995. public function chat($data) {
  6996. $uid = Site::getUid();
  6997. // 积分余额预检(不足直接报错)
  6998. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6999. $anime_id = getProp($data, 'anime_id');
  7000. $file = getProp($data, 'file');
  7001. $content = getProp($data, 'content', '');
  7002. $bid = getProp($data, 'bid', 0);
  7003. $script_id = getProp($data, 'script_id', 0);
  7004. $episode_number = getProp($data, 'episode_number', 1);
  7005. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7006. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7007. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7008. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7009. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7010. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7011. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7012. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7013. $roles = is_array($roles) ? $roles : [];
  7014. $scenes = is_array($scenes) ? $scenes : [];
  7015. // 获取最后一集序号
  7016. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  7017. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7018. // 转换主体列表和场景列表的格式
  7019. // 获取参考主体或场景
  7020. if ((int)$episode_number === 1) {
  7021. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7022. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7023. }else {
  7024. $prev_episode_number = $episode_number - 1;
  7025. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7026. }
  7027. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7028. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7029. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7030. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7031. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  7032. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  7033. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  7034. 中年女:邻居阿姨
  7035. 老年男:幽默大爷
  7036. 老年女:婆婆
  7037. 萌娃:奶气萌娃";
  7038. if ($roles_content) {
  7039. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7040. 主体范围:\n {$roles_content}\n
  7041. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7042. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7043. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7044. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7045. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7046. }else {
  7047. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7048. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7049. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7050. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7051. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7052. }
  7053. if ($scenes_content) {
  7054. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7055. 场景范围:\n {$scenes_content}\n
  7056. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7057. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7058. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7059. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7060. }else {
  7061. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7062. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7063. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7064. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7065. }
  7066. // 提取文件内容
  7067. if ($file) {
  7068. $uploaded_content = $this->extractFileContent($file);
  7069. if (!$uploaded_content) {
  7070. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7071. }
  7072. } elseif ($script_id) {
  7073. $uploaded_content = $this->getContentByScriptId($script_id);
  7074. if (!$uploaded_content) {
  7075. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7076. }
  7077. } elseif ($bid) {
  7078. $uploaded_content = $this->getContentByBid($bid);
  7079. if (!$uploaded_content) {
  7080. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7081. }
  7082. } elseif ($content) {
  7083. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7084. }
  7085. // elseif ($prompt) {
  7086. // $uploaded_content = filterContent($prompt);
  7087. // }
  7088. else {
  7089. $uploaded_content = '';
  7090. }
  7091. $input_art_style = getProp($anime, 'art_style');
  7092. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7093. // 美术风格
  7094. if (!$mappedArtStyle) {
  7095. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7096. }else {
  7097. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7098. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7099. }else {
  7100. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7101. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7102. }
  7103. }
  7104. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7105. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7106. // 强制要求:
  7107. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7108. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7109. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7110. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7111. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  7112. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  7113. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7114. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7115. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7116. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7117. // - 分镜要和场景列表、人物主体保持一致\n
  7118. // 普通要求:
  7119. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7120. // {$role_demo}
  7121. // {$scene_demo}
  7122. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7123. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7124. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7125. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  7126. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7127. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7128. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7129. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7130. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7131. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7132. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7133. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7134. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7135. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7136. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7137. // 5.$mappedArtStyle_prompt\n\n
  7138. // 示例格式:\n
  7139. // 第1集:隐形的守护者
  7140. // ###故事梗概
  7141. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7142. // ###美术风格
  7143. // 基础画风风格词:韩漫二次元
  7144. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7145. // ###主体列表
  7146. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7147. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7148. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7149. // ###场景列表
  7150. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7151. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7152. // 无人物。}
  7153. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7154. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7155. // 无人物。}
  7156. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7157. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7158. // 无人物。}
  7159. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7160. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7161. // 无人物。}
  7162. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7163. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7164. // 无人物。}
  7165. // ###分镜剧本
  7166. // ##第1幕:徐家老旧厨房 白天 室内
  7167. // 分镜1
  7168. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7169. // 场景:徐家老旧厨房
  7170. // 构图设计:全景,低角度仰视
  7171. // 运镜调度:手持拍摄
  7172. // 配音角色:旁白
  7173. // 出镜角色:许芸-校服装、徐母
  7174. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7175. // 画面类型:普通画面
  7176. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7177. // 分镜2
  7178. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7179. // 场景:徐家老旧厨房
  7180. // 构图设计:近景,徐母面部特写
  7181. // 运镜调度:固定镜头
  7182. // 配音角色:徐母
  7183. // 出镜角色:徐母
  7184. // 台词内容:问我夜不归宿死哪儿去了。
  7185. // 画面类型:对口型
  7186. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7187. // ##第2幕:徐家简陋客厅 黄昏 室内
  7188. // 分镜3
  7189. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7190. // 场景:徐家简陋客厅
  7191. // 构图设计:全景,景深虚化
  7192. // 运镜调度:固定镜头
  7193. // 配音角色:旁白
  7194. // 出镜角色:无
  7195. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7196. // 画面类型:普通画面
  7197. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7198. // 分镜4
  7199. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7200. // 场景:徐家简陋客厅
  7201. // 构图设计:特写,火车票
  7202. // 运镜调度:固定镜头
  7203. // 配音角色:旁白
  7204. // 出镜角色:无
  7205. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7206. // 画面类型:普通画面
  7207. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7208. // \n\n";
  7209. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7210. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7211. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  7212. 普通要求:
  7213. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7214. {$role_demo}
  7215. {$scene_demo}
  7216. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7217. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7218. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7219. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7220. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7221. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7222. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7223. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7224. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7225. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7226. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7227. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7228. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7229. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7230. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7231. 5.$mappedArtStyle_prompt
  7232. 6.《情绪-视听语言映射表》:
  7233. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7234. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7235. -----|---------|------------|----------------
  7236. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7237. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7238. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7239. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7240. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7241. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7242. -----|---------|------------|----------------
  7243. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7244. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7245. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7246. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7247. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7248. --------|---------|--------------|-------------
  7249. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7250. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7251. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7252. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7253. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7254. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7255. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7256. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7257. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7258. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7259. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7260. -----|---------|------------|------------
  7261. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7262. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7263. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7264. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7265. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7266. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7267. --------|---------|--------------|----------
  7268. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7269. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7270. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7271. 6.6 声音设计与潜意识影响 (Soundscape)
  7272. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7273. -----|---------|------------|------------------
  7274. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7275. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7276. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7277. 理论基石:
  7278. - The Five C's of Cinematography by Joseph V. Mascelli
  7279. - Film Art: An Introduction by David Bordwell
  7280. - Sight, Sound, Motion by Herbert Zettl
  7281. - Notes on the Cinematograph by Robert Bresson
  7282. \n\n
  7283. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  7284. 示例格式:\n
  7285. 第1集:隐形的守护者
  7286. ###故事梗概
  7287. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7288. ###美术风格
  7289. 基础画风风格词:韩漫二次元
  7290. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7291. ###主体列表
  7292. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7293. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7294. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7295. ###场景列表
  7296. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7297. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7298. 无人物。}
  7299. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7300. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7301. 无人物。}
  7302. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7303. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7304. 无人物。}
  7305. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7306. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7307. 无人物。}
  7308. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7309. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7310. 无人物。}
  7311. ###分镜剧本
  7312. ##第1幕:徐家老旧厨房 白天 室内
  7313. 分镜1
  7314. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7315. 场景:徐家老旧厨房
  7316. 构图设计:全景,低角度仰视
  7317. 运镜调度:手持拍摄
  7318. 配音角色:旁白
  7319. 出镜角色:许芸-校服装、徐母
  7320. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7321. 画面类型:普通画面
  7322. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7323. 分镜2
  7324. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7325. 场景:徐家老旧厨房
  7326. 构图设计:近景,徐母面部特写
  7327. 运镜调度:固定镜头
  7328. 配音角色:徐母
  7329. 出镜角色:徐母
  7330. 台词内容:问我夜不归宿死哪儿去了。
  7331. 画面类型:对口型
  7332. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7333. ##第2幕:徐家简陋客厅 黄昏 室内
  7334. 分镜3
  7335. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7336. 场景:徐家简陋客厅
  7337. 构图设计:全景,景深虚化
  7338. 运镜调度:固定镜头
  7339. 配音角色:旁白
  7340. 出镜角色:无
  7341. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7342. 画面类型:普通画面
  7343. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7344. 分镜4
  7345. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7346. 场景:徐家简陋客厅
  7347. 构图设计:特写,火车票
  7348. 运镜调度:固定镜头
  7349. 配音角色:旁白
  7350. 出镜角色:无
  7351. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7352. 画面类型:普通画面
  7353. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7354. \n\n";
  7355. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7356. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  7357. $is_regenerate_version = true;
  7358. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7359. $prompt = $origin_prompt;
  7360. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7361. // 获取章节内容
  7362. $full_content = getProp($anime, 'content');
  7363. if ($uploaded_content) {
  7364. $full_content = $uploaded_content;
  7365. }
  7366. // 根据章节内容拆分章节
  7367. $chapters = splitContent($full_content);
  7368. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7369. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7370. $messages = [];
  7371. if ($prompt == '确认分镜大纲') {
  7372. // 暂时保留
  7373. $content = $chapter_content;
  7374. if ($is_single) $content = $full_content; // 单剧集使用全文
  7375. if (!$content) {
  7376. Utils::throwError('20003:章节内容无法获取,请确认');
  7377. }
  7378. $question = $is_single
  7379. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7380. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7381. // 构建消息
  7382. $messages[] =
  7383. [
  7384. 'role' => 'user',
  7385. 'content' => $question
  7386. ];
  7387. }else if ($prompt == '继续策划下一集') {
  7388. if ($is_single) {
  7389. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7390. }
  7391. $content = $chapter_content;
  7392. if (!$content) {
  7393. Utils::throwError('20003:章节内容无法获取,请确认');
  7394. }
  7395. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7396. // 获取上一集最后记录
  7397. $prev_sequence = $episode_number - 1;
  7398. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7399. // 构建消息
  7400. $messages[] =
  7401. [
  7402. 'role' => 'user',
  7403. 'content' => $question
  7404. ];
  7405. }else {
  7406. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7407. if (!$content) {
  7408. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7409. }
  7410. if (!$content) {
  7411. Utils::throwError('20003:章节内容无法获取,请确认');
  7412. }
  7413. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7414. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7415. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7416. if ($origin_prompt) {
  7417. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  7418. }
  7419. $messages[] =
  7420. [
  7421. 'role' => 'user',
  7422. 'content' => $question
  7423. ];
  7424. }
  7425. // 处理文本模型
  7426. $model = getProp($data, 'model');
  7427. if (!$model) {
  7428. // 用户没有输入,从anime表获取
  7429. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7430. $model = getProp($anime, 'model');
  7431. if (!$model) {
  7432. // anime表也没有,使用默认值
  7433. $model = 'doubao-seed-2-0-mini-260215';
  7434. }
  7435. }
  7436. // 验证模型是否在可用模型表中
  7437. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7438. $model = 'doubao-seed-2-0-mini-260215';
  7439. }
  7440. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7441. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7442. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7443. if ($model === 'deepseek-chat') {
  7444. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7445. $model = 'deepseek-v4-flash';
  7446. $thinkingMode = 'disabled';
  7447. } elseif ($model === 'deepseek-reasoner') {
  7448. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7449. $model = 'deepseek-v4-flash';
  7450. $thinkingMode = 'enabled';
  7451. }
  7452. $post_data = [
  7453. 'model' => $model,
  7454. 'messages' => $messages,
  7455. // 'max_tokens' => 8192,
  7456. 'temperature' => 0.2,
  7457. 'frequency_penalty' => 0,
  7458. 'presence_penalty' => 0,
  7459. 'response_format' => ['type' => 'text'],
  7460. 'thinking' => ['type' => $thinkingMode],
  7461. 'stream' => true // 启用流式输出
  7462. ];
  7463. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7464. // 根据模型类型选择调用方法
  7465. $fullContent = '';
  7466. $fullReasoningContent = '';
  7467. $usage = [];
  7468. try {
  7469. $streamGenerator = $this->dispatchStreamByModel($post_data);
  7470. // 验证返回值类型
  7471. if (!is_iterable($streamGenerator)) {
  7472. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7473. dLog('deepseek')->error('chat流式生成器无效', [
  7474. 'generator_type' => $errorType,
  7475. 'model' => $model,
  7476. 'anime_id' => $anime_id,
  7477. 'episode_number' => $episode_number
  7478. ]);
  7479. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7480. 'type' => $errorType,
  7481. 'model' => $model
  7482. ]);
  7483. yield [
  7484. 'type' => 'error',
  7485. 'episode' => [],
  7486. 'answer' => '',
  7487. 'reasoning' => '',
  7488. 'usage' => [],
  7489. 'error' => '接口返回数据异常,请重新请求'
  7490. ];
  7491. return;
  7492. }
  7493. // 处理流式输出
  7494. foreach ($streamGenerator as $chunk) {
  7495. if (isset($chunk['type'])) {
  7496. if ($chunk['type'] === 'done') {
  7497. // 最终结果
  7498. $fullContent = $chunk['full_content'];
  7499. $fullReasoningContent = $chunk['full_reasoning'];
  7500. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7501. } else {
  7502. // 逐块yield数据
  7503. yield $chunk;
  7504. }
  7505. }
  7506. }
  7507. } catch (\Exception $e) {
  7508. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7509. 'model' => $model,
  7510. 'anime_id' => $anime_id,
  7511. 'episode_number' => $episode_number,
  7512. 'trace' => $e->getTraceAsString()
  7513. ]);
  7514. logDB('deepseek', 'error', 'chat流式处理失败', [
  7515. 'error' => $e->getMessage(),
  7516. 'model' => $model
  7517. ]);
  7518. yield [
  7519. 'type' => 'error',
  7520. 'episode' => [],
  7521. 'answer' => '',
  7522. 'reasoning' => '',
  7523. 'usage' => [],
  7524. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7525. ];
  7526. return;
  7527. }
  7528. dLog('deepseek')->info('完整内容: '.$fullContent);
  7529. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7530. // 处理完整内容并返回最终结果
  7531. $episode_arr = handleEpisodeContent($fullContent);
  7532. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7533. if (empty($episode_arr['acts'])) {
  7534. // 未生成剧本相关内容,保存对话记录并返回提示
  7535. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7536. try {
  7537. $now = date('Y-m-d H:i:s');
  7538. // 保存对话记录
  7539. $records = [
  7540. [
  7541. 'uid' => $uid,
  7542. 'anime_id' => $anime_id,
  7543. 'sequence' => $episode_number,
  7544. 'role' => 'user',
  7545. 'content' => $prompt,
  7546. 'created_at' => $now,
  7547. 'updated_at' => $now
  7548. ],
  7549. [
  7550. 'uid' => $uid,
  7551. 'anime_id' => $anime_id,
  7552. 'sequence' => $episode_number,
  7553. 'role' => 'assistant',
  7554. 'content' => $fullContent,
  7555. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7556. 'created_at' => $now,
  7557. 'updated_at' => $now
  7558. ]
  7559. ];
  7560. DB::table('mp_anime_records')->insert($records);
  7561. } catch (\Exception $e) {
  7562. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7563. }
  7564. yield [
  7565. 'type' => 'done',
  7566. 'episode' => [],
  7567. 'answer' => $fullContent,
  7568. 'reasoning' => $fullReasoningContent,
  7569. 'usage' => $usage,
  7570. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7571. ];
  7572. return;
  7573. }
  7574. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7575. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7576. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7577. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7578. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7579. $existing_props = is_array($existing_props) ? $existing_props : [];
  7580. $now = date('Y-m-d H:i:s');
  7581. try {
  7582. DB::beginTransaction();
  7583. $saveResult = $this->saveEpisodeVersionData(
  7584. $anime_id,
  7585. $episode_number,
  7586. $episode_arr,
  7587. $existing_roles,
  7588. $existing_scenes,
  7589. $existing_props,
  7590. $current_episode,
  7591. $base_episode,
  7592. $is_regenerate_version,
  7593. $content,
  7594. $now
  7595. );
  7596. $episode = $saveResult['episode'];
  7597. $episode_id = $saveResult['episode_id'];
  7598. $merged_roles = $saveResult['merged_roles'];
  7599. $merged_scenes = $saveResult['merged_scenes'];
  7600. $merged_props = $saveResult['merged_props'];
  7601. $record_content = $origin_prompt;
  7602. if ($uploaded_content !== '') {
  7603. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7604. }
  7605. $records = [
  7606. [
  7607. 'uid' => $uid,
  7608. 'anime_id' => $anime_id,
  7609. 'role' => 'user',
  7610. 'content' => $record_content,
  7611. 'sequence' => $episode_number,
  7612. 'episode_id' => $episode_id,
  7613. 'created_at' => $now,
  7614. 'updated_at' => $now
  7615. ],
  7616. [
  7617. 'uid' => $uid,
  7618. 'anime_id' => $anime_id,
  7619. 'role' => 'assistant',
  7620. 'content' => $fullContent,
  7621. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7622. 'sequence' => $episode_number,
  7623. 'episode_id' => $episode_id,
  7624. 'created_at' => $now,
  7625. 'updated_at' => $now
  7626. ]
  7627. ];
  7628. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7629. if (!$boolen4) {
  7630. Utils::throwError('20003:对话记录保存失败');
  7631. }
  7632. // 保存模型和内容到anime表
  7633. $update_anime_data = [
  7634. 'model' => $model,
  7635. 'updated_at' => $now
  7636. ];
  7637. if ($uploaded_content) {
  7638. $update_anime_data['content'] = $uploaded_content;
  7639. }
  7640. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7641. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7642. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7643. 'anime_id' => $anime_id,
  7644. 'episode_number' => $episode_number,
  7645. 'model' => $model,
  7646. 'source' => 'chat',
  7647. ]);
  7648. }catch (\Exception $e) {
  7649. DB::rollBack();
  7650. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7651. yield [
  7652. 'type' => 'done',
  7653. 'answer' => $fullContent,
  7654. 'reasoning' => $fullReasoningContent,
  7655. 'usage' => $usage,
  7656. 'error' => $e->getMessage(),
  7657. ];
  7658. return;
  7659. }
  7660. DB::commit();
  7661. if ($is_global_generate_pics) {
  7662. // // 批量生成全局角色图片
  7663. // $this->batchSetGlobalRoleImg([
  7664. // 'anime_id' => $anime_id,
  7665. // ], true);
  7666. // // 批量生成全局场景图片
  7667. // $this->batchSetGlobalSceneImg([
  7668. // 'anime_id' => $anime_id,
  7669. // ], true);
  7670. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7671. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7672. }
  7673. $episode['episode_id'] = $episode_id;
  7674. $episode['roles'] = $merged_roles;
  7675. $episode['scenes'] = $merged_scenes;
  7676. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7677. yield [
  7678. 'type' => 'done',
  7679. 'episode' => $episode,
  7680. 'answer' => $fullContent,
  7681. 'reasoning' => $fullReasoningContent,
  7682. 'usage' => $usage
  7683. ];
  7684. }
  7685. public function addChatForAce($data) {
  7686. $uid = Site::getUid();
  7687. $anime_id = getProp($data, 'anime_id');
  7688. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7689. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7690. if (!$anime) Utils::throwError('20003:对话不存在');
  7691. $file = getProp($data, 'file');
  7692. $content = getProp($data, 'content', '');
  7693. $bid = getProp($data, 'bid', 0);
  7694. $script_id = getProp($data, 'script_id', 0);
  7695. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7696. $prompt = getProp($data, 'prompt');
  7697. $is_multi = getProp($anime, 'is_multi');
  7698. $is_single = (int)$is_multi !== 1;
  7699. // 积分余额预检(仅单剧集模式收费)
  7700. if ($is_single) {
  7701. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7702. }
  7703. $extra_products = getProp($data, 'products', []);
  7704. if (!$extra_products) {
  7705. $extra_products = getProp($anime, 'extra_products');
  7706. if ($extra_products) {
  7707. $extra_products = json_decode($extra_products, true);
  7708. }else {
  7709. $extra_products = [];
  7710. }
  7711. }else {
  7712. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7713. }
  7714. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7715. $anime_script_id = getProp($anime, 'script_id');
  7716. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7717. $cpid = Site::getCpid();
  7718. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7719. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7720. ->where('mapping.script_id', $anime_script_id)
  7721. ->where('product.cpid', $cpid)
  7722. ->where('product.is_deleted', 0);
  7723. $mappings = $script_products_mappings->select(
  7724. 'mapping.product_id',
  7725. 'mapping.episode_number',
  7726. 'product.product_name',
  7727. 'product.type',
  7728. 'product.product',
  7729. 'product.pic_prompt',
  7730. 'product.url',
  7731. 'product.pic_task_id',
  7732. 'product.pic_task_status',
  7733. 'product.three_view_image_url'
  7734. )
  7735. ->get();
  7736. // 按 product_id 分组,合并 episode_number
  7737. $productMap = [];
  7738. foreach ($mappings as $item) {
  7739. $product_id = $item->product_id;
  7740. $product_name = $item->product_name;
  7741. // 处理product_name两边的符号
  7742. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7743. if (!isset($productMap[$product_id])) {
  7744. $productMap[$product_id] = [
  7745. 'product_id' => $product_id,
  7746. 'product_name' => $product_name,
  7747. 'type' => (int)$item->type,
  7748. 'product' => (int)$item->product,
  7749. 'pic_prompt' => $item->pic_prompt,
  7750. 'url' => $item->url,
  7751. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7752. 'pic_task_id' => $item->pic_task_id,
  7753. 'pic_task_status' => $item->pic_task_status,
  7754. 'episode_numbers' => [],
  7755. ];
  7756. }
  7757. // 添加 episode_number(去重)
  7758. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7759. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7760. }
  7761. }
  7762. // 将查询到的剧本资产合并到extra_products中
  7763. // 先构建extra_products的索引(以product_id为key,用于去重)
  7764. $extraProductsMap = [];
  7765. foreach ($extra_products as $item) {
  7766. $key = getProp($item, 'product_id');
  7767. if ($key) {
  7768. $extraProductsMap[$key] = $item;
  7769. }
  7770. }
  7771. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7772. foreach ($productMap as $product) {
  7773. $product_id = $product['product_id'];
  7774. // 如果不存在则添加(不带episode_number信息)
  7775. if (!isset($extraProductsMap[$product_id])) {
  7776. $extraProductsMap[$product_id] = [
  7777. 'product_id' => $product['product_id'],
  7778. 'product_name' => $product['product_name'],
  7779. 'type' => $product['type'],
  7780. 'product' => $product['product'],
  7781. 'pic_prompt' => $product['pic_prompt'],
  7782. 'url' => $product['url'],
  7783. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  7784. 'pic_task_id' => $product['pic_task_id'],
  7785. 'pic_task_status' => $product['pic_task_status'],
  7786. ];
  7787. }
  7788. }
  7789. // 重新赋值给extra_products
  7790. $extra_products = array_values($extraProductsMap);
  7791. }
  7792. $user_anime_name = getProp($anime, 'anime_name');
  7793. // 处理提示词
  7794. if ($prompt && $extra_products) {
  7795. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7796. foreach($extra_products as $item) {
  7797. $product_name = getProp($item, 'product_name');
  7798. if ($product_name) {
  7799. // 替换 {product_name} 为 product_name
  7800. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7801. }
  7802. }
  7803. }
  7804. // 处理文本模型
  7805. $model = getProp($data, 'model');
  7806. if (!$model) {
  7807. // 用户没有输入,从anime表获取
  7808. $model = getProp($anime, 'model');
  7809. if (!$model) {
  7810. // anime表也没有,使用默认值
  7811. $model = 'deepseek-v4-pro';
  7812. }
  7813. }
  7814. // 验证模型是否在可用模型表中
  7815. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7816. $model = 'deepseek-v4-pro';
  7817. }
  7818. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7819. if ($prompt) {
  7820. $question .= "本次修改要求如下:\n{$prompt}";
  7821. }
  7822. // if (!$file && !$content && !$bid) {
  7823. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7824. // }
  7825. // 提取文件内容
  7826. if ($file) {
  7827. $content = $this->extractFileContent($file);
  7828. if (!$content) {
  7829. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7830. }
  7831. } elseif ($script_id) {
  7832. $content = $this->getContentByScriptId($script_id);
  7833. if (!$content) {
  7834. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7835. }
  7836. } elseif ($bid) {
  7837. $content = $this->getContentByBid($bid);
  7838. if (!$content) {
  7839. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7840. }
  7841. } elseif ($content) {
  7842. $content = filterContent($content);
  7843. } else {
  7844. $content = getProp($anime, 'content');
  7845. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7846. $need_generate_content = true;
  7847. }
  7848. }
  7849. // 美术风格
  7850. $input_art_style = getProp($data, 'art_style');
  7851. if (!$input_art_style) {
  7852. $mappedArtStyle = getProp($anime, 'art_style');
  7853. }else {
  7854. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7855. }
  7856. // 判断是否需要生成原文内容
  7857. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7858. // 如果需要生成原文内容,添加额外的要求
  7859. $content_generation_requirement = $need_generate_content
  7860. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7861. : "";
  7862. // 美术风格
  7863. if (!$mappedArtStyle) {
  7864. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7865. }else {
  7866. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7867. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7868. }else {
  7869. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7870. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7871. }
  7872. }
  7873. // 构建主体、场景和道具提示词
  7874. $extra_role_prompt = "\n";
  7875. $extra_scene_prompt = "\n";
  7876. $extra_prop_prompt = "\n";
  7877. $extra_roles = [];
  7878. $extra_scenes = [];
  7879. $extra_props = [];
  7880. $ref_products = []; // 参考资产
  7881. if ($extra_products) {
  7882. foreach($extra_products as $item) {
  7883. $product = getProp($item, 'product');
  7884. $product_name = getProp($item, 'product_name');
  7885. if ($product_name == '旁白') continue;
  7886. $ref_products[$product_name] = $item;
  7887. $pic_prompt = getProp($item, 'pic_prompt');
  7888. if ((int)$product === 1) {
  7889. // 拼接角色信息
  7890. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7891. $extra_roles[$product_name] = [
  7892. 'role' => $product_name,
  7893. 'pic_prompt' => $pic_prompt,
  7894. 'url' => getProp($item, 'url', ''),
  7895. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7896. ];
  7897. } elseif ((int)$product === 2) {
  7898. // 拼接场景信息
  7899. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7900. $extra_scenes[$product_name] = [
  7901. 'scene' => $product_name,
  7902. 'pic_prompt' => $pic_prompt,
  7903. 'url' => getProp($item, 'url', ''),
  7904. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7905. ];
  7906. } elseif ((int)$product === 3) {
  7907. // 拼接道具信息
  7908. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7909. $extra_props[$product_name] = [
  7910. 'prop' => $product_name,
  7911. 'pic_prompt' => $pic_prompt,
  7912. 'url' => getProp($item, 'url', ''),
  7913. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7914. ];
  7915. }
  7916. }
  7917. // 优化提示词,融入剧本
  7918. if (!empty(trim($extra_role_prompt))) {
  7919. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7920. }
  7921. if (!empty(trim($extra_scene_prompt))) {
  7922. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7923. }
  7924. if (!empty(trim($extra_prop_prompt))) {
  7925. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7926. }
  7927. }
  7928. if ($anime_script_id && $is_single) {
  7929. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7930. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7931. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7932. }else {
  7933. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7934. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7935. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7936. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7937. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7938. {$extra_role_prompt}";
  7939. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7940. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7941. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7942. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7943. {$extra_scene_prompt}";
  7944. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7945. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7946. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7947. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7948. {$extra_prop_prompt}";
  7949. }
  7950. $systemPrompt = $is_single
  7951. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7952. 强制要求:
  7953. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7954. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7955. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7956. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7957. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7958. 普通要求:
  7959. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7960. $role_demo
  7961. $scene_demo
  7962. $prop_demo
  7963. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7964. 5.1片段分割逻辑(优先级从高到低):
  7965. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7966. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7967. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7968. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7969. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7970. - 片段数量格式为: 片段数量:8
  7971. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7972. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7973. 5.3分镜结构:每个分镜包含以下字段:
  7974. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  7975. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7976. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7977. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7978. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7979. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7980. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7981. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7982. - 运镜:场景+画面描述+运镜
  7983. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7984. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7985. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7986. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7987. 6.《情绪-视听语言映射表》:
  7988. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7989. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7990. -----|---------|------------|----------------
  7991. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7992. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7993. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7994. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7995. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7996. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7997. -----|---------|------------|----------------
  7998. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7999. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8000. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8001. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8002. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8003. --------|---------|--------------|-------------
  8004. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8005. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8006. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8007. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8008. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8009. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8010. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8011. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8012. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8013. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8014. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8015. -----|---------|------------|------------
  8016. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8017. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8018. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8019. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8020. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8021. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8022. --------|---------|--------------|----------
  8023. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8024. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8025. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8026. 6.6 声音设计与潜意识影响 (Soundscape)
  8027. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8028. -----|---------|------------|------------------
  8029. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8030. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8031. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8032. 理论基石:
  8033. - The Five C's of Cinematography by Joseph V. Mascelli
  8034. - Film Art: An Introduction by David Bordwell
  8035. - Sight, Sound, Motion by Herbert Zettl
  8036. - Notes on the Cinematograph by Robert Bresson
  8037. \n\n
  8038. 7.{$mappedArtStyle_prompt}\n\n
  8039. 示例如下:\n
  8040. ###剧本名:西昆仑
  8041. ###故事梗概
  8042. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8043. ###剧本亮点
  8044. 亮点1:绝境奇药,生死一线
  8045. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8046. 亮点2:结拜兄妹,化解尴尬
  8047. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8048. 亮点3:纤发夺命,情愫暗涌
  8049. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8050. ###人物关系
  8051. 阿雪与梁萧之间存在兄妹之情。
  8052. ###核心矛盾
  8053. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8054. ###主体列表
  8055. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8056. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8057. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8058. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8059. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8060. 全景,正面拍摄,青年女性,亚洲人。
  8061. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8062. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8063. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8064. ###美术风格
  8065. 基础画风风格词:厚涂古风
  8066. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8067. ###场景列表
  8068. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8069. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8070. 无人物。}
  8071. ###分段剧本
  8072. 片段数量:8
  8073. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8074. ##片段1
  8075. 时长:12s
  8076. 分镜1
  8077. 出场角色:刀疤脸
  8078. 场景:边境小镇街道
  8079. 出场道具:酒杯-高脚杯
  8080. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8081. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8082. 配音台词:
  8083. 背景音效:
  8084. 分镜2
  8085. 出场角色:刀疤脸
  8086. 场景:悦来酒馆
  8087. 出场道具:酒杯-高脚杯
  8088. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8089. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8090. 配音台词:
  8091. 背景音效:
  8092. 分镜3
  8093. 出场角色:刀疤脸
  8094. 场景:悦来酒馆
  8095. 出场道具:酒杯-高脚杯
  8096. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8097. 运镜:从中景推向令牌特写。
  8098. 配音台词:
  8099. 背景音效:
  8100. 分镜4
  8101. 出场角色:刀疤脸
  8102. 场景:悦来酒馆
  8103. 出场道具:酒杯-高脚杯
  8104. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8105. 运镜:极速推向酒水溅起的瞬间。
  8106. 配音台词:
  8107. 背景音效:
  8108. 分镜5
  8109. 出场角色:刀疤脸
  8110. 场景:悦来酒馆
  8111. 出场道具:酒杯-高脚杯
  8112. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8113. 运镜:固定机位,利用倾斜构图制造压迫感。
  8114. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8115. 背景音效:
  8116. \n\n"
  8117. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8118. 强制要求:\n
  8119. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8120. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8121. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8122. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8123. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8124. 普通要求:\n
  8125. 1.剧本名(必须生成)必须与文档内容高度相关
  8126. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8127. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8128. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8129. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8130. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8131. {$extra_role_prompt}
  8132. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8133. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8134. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8135. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8136. {$extra_scene_prompt}
  8137. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8138. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8139. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8140. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8141. {$extra_prop_prompt}
  8142. 5.{$mappedArtStyle_prompt}\n\n
  8143. 示例如下:\n
  8144. ###剧本名:西昆仑
  8145. ###故事梗概
  8146. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8147. ###剧本亮点
  8148. 亮点1:绝境奇药,生死一线
  8149. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8150. 亮点2:结拜兄妹,化解尴尬
  8151. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8152. 亮点3:纤发夺命,情愫暗涌
  8153. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8154. ###人物关系
  8155. 阿雪与梁萧之间存在兄妹之情。
  8156. ###核心矛盾
  8157. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8158. ###主体列表
  8159. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8160. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8161. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8162. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8163. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8164. 全景,正面拍摄,青年女性,亚洲人。
  8165. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8166. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8167. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8168. ###美术风格
  8169. 基础画风风格词:厚涂古风
  8170. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8171. ###场景列表
  8172. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8173. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8174. 无人物。}
  8175. ###道具列表
  8176. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  8177. // 构建消息
  8178. $messages = [
  8179. [
  8180. 'role' => 'system',
  8181. 'content' => $systemPrompt
  8182. ],
  8183. [
  8184. 'role' => 'user',
  8185. 'content' => "以下是文档内容:
  8186. {$content}
  8187. 用户问题:
  8188. {$question}"
  8189. ]
  8190. ];
  8191. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8192. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认思考模式
  8193. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8194. if ($model === 'deepseek-chat') {
  8195. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8196. $model = 'deepseek-v4-flash';
  8197. $thinkingMode = 'disabled';
  8198. } elseif ($model === 'deepseek-reasoner') {
  8199. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8200. $model = 'deepseek-v4-flash';
  8201. $thinkingMode = 'enabled';
  8202. }
  8203. $post_data = [
  8204. 'model' => $model,
  8205. 'messages' => $messages,
  8206. // 'max_tokens' => 8192,
  8207. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8208. 'frequency_penalty' => 0,
  8209. 'presence_penalty' => 0,
  8210. 'response_format' => ['type' => 'text'],
  8211. 'thinking' => ['type'=>$thinkingMode],
  8212. 'stream' => true // 启用流式输出
  8213. ];
  8214. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8215. // 根据模型类型选择调用方法
  8216. $fullContent = '';
  8217. $fullReasoningContent = '';
  8218. $usage = [];
  8219. try {
  8220. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8221. // 验证返回值类型
  8222. if (!is_iterable($streamGenerator)) {
  8223. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8224. dLog('deepseek')->error('addChat流式生成器无效', [
  8225. 'generator_type' => $errorType,
  8226. 'model' => $model,
  8227. 'anime_id' => $anime_id
  8228. ]);
  8229. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  8230. 'type' => $errorType,
  8231. 'model' => $model
  8232. ]);
  8233. yield [
  8234. 'type' => 'error',
  8235. 'script' => [],
  8236. 'episode' => [],
  8237. 'answer' => '',
  8238. 'reasoning' => '',
  8239. 'usage' => [],
  8240. 'error' => '接口返回数据异常,请重新请求'
  8241. ];
  8242. return;
  8243. }
  8244. // 处理流式输出
  8245. foreach ($streamGenerator as $chunk) {
  8246. if (isset($chunk['type'])) {
  8247. if ($chunk['type'] === 'done') {
  8248. // 最终结果
  8249. $fullContent = $chunk['full_content'];
  8250. $fullReasoningContent = $chunk['full_reasoning'];
  8251. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8252. } else {
  8253. // 逐块yield数据
  8254. yield $chunk;
  8255. }
  8256. }
  8257. }
  8258. } catch (\Exception $e) {
  8259. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  8260. 'model' => $model,
  8261. 'anime_id' => $anime_id,
  8262. 'trace' => $e->getTraceAsString()
  8263. ]);
  8264. logDB('deepseek', 'error', 'addChat流式处理失败', [
  8265. 'error' => $e->getMessage(),
  8266. 'model' => $model
  8267. ]);
  8268. yield [
  8269. 'type' => 'error',
  8270. 'script' => [],
  8271. 'episode' => [],
  8272. 'answer' => '',
  8273. 'reasoning' => '',
  8274. 'usage' => [],
  8275. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8276. ];
  8277. return;
  8278. }
  8279. dLog('deepseek')->info('完整内容: '.$fullContent);
  8280. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8281. // 处理完整内容并返回最终结果
  8282. $script_arr = [];
  8283. if ($fullContent) {
  8284. $script_arr = handleScriptContentForAce($fullContent);
  8285. dLog('deepseek')->info('解析内容', $script_arr);
  8286. logDB('deepseek', 'info', '解析内容', $script_arr);
  8287. }
  8288. if (empty($script_arr['roles'])) {
  8289. // 未生成剧本相关内容,保存对话记录并返回提示
  8290. dLog('deepseek')->info('未生成剧本相关的内容');
  8291. try {
  8292. DB::beginTransaction();
  8293. $now = date('Y-m-d H:i:s');
  8294. // 保存对话记录
  8295. $records = [
  8296. [
  8297. 'uid' => $uid,
  8298. 'anime_id' => $anime_id,
  8299. 'sequence' => 0,
  8300. 'role' => 'user',
  8301. 'content' => $prompt,
  8302. 'created_at' => $now,
  8303. 'updated_at' => $now
  8304. ],
  8305. [
  8306. 'uid' => $uid,
  8307. 'anime_id' => $anime_id,
  8308. 'sequence' => 0,
  8309. 'role' => 'assistant',
  8310. // 'content' => $fullContent,
  8311. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  8312. 'created_at' => $now,
  8313. 'updated_at' => $now
  8314. ]
  8315. ];
  8316. DB::table('mp_anime_records')->insert($records);
  8317. DB::commit();
  8318. } catch (\Exception $e) {
  8319. DB::rollBack();
  8320. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8321. }
  8322. yield [
  8323. 'type' => 'done',
  8324. 'script' => [],
  8325. 'episode' => [],
  8326. 'answer' => $fullContent,
  8327. 'reasoning' => $fullReasoningContent,
  8328. 'usage' => $usage,
  8329. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8330. ];
  8331. return;
  8332. }
  8333. // 如果需要生成原文内容,从script_arr中提取
  8334. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8335. $content = $script_arr['content'];
  8336. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  8337. if (!$content) {
  8338. yield [
  8339. 'type' => 'done',
  8340. 'script' => [],
  8341. 'episode' => [],
  8342. 'answer' => $fullContent,
  8343. 'reasoning' => $fullReasoningContent,
  8344. 'usage' => $usage,
  8345. 'error' => '未生成剧本内容,请调整提示词再试'
  8346. ];
  8347. return;
  8348. }
  8349. }
  8350. // 替换美术风格
  8351. if ($mappedArtStyle !== '') {
  8352. $script_arr['art_style'] = $mappedArtStyle;
  8353. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8354. }
  8355. // 新建动漫
  8356. if ($user_anime_name == '新剧本策划') {
  8357. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8358. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8359. // if (!$anime_name) {
  8360. // // 未识别到剧本名,保存对话记录并返回提示
  8361. // dLog('deepseek')->info('未能识别到剧本名称');
  8362. // try {
  8363. // DB::beginTransaction();
  8364. // $now = date('Y-m-d H:i:s');
  8365. // // 保存对话记录
  8366. // $records = [
  8367. // [
  8368. // 'uid' => $uid,
  8369. // 'anime_id' => $anime_id,
  8370. // 'sequence' => 0,
  8371. // 'role' => 'user',
  8372. // 'content' => $prompt,
  8373. // 'created_at' => $now,
  8374. // 'updated_at' => $now
  8375. // ],
  8376. // [
  8377. // 'uid' => $uid,
  8378. // 'anime_id' => $anime_id,
  8379. // 'sequence' => 0,
  8380. // 'role' => 'assistant',
  8381. // 'content' => '未能生成剧本名称,请重试',
  8382. // 'created_at' => $now,
  8383. // 'updated_at' => $now
  8384. // ]
  8385. // ];
  8386. // DB::table('mp_anime_records')->insert($records);
  8387. // DB::commit();
  8388. // } catch (\Exception $e) {
  8389. // DB::rollBack();
  8390. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8391. // }
  8392. // yield [
  8393. // 'type' => 'done',
  8394. // 'script' => [],
  8395. // 'episode' => [],
  8396. // 'answer' => $fullContent,
  8397. // 'reasoning' => $fullReasoningContent,
  8398. // 'usage' => $usage,
  8399. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  8400. // ];
  8401. // return;
  8402. // }
  8403. // 确认对话名称唯一性
  8404. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8405. $anime_name = $anime_name . '_' . date('YmdHis');
  8406. }
  8407. }else {
  8408. $anime_name = $user_anime_name;
  8409. }
  8410. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  8411. if ($is_single) {
  8412. $max_retries = 3;
  8413. $retry_count = 0;
  8414. $validation_failed = false;
  8415. $validation_error_msg = '';
  8416. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8417. // 首次校验
  8418. if ($anime_script_id) {
  8419. if (empty($episode_arr['acts'])) {
  8420. $validation_failed = true;
  8421. $validation_error_msg = '未生成分镜剧本相关的内容';
  8422. } else {
  8423. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8424. $generated_roles = array_filter($generated_roles, function($role) {
  8425. return $role !== '旁白';
  8426. });
  8427. if (empty($generated_roles)) {
  8428. $validation_failed = true;
  8429. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8430. }
  8431. if (!$validation_failed && !empty($extra_roles)) {
  8432. $expected_roles = array_keys($extra_roles);
  8433. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8434. if (!empty($invalid_roles)) {
  8435. $validation_failed = true;
  8436. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8437. }
  8438. }
  8439. if (!$validation_failed && !empty($extra_scenes)) {
  8440. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8441. $expected_scenes = array_keys($extra_scenes);
  8442. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8443. if (!empty($invalid_scenes)) {
  8444. $validation_failed = true;
  8445. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8446. }
  8447. }
  8448. if (!$validation_failed && !empty($extra_props)) {
  8449. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8450. $expected_props = array_keys($extra_props);
  8451. $invalid_props = array_diff($generated_props, $expected_props);
  8452. if (!empty($invalid_props)) {
  8453. $validation_failed = true;
  8454. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8455. }
  8456. }
  8457. }
  8458. } else {
  8459. if (empty($episode_arr['acts'])) {
  8460. $validation_failed = true;
  8461. $validation_error_msg = '未生成分镜剧本相关的内容';
  8462. } else {
  8463. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8464. $generated_roles = array_filter($generated_roles, function($role) {
  8465. return $role !== '旁白';
  8466. });
  8467. if (empty($generated_roles)) {
  8468. $validation_failed = true;
  8469. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8470. }
  8471. }
  8472. }
  8473. // 重试循环
  8474. while ($validation_failed && $retry_count < $max_retries) {
  8475. $retry_count++;
  8476. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8477. 'reason' => $validation_error_msg,
  8478. 'anime_id' => $anime_id,
  8479. 'episode_number' => 1
  8480. ]);
  8481. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8482. 'reason' => $validation_error_msg,
  8483. 'anime_id' => $anime_id
  8484. ]);
  8485. yield [
  8486. 'type' => 'retry',
  8487. 'retry_count' => $retry_count,
  8488. 'reason' => $validation_error_msg
  8489. ];
  8490. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8491. if ($anime_script_id) {
  8492. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8493. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8494. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8495. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  8496. } else {
  8497. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8498. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  8499. }
  8500. $messages[] = [
  8501. 'role' => 'assistant',
  8502. 'content' => $fullContent
  8503. ];
  8504. $messages[] = [
  8505. 'role' => 'user',
  8506. 'content' => $retry_prompt
  8507. ];
  8508. $post_data['messages'] = $messages;
  8509. try {
  8510. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8511. $fullContent = '';
  8512. $fullReasoningContent = '';
  8513. foreach ($streamGenerator as $chunk) {
  8514. if (isset($chunk['type'])) {
  8515. if ($chunk['type'] === 'done') {
  8516. $fullContent = $chunk['full_content'];
  8517. $fullReasoningContent = $chunk['full_reasoning'];
  8518. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8519. } else {
  8520. yield $chunk;
  8521. }
  8522. }
  8523. }
  8524. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8525. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  8526. if ($fullContent === '') {
  8527. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  8528. yield [
  8529. 'type' => 'done',
  8530. 'script' => [],
  8531. 'episode' => [],
  8532. 'answer' => '',
  8533. 'reasoning' => $fullReasoningContent,
  8534. 'usage' => $usage,
  8535. 'error' => '生成接口未返回有效内容,请稍后重试'
  8536. ];
  8537. return;
  8538. }
  8539. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8540. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8541. $script_arr = handleScriptContentForAce($fullContent);
  8542. if ($mappedArtStyle !== '') {
  8543. $script_arr['art_style'] = $mappedArtStyle;
  8544. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8545. }
  8546. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8547. $validation_failed = false;
  8548. $validation_error_msg = '';
  8549. if ($anime_script_id) {
  8550. if (empty($episode_arr['acts'])) {
  8551. $validation_failed = true;
  8552. $validation_error_msg = '未生成分镜剧本相关的内容';
  8553. } else {
  8554. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8555. $generated_roles = array_filter($generated_roles, function($role) {
  8556. return $role !== '旁白';
  8557. });
  8558. if (empty($generated_roles)) {
  8559. $validation_failed = true;
  8560. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8561. }
  8562. if (!$validation_failed && !empty($extra_roles)) {
  8563. $expected_roles = array_keys($extra_roles);
  8564. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8565. if (!empty($invalid_roles)) {
  8566. $validation_failed = true;
  8567. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8568. }
  8569. }
  8570. if (!$validation_failed && !empty($extra_scenes)) {
  8571. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8572. $expected_scenes = array_keys($extra_scenes);
  8573. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8574. if (!empty($invalid_scenes)) {
  8575. $validation_failed = true;
  8576. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8577. }
  8578. }
  8579. if (!$validation_failed && !empty($extra_props)) {
  8580. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8581. $expected_props = array_keys($extra_props);
  8582. $invalid_props = array_diff($generated_props, $expected_props);
  8583. if (!empty($invalid_props)) {
  8584. $validation_failed = true;
  8585. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8586. }
  8587. }
  8588. }
  8589. } else {
  8590. if (empty($episode_arr['acts'])) {
  8591. $validation_failed = true;
  8592. $validation_error_msg = '未生成分镜剧本相关的内容';
  8593. } else {
  8594. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8595. $generated_roles = array_filter($generated_roles, function($role) {
  8596. return $role !== '旁白';
  8597. });
  8598. if (empty($generated_roles)) {
  8599. $validation_failed = true;
  8600. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8601. }
  8602. }
  8603. }
  8604. } catch (\Exception $e) {
  8605. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8606. 'trace' => $e->getTraceAsString()
  8607. ]);
  8608. break;
  8609. }
  8610. }
  8611. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  8612. if ($validation_failed && $retry_count >= $max_retries) {
  8613. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8614. 'retry_count' => $retry_count,
  8615. 'last_error' => $validation_error_msg
  8616. ]);
  8617. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8618. 'error' => $validation_error_msg,
  8619. 'anime_id' => $anime_id
  8620. ]);
  8621. $validation_failed = false;
  8622. $validation_error_msg = '';
  8623. }
  8624. // 如果重试后仍然失败
  8625. if ($validation_failed) {
  8626. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8627. 'retry_count' => $retry_count,
  8628. 'last_error' => $validation_error_msg
  8629. ]);
  8630. try {
  8631. $now = date('Y-m-d H:i:s');
  8632. $records = [
  8633. [
  8634. 'uid' => $uid,
  8635. 'anime_id' => $anime_id,
  8636. 'sequence' => 1,
  8637. 'role' => 'user',
  8638. 'content' => $prompt,
  8639. 'created_at' => $now,
  8640. 'updated_at' => $now
  8641. ],
  8642. [
  8643. 'uid' => $uid,
  8644. 'anime_id' => $anime_id,
  8645. 'sequence' => 1,
  8646. 'role' => 'assistant',
  8647. 'content' => $fullContent,
  8648. 'created_at' => $now,
  8649. 'updated_at' => $now
  8650. ]
  8651. ];
  8652. DB::table('mp_anime_records')->insert($records);
  8653. } catch (\Exception $e) {
  8654. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8655. }
  8656. yield [
  8657. 'type' => 'done',
  8658. 'script' => [],
  8659. 'episode' => [],
  8660. 'answer' => $fullContent,
  8661. 'reasoning' => $fullReasoningContent,
  8662. 'usage' => $usage,
  8663. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8664. ];
  8665. return;
  8666. }
  8667. // 验证成功,记录日志
  8668. if ($retry_count > 0) {
  8669. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8670. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8671. }
  8672. }
  8673. $table_data = [
  8674. 'user_id' => $uid,
  8675. 'anime_name' => $anime_name,
  8676. 'model' => $model,
  8677. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8678. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8679. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8680. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8681. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8682. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8683. 'art_style_type' => $input_art_style,
  8684. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8685. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8686. 'status' => '解析完成',
  8687. 'content' => $content,
  8688. 'is_multi' => $is_multi,
  8689. 'ace_mode' => $ace_mode,
  8690. 'generate_status' => '待执行',
  8691. 'updated_at' => date('Y-m-d H:i:s')
  8692. ];
  8693. if ($table_data['content']) {
  8694. $chapters = splitContent($table_data['content']);
  8695. $chapter_count = count($chapters);
  8696. if ($chapter_count > 0) {
  8697. $table_data['start_episode_sequence'] = 1;
  8698. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8699. }
  8700. }
  8701. if ($extra_products) {
  8702. $table_data['extra_products'] = json_encode($extra_products, 256);
  8703. }
  8704. // 如果有剧本ID则进行绑定
  8705. if ($script_id) {
  8706. $table_data['script_id'] = $script_id;
  8707. }
  8708. $single_episode = [];
  8709. try {
  8710. DB::beginTransaction();
  8711. $now = date('Y-m-d H:i:s');
  8712. // 更新动漫大纲
  8713. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8714. if (!$boolen) {
  8715. dLog('deepseek')->info('动漫保存失败', $table_data);
  8716. Utils::throwError('20003:动漫保存失败');
  8717. }
  8718. // 保存对话记录
  8719. $records = [
  8720. [
  8721. 'uid' => $uid,
  8722. 'anime_id' => $anime_id,
  8723. 'sequence' => 0,
  8724. 'role' => 'user',
  8725. 'content' => $prompt,
  8726. 'created_at' => date('Y-m-d H:i:s'),
  8727. 'updated_at' => date('Y-m-d H:i:s')
  8728. ],
  8729. [
  8730. 'uid' => $uid,
  8731. 'anime_id' => $anime_id,
  8732. 'sequence' => 0,
  8733. 'role' => 'assistant',
  8734. 'content' => $fullContent,
  8735. 'created_at' => date('Y-m-d H:i:s'),
  8736. 'updated_at' => date('Y-m-d H:i:s')
  8737. ]
  8738. ];
  8739. // 保存对话记录
  8740. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8741. if (!$boolen3) {
  8742. Utils::throwError('20003:对话记录保存失败');
  8743. }
  8744. if ($is_single) {
  8745. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8746. if (empty($episode_arr['acts'])) {
  8747. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8748. }
  8749. $saveResult = $this->saveEpisodeVersionData(
  8750. $anime_id,
  8751. 1,
  8752. $episode_arr,
  8753. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8754. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8755. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8756. null,
  8757. null,
  8758. false,
  8759. $content,
  8760. $now,
  8761. $ref_products
  8762. );
  8763. $single_episode = $saveResult['episode'];
  8764. $episode_id = $saveResult['episode_id'];
  8765. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8766. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8767. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8768. 'props' => json_encode($saveResult['merged_props'], 256),
  8769. 'updated_at' => $now
  8770. ]);
  8771. if ($boolen5 === false) {
  8772. Utils::throwError('20003:单剧集主表资源同步失败');
  8773. }
  8774. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8775. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8776. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8777. $episode_record_content = '确认分镜大纲';
  8778. if ($content !== '') {
  8779. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8780. }
  8781. $episode_records = [
  8782. [
  8783. 'uid' => $uid,
  8784. 'anime_id' => $anime_id,
  8785. 'role' => 'user',
  8786. 'content' => $episode_record_content,
  8787. 'sequence' => 1,
  8788. 'episode_id' => $episode_id,
  8789. 'created_at' => $now,
  8790. 'updated_at' => $now
  8791. ],
  8792. [
  8793. 'uid' => $uid,
  8794. 'anime_id' => $anime_id,
  8795. 'role' => 'assistant',
  8796. 'content' => $fullContent,
  8797. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8798. 'sequence' => 1,
  8799. 'episode_id' => $episode_id,
  8800. 'created_at' => $now,
  8801. 'updated_at' => $now
  8802. ]
  8803. ];
  8804. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8805. if (!$boolen4) {
  8806. Utils::throwError('20003:单剧集分镜记录保存失败');
  8807. }
  8808. }
  8809. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8810. if ($is_single && !empty($single_episode)) {
  8811. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8812. 'anime_id' => $anime_id,
  8813. 'episode_id' => $episode_id ?? 0,
  8814. 'model' => $model,
  8815. 'source' => 'addChatForAce',
  8816. ]);
  8817. }
  8818. }catch (\Exception $e) {
  8819. DB::rollBack();
  8820. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8821. yield [
  8822. 'type' => 'done',
  8823. 'answer' => $fullContent,
  8824. 'reasoning' => $fullReasoningContent,
  8825. 'usage' => $usage,
  8826. 'error' => $e->getMessage(),
  8827. ];
  8828. return;
  8829. }
  8830. DB::commit();
  8831. dLog('deepseek')->info('保存完毕');
  8832. if ($is_single && !empty($single_episode)) {
  8833. // $this->batchSetGlobalRoleImg([
  8834. // 'anime_id' => $anime_id,
  8835. // ]);
  8836. // $this->batchSetGlobalSceneImg([
  8837. // 'anime_id' => $anime_id,
  8838. // ]);
  8839. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8840. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8841. }
  8842. $table_data['anime_id'] = $anime_id;
  8843. $table_data['roles'] = json_decode($table_data['roles'], true);
  8844. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8845. // $table_data['episodes'] = $script_arr['episodes'];
  8846. unset($table_data['created_at']);
  8847. unset($table_data['updated_at']);
  8848. unset($table_data['status']);
  8849. dLog('deepseek')->info('开始返回');
  8850. yield [
  8851. 'type' => 'done',
  8852. 'script' => $table_data,
  8853. 'episode' => $single_episode,
  8854. 'answer' => $fullContent,
  8855. 'reasoning' => $fullReasoningContent,
  8856. 'usage' => $usage
  8857. ];
  8858. }
  8859. public function reGenerateAnimeForAce($data) {
  8860. $uid = Site::getUid();
  8861. $file = getProp($data, 'file');
  8862. $content = getProp($data, 'content', '');
  8863. $bid = getProp($data, 'bid', 0);
  8864. $script_id = getProp($data, 'script_id', 0);
  8865. $anime_id = getProp($data, 'anime_id');
  8866. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8867. if (!$anime) {
  8868. Utils::throwError('20003:该对话不存在');
  8869. }
  8870. $is_multi = getProp($anime, 'is_multi', 1);
  8871. $is_single = (int)$is_multi !== 1;
  8872. // 积分余额预检(仅单剧集模式收费)
  8873. if ($is_single) {
  8874. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8875. }
  8876. $extra_products = getProp($data, 'products', []);
  8877. if (!$extra_products) {
  8878. $extra_products = getProp($anime, 'extra_products');
  8879. if ($extra_products) {
  8880. $extra_products = json_decode($extra_products, true);
  8881. }else {
  8882. $extra_products = [];
  8883. }
  8884. }else {
  8885. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8886. }
  8887. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8888. $anime_script_id = getProp($anime, 'script_id');
  8889. if ($anime_script_id && $is_single) {
  8890. $cpid = Site::getCpid();
  8891. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8892. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8893. ->where('mapping.script_id', $anime_script_id)
  8894. ->where('product.cpid', $cpid)
  8895. ->where('product.is_deleted', 0);
  8896. $mappings = $script_products_mappings->select(
  8897. 'mapping.product_id',
  8898. 'mapping.episode_number',
  8899. 'product.product_name',
  8900. 'product.type',
  8901. 'product.product',
  8902. 'product.pic_prompt',
  8903. 'product.url',
  8904. 'product.pic_task_id',
  8905. 'product.pic_task_status',
  8906. 'product.three_view_image_url'
  8907. )
  8908. ->get();
  8909. // 按 product_id 分组,合并 episode_number
  8910. $productMap = [];
  8911. foreach ($mappings as $item) {
  8912. $product_id = $item->product_id;
  8913. $product_name = $item->product_name;
  8914. // 处理product_name两边的符号
  8915. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8916. if (!isset($productMap[$product_id])) {
  8917. $productMap[$product_id] = [
  8918. 'product_id' => $product_id,
  8919. 'product_name' => $product_name,
  8920. 'type' => (int)$item->type,
  8921. 'product' => (int)$item->product,
  8922. 'pic_prompt' => $item->pic_prompt,
  8923. 'url' => $item->url,
  8924. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8925. 'pic_task_id' => $item->pic_task_id,
  8926. 'pic_task_status' => $item->pic_task_status,
  8927. 'episode_numbers' => [],
  8928. ];
  8929. }
  8930. // 添加 episode_number(去重)
  8931. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8932. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8933. }
  8934. }
  8935. // 将查询到的剧本资产合并到extra_products中
  8936. // 先构建extra_products的索引(以product_id为key,用于去重)
  8937. $extraProductsMap = [];
  8938. foreach ($extra_products as $item) {
  8939. $key = getProp($item, 'product_id');
  8940. if ($key) {
  8941. $extraProductsMap[$key] = $item;
  8942. }
  8943. }
  8944. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8945. foreach ($productMap as $product) {
  8946. $product_id = $product['product_id'];
  8947. // 如果不存在则添加(不带episode_number信息)
  8948. if (!isset($extraProductsMap[$product_id])) {
  8949. $extraProductsMap[$product_id] = [
  8950. 'product_id' => $product['product_id'],
  8951. 'product_name' => $product['product_name'],
  8952. 'type' => $product['type'],
  8953. 'product' => $product['product'],
  8954. 'pic_prompt' => $product['pic_prompt'],
  8955. 'url' => $product['url'],
  8956. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  8957. 'pic_task_id' => $product['pic_task_id'],
  8958. 'pic_task_status' => $product['pic_task_status'],
  8959. ];
  8960. }
  8961. }
  8962. // 重新赋值给extra_products
  8963. $extra_products = array_values($extraProductsMap);
  8964. }
  8965. $user_anime_name = getProp($anime, 'anime_name');
  8966. $prompt = getProp($data, 'prompt');
  8967. // 处理提示词
  8968. if ($prompt && $extra_products) {
  8969. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8970. foreach($extra_products as $item) {
  8971. $product_name = getProp($item, 'product_name');
  8972. if ($product_name) {
  8973. // 替换 {product_name} 为 product_name
  8974. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8975. }
  8976. }
  8977. }
  8978. // 处理文本模型
  8979. $model = getProp($data, 'model');
  8980. if (!$model) {
  8981. // 用户没有输入,从anime表获取
  8982. $model = getProp($anime, 'model');
  8983. if (!$model) {
  8984. // anime表也没有,使用默认值
  8985. $model = 'deepseek-v4-pro';
  8986. }
  8987. }
  8988. // 验证模型是否在可用模型表中
  8989. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8990. $model = 'deepseek-v4-pro';
  8991. }
  8992. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8993. if ($is_single) {
  8994. $episode_exists = DB::table('mp_anime_episodes')
  8995. ->where('anime_id', $anime_id)
  8996. ->where('sequence', 1)
  8997. ->exists();
  8998. if ($episode_exists) {
  8999. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  9000. }
  9001. }
  9002. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  9003. if ($prompt) {
  9004. $question .= "本次修改要求如下:\n{$prompt}";
  9005. }
  9006. // 提取文件内容
  9007. if ($file) {
  9008. $content = $this->extractFileContent($file);
  9009. if (!$content) {
  9010. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9011. }
  9012. } elseif ($script_id) {
  9013. $content = $this->getContentByScriptId($script_id);
  9014. if (!$content) {
  9015. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9016. }
  9017. } elseif ($bid) {
  9018. $content = $this->getContentByBid($bid);
  9019. if (!$content) {
  9020. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9021. }
  9022. } elseif ($content) {
  9023. $content = filterContent($content);
  9024. }else {
  9025. $content = filterContent(getProp($anime, 'content'));
  9026. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  9027. $need_generate_content = true;
  9028. }
  9029. }
  9030. // 判断是否需要生成原文内容
  9031. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  9032. // 如果需要生成原文内容,添加额外的要求
  9033. $content_generation_requirement = $need_generate_content
  9034. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  9035. : "";
  9036. // 美术风格
  9037. $input_art_style = getProp($data, 'art_style');
  9038. if (!$input_art_style) {
  9039. $mappedArtStyle = getProp($anime, 'art_style');
  9040. }else {
  9041. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9042. }
  9043. if (!$mappedArtStyle) {
  9044. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9045. }else {
  9046. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9047. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9048. }else {
  9049. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9050. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9051. }
  9052. }
  9053. // 构建主体、场景和道具提示词
  9054. $extra_role_prompt = "\n";
  9055. $extra_scene_prompt = "\n";
  9056. $extra_prop_prompt = "\n";
  9057. $extra_roles = [];
  9058. $extra_scenes = [];
  9059. $extra_props = [];
  9060. $ref_products = []; // 参考资产
  9061. if ($extra_products) {
  9062. foreach($extra_products as $item) {
  9063. $product = getProp($item, 'product');
  9064. $product_name = getProp($item, 'product_name');
  9065. if ($product_name == '旁白') continue;
  9066. $ref_products[$product_name] = $item;
  9067. $pic_prompt = getProp($item, 'pic_prompt');
  9068. if ((int)$product === 1) {
  9069. // 拼接角色信息
  9070. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9071. $extra_roles[$product_name] = [
  9072. 'role' => $product_name,
  9073. 'pic_prompt' => $pic_prompt,
  9074. 'url' => getProp($item, 'url', ''),
  9075. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9076. ];
  9077. } elseif ((int)$product === 2) {
  9078. // 拼接场景信息
  9079. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9080. $extra_scenes[$product_name] = [
  9081. 'scene' => $product_name,
  9082. 'pic_prompt' => $pic_prompt,
  9083. 'url' => getProp($item, 'url', ''),
  9084. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9085. ];
  9086. } elseif ((int)$product === 3) {
  9087. // 拼接道具信息
  9088. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9089. $extra_props[$product_name] = [
  9090. 'prop' => $product_name,
  9091. 'pic_prompt' => $pic_prompt,
  9092. 'url' => getProp($item, 'url', ''),
  9093. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9094. ];
  9095. }
  9096. }
  9097. // 优化提示词,融入剧本
  9098. if (!empty(trim($extra_role_prompt))) {
  9099. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9100. }
  9101. if (!empty(trim($extra_scene_prompt))) {
  9102. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9103. }
  9104. if (!empty(trim($extra_prop_prompt))) {
  9105. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9106. }
  9107. }
  9108. if ($anime_script_id && $is_single) {
  9109. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  9110. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  9111. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  9112. }else {
  9113. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9114. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9115. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9116. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9117. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9118. {$extra_role_prompt}";
  9119. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9120. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  9121. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9122. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9123. {$extra_scene_prompt}";
  9124. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9125. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  9126. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9127. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  9128. {$extra_prop_prompt}";
  9129. }
  9130. $system_message = ['role'=>'system', 'content'=>$is_single
  9131. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  9132. 强制要求:
  9133. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9134. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9135. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9136. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9137. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9138. 普通要求:
  9139. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  9140. $role_demo
  9141. $scene_demo
  9142. $prop_demo
  9143. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9144. 5.1片段分割逻辑(优先级从高到低):
  9145. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9146. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9147. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9148. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9149. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9150. - 片段数量格式为: 片段数量:8
  9151. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9152. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9153. 5.3分镜结构:每个分镜包含以下字段:
  9154. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9155. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9156. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9157. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9158. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9159. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9160. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9161. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9162. - 运镜:场景+画面描述+运镜
  9163. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9164. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9165. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9166. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  9167. 6.《情绪-视听语言映射表》:
  9168. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9169. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9170. -----|---------|------------|----------------
  9171. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9172. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9173. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9174. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9175. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9176. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9177. -----|---------|------------|----------------
  9178. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9179. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9180. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9181. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9182. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9183. --------|---------|--------------|-------------
  9184. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9185. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9186. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9187. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9188. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9189. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9190. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9191. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9192. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9193. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9194. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9195. -----|---------|------------|------------
  9196. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9197. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9198. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9199. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9200. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9201. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9202. --------|---------|--------------|----------
  9203. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9204. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9205. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9206. 6.6 声音设计与潜意识影响 (Soundscape)
  9207. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9208. -----|---------|------------|------------------
  9209. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9210. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9211. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9212. 理论基石:
  9213. - The Five C's of Cinematography by Joseph V. Mascelli
  9214. - Film Art: An Introduction by David Bordwell
  9215. - Sight, Sound, Motion by Herbert Zettl
  9216. - Notes on the Cinematograph by Robert Bresson
  9217. \n\n
  9218. 7.{$mappedArtStyle_prompt}\n\n
  9219. 示例如下:\n
  9220. ###剧本名:西昆仑
  9221. ###故事梗概
  9222. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9223. ###剧本亮点
  9224. 亮点1:绝境奇药,生死一线
  9225. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9226. 亮点2:结拜兄妹,化解尴尬
  9227. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9228. 亮点3:纤发夺命,情愫暗涌
  9229. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9230. ###人物关系
  9231. 阿雪与梁萧之间存在兄妹之情。
  9232. ###核心矛盾
  9233. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9234. ###主体列表
  9235. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9236. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9237. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9238. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9239. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9240. 全景,正面拍摄,青年女性,亚洲人。
  9241. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9242. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9243. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9244. ###美术风格
  9245. 基础画风风格词:厚涂古风
  9246. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9247. ###场景列表
  9248. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9249. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9250. 无人物。}
  9251. ###分段剧本
  9252. 片段数量:8
  9253. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9254. ##片段1
  9255. 时长:12s
  9256. 分镜1
  9257. 出场角色:刀疤脸
  9258. 场景:边境小镇街道
  9259. 出场道具:酒杯-高脚杯
  9260. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9261. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9262. 配音台词:
  9263. 背景音效:
  9264. 分镜2
  9265. 出场角色:刀疤脸
  9266. 场景:悦来酒馆
  9267. 出场道具:酒杯-高脚杯
  9268. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9269. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9270. 配音台词:
  9271. 背景音效:
  9272. 分镜3
  9273. 出场角色:刀疤脸
  9274. 场景:悦来酒馆
  9275. 出场道具:酒杯-高脚杯
  9276. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9277. 运镜:从中景推向令牌特写。
  9278. 配音台词:
  9279. 背景音效:
  9280. 分镜4
  9281. 出场角色:刀疤脸
  9282. 场景:悦来酒馆
  9283. 出场道具:酒杯-高脚杯
  9284. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9285. 运镜:极速推向酒水溅起的瞬间。
  9286. 配音台词:
  9287. 背景音效:
  9288. 分镜5
  9289. 出场角色:刀疤脸
  9290. 场景:悦来酒馆
  9291. 出场道具:酒杯-高脚杯
  9292. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9293. 运镜:固定机位,利用倾斜构图制造压迫感。
  9294. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9295. 背景音效:
  9296. \n\n"
  9297. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9298. 强制要求:\n
  9299. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9300. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9301. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9302. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9303. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9304. 普通要求:\n
  9305. 1.剧本名(必须生成)必须与文档内容高度相关
  9306. $role_demo
  9307. $scene_demo
  9308. $prop_demo
  9309. 5.{$mappedArtStyle_prompt}\n\n
  9310. 示例如下:\n
  9311. ###剧本名:西昆仑
  9312. ###故事梗概
  9313. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9314. ###剧本亮点
  9315. 亮点1:绝境奇药,生死一线
  9316. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9317. 亮点2:结拜兄妹,化解尴尬
  9318. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9319. 亮点3:纤发夺命,情愫暗涌
  9320. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9321. ###人物关系
  9322. 阿雪与梁萧之间存在兄妹之情。
  9323. ###核心矛盾
  9324. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9325. ###主体列表
  9326. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9327. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9328. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9329. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9330. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9331. 全景,正面拍摄,青年女性,亚洲人。
  9332. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9333. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9334. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9335. ###美术风格
  9336. 基础画风风格词:厚涂古风
  9337. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9338. ###场景列表
  9339. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9340. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9341. 无人物。}
  9342. ###道具列表
  9343. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  9344. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  9345. $episode_count = $this->extractEpisodeNumber($prompt);
  9346. if ((int)getProp($anime, 'is_multi') !== 1) {
  9347. yield [
  9348. 'type' => 'done',
  9349. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  9350. 'reasoning' => '',
  9351. 'usage' => []
  9352. ];
  9353. return;
  9354. }
  9355. if ($episode_count) {
  9356. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  9357. $system_message = [
  9358. 'role' => 'system',
  9359. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9360. 强制要求:\n
  9361. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9362. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9363. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9364. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9365. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9366. 普通要求:\n
  9367. 1.<故事梗概>控制在200-300字左右
  9368. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9369. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9370. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9371. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9372. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9373. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9374. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9375. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9376. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9377. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  9378. 示例如下:\n
  9379. ###剧本名:西昆仑
  9380. ###故事梗概
  9381. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9382. ###剧本亮点
  9383. 亮点1:绝境奇药,生死一线
  9384. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9385. 亮点2:结拜兄妹,化解尴尬
  9386. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9387. 亮点3:纤发夺命,情愫暗涌
  9388. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9389. ###人物关系
  9390. 阿雪与梁萧之间存在兄妹之情。
  9391. ###核心矛盾
  9392. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9393. ###主体列表
  9394. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9395. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9396. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9397. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9398. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9399. 全景,正面拍摄,青年女性,亚洲人。
  9400. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9401. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9402. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9403. ###美术风格
  9404. 基础画风风格词:厚涂古风
  9405. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9406. ###场景列表
  9407. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9408. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9409. 无人物。}
  9410. ###分集详细内容
  9411. ##第1章 重生
  9412. 我重生了。
  9413. 源于一个男人偏执的暗恋。
  9414. ##第2章 相救
  9415. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  9416. 我眼睛扫向站在锅炉后的卞大伟。"
  9417. ];
  9418. // 构建消息
  9419. $messages = [
  9420. $system_message,
  9421. [
  9422. 'role' => 'user',
  9423. 'content' => "以下是文档内容:
  9424. {$content}
  9425. 用户问题:
  9426. {$question}"
  9427. ]
  9428. ];
  9429. }else {
  9430. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  9431. // 构建消息
  9432. $messages = [
  9433. $system_message,
  9434. [
  9435. 'role' => 'user',
  9436. 'content' => "以下是文档内容:
  9437. {$content}
  9438. 用户问题:
  9439. {$question}"
  9440. ]
  9441. ];
  9442. }else {
  9443. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  9444. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  9445. return (array)$value;
  9446. })->toArray();
  9447. array_unshift($messages, $system_message);
  9448. $messages[] = [
  9449. 'role' => 'user',
  9450. 'content' => $prompt
  9451. ];
  9452. }
  9453. }
  9454. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9455. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  9456. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9457. if ($model === 'deepseek-chat') {
  9458. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9459. $model = 'deepseek-v4-flash';
  9460. $thinkingMode = 'disabled';
  9461. } elseif ($model === 'deepseek-reasoner') {
  9462. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9463. $model = 'deepseek-v4-flash';
  9464. $thinkingMode = 'enabled';
  9465. }
  9466. $post_data = [
  9467. 'model' => $model,
  9468. 'messages' => $messages,
  9469. // 'max_tokens' => 8192,
  9470. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9471. 'frequency_penalty' => 0,
  9472. 'presence_penalty' => 0,
  9473. 'response_format' => ['type' => 'text'],
  9474. 'thinking' => ['type' => $thinkingMode],
  9475. 'stream' => true // 启用流式输出
  9476. ];
  9477. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9478. // 根据模型类型选择调用方法
  9479. $fullContent = '';
  9480. $fullReasoningContent = '';
  9481. $usage = [];
  9482. // dd($post_data);
  9483. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  9484. try {
  9485. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9486. // 验证返回值类型
  9487. if (!is_iterable($streamGenerator)) {
  9488. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9489. dLog('deepseek')->error('方法名流式生成器无效', [
  9490. 'generator_type' => $errorType,
  9491. 'model' => $model,
  9492. // 添加其他上下文信息
  9493. ]);
  9494. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  9495. 'type' => $errorType,
  9496. 'model' => $model
  9497. ]);
  9498. yield [
  9499. 'type' => 'error',
  9500. // 根据方法返回相应的空数据结构
  9501. 'answer' => '',
  9502. 'reasoning' => '',
  9503. 'usage' => [],
  9504. 'error' => '接口返回数据异常,请重新请求'
  9505. ];
  9506. return;
  9507. }
  9508. // 处理流式输出
  9509. foreach ($streamGenerator as $chunk) {
  9510. if (isset($chunk['type'])) {
  9511. if ($chunk['type'] === 'done') {
  9512. $fullContent = $chunk['full_content'];
  9513. $fullReasoningContent = $chunk['full_reasoning'];
  9514. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9515. } else {
  9516. yield $chunk;
  9517. }
  9518. }
  9519. }
  9520. } catch (\Exception $e) {
  9521. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  9522. 'model' => $model,
  9523. 'trace' => $e->getTraceAsString()
  9524. ]);
  9525. logDB('deepseek', 'error', '方法名流式处理失败', [
  9526. 'error' => $e->getMessage(),
  9527. 'model' => $model
  9528. ]);
  9529. yield [
  9530. 'type' => 'error',
  9531. // 根据方法返回相应的空数据结构
  9532. 'answer' => '',
  9533. 'reasoning' => '',
  9534. 'usage' => [],
  9535. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9536. ];
  9537. return;
  9538. }
  9539. dLog('deepseek')->info('完整内容: '.$fullContent);
  9540. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9541. // 处理完整内容并返回最终结果
  9542. $script_arr = [];
  9543. if ($fullContent) {
  9544. $script_arr = handleScriptContentForAce($fullContent);
  9545. dLog('deepseek')->info('解析内容', $script_arr);
  9546. logDB('deepseek', 'info', '解析内容', $script_arr);
  9547. }
  9548. if (empty($script_arr['roles'])) {
  9549. // 未生成剧本相关内容,保存对话记录并返回提示
  9550. dLog('deepseek')->info('未生成剧本相关的内容');
  9551. try {
  9552. $now = date('Y-m-d H:i:s');
  9553. // 保存对话记录
  9554. $records = [
  9555. [
  9556. 'uid' => $uid,
  9557. 'anime_id' => $anime_id,
  9558. 'sequence' => 0,
  9559. 'role' => 'user',
  9560. 'content' => $prompt,
  9561. 'created_at' => $now,
  9562. 'updated_at' => $now
  9563. ],
  9564. [
  9565. 'uid' => $uid,
  9566. 'anime_id' => $anime_id,
  9567. 'sequence' => 0,
  9568. 'role' => 'assistant',
  9569. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  9570. 'created_at' => $now,
  9571. 'updated_at' => $now
  9572. ]
  9573. ];
  9574. DB::table('mp_anime_records')->insert($records);
  9575. } catch (\Exception $e) {
  9576. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9577. }
  9578. yield [
  9579. 'type' => 'done',
  9580. 'script' => [],
  9581. 'episode' => [],
  9582. 'answer' => $fullContent,
  9583. 'reasoning' => $fullReasoningContent,
  9584. 'usage' => $usage,
  9585. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  9586. ];
  9587. return;
  9588. }
  9589. // 替换美术风格
  9590. if ($mappedArtStyle !== '') {
  9591. $script_arr['art_style'] = $mappedArtStyle;
  9592. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9593. }
  9594. if ($user_anime_name != '新剧本策划') {
  9595. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  9596. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  9597. // 确认对话名称唯一性
  9598. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  9599. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  9600. }
  9601. }else {
  9602. $anime_name = $user_anime_name;
  9603. }
  9604. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  9605. if ($is_single) {
  9606. $max_retries = 3;
  9607. $retry_count = 0;
  9608. $validation_failed = false;
  9609. $validation_error_msg = '';
  9610. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9611. // 首次校验
  9612. if ($anime_script_id) {
  9613. if (empty($episode_arr['acts'])) {
  9614. $validation_failed = true;
  9615. $validation_error_msg = '未生成分镜剧本相关的内容';
  9616. } else {
  9617. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9618. $generated_roles = array_filter($generated_roles, function($role) {
  9619. return $role !== '旁白';
  9620. });
  9621. if (empty($generated_roles)) {
  9622. $validation_failed = true;
  9623. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9624. }
  9625. if (!$validation_failed && !empty($extra_roles)) {
  9626. $expected_roles = array_keys($extra_roles);
  9627. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9628. if (!empty($invalid_roles)) {
  9629. $validation_failed = true;
  9630. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9631. }
  9632. }
  9633. if (!$validation_failed && !empty($extra_scenes)) {
  9634. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9635. $expected_scenes = array_keys($extra_scenes);
  9636. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9637. if (!empty($invalid_scenes)) {
  9638. $validation_failed = true;
  9639. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9640. }
  9641. }
  9642. if (!$validation_failed && !empty($extra_props)) {
  9643. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9644. $expected_props = array_keys($extra_props);
  9645. $invalid_props = array_diff($generated_props, $expected_props);
  9646. if (!empty($invalid_props)) {
  9647. $validation_failed = true;
  9648. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9649. }
  9650. }
  9651. }
  9652. } else {
  9653. if (empty($episode_arr['acts'])) {
  9654. $validation_failed = true;
  9655. $validation_error_msg = '未生成分镜剧本相关的内容';
  9656. } else {
  9657. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9658. $generated_roles = array_filter($generated_roles, function($role) {
  9659. return $role !== '旁白';
  9660. });
  9661. if (empty($generated_roles)) {
  9662. $validation_failed = true;
  9663. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9664. }
  9665. }
  9666. }
  9667. // 重试循环
  9668. while ($validation_failed && $retry_count < $max_retries) {
  9669. $retry_count++;
  9670. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9671. 'reason' => $validation_error_msg,
  9672. 'anime_id' => $anime_id,
  9673. 'episode_number' => 1
  9674. ]);
  9675. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9676. 'reason' => $validation_error_msg,
  9677. 'anime_id' => $anime_id
  9678. ]);
  9679. yield [
  9680. 'type' => 'retry',
  9681. 'retry_count' => $retry_count,
  9682. 'reason' => $validation_error_msg
  9683. ];
  9684. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9685. if ($anime_script_id) {
  9686. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9687. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9688. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9689. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9690. } else {
  9691. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9692. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9693. }
  9694. $messages[] = [
  9695. 'role' => 'assistant',
  9696. 'content' => $fullContent
  9697. ];
  9698. $messages[] = [
  9699. 'role' => 'user',
  9700. 'content' => $retry_prompt
  9701. ];
  9702. $post_data['messages'] = $messages;
  9703. try {
  9704. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9705. $fullContent = '';
  9706. $fullReasoningContent = '';
  9707. foreach ($streamGenerator as $chunk) {
  9708. if (isset($chunk['type'])) {
  9709. if ($chunk['type'] === 'done') {
  9710. $fullContent = $chunk['full_content'];
  9711. $fullReasoningContent = $chunk['full_reasoning'];
  9712. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9713. } else {
  9714. yield $chunk;
  9715. }
  9716. }
  9717. }
  9718. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9719. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  9720. if ($fullContent === '') {
  9721. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  9722. yield [
  9723. 'type' => 'done',
  9724. 'script' => [],
  9725. 'episode' => [],
  9726. 'answer' => '',
  9727. 'reasoning' => $fullReasoningContent,
  9728. 'usage' => $usage,
  9729. 'error' => '生成接口未返回有效内容,请稍后重试'
  9730. ];
  9731. return;
  9732. }
  9733. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9734. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9735. $script_arr = handleScriptContentForAce($fullContent);
  9736. if ($mappedArtStyle !== '') {
  9737. $script_arr['art_style'] = $mappedArtStyle;
  9738. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9739. }
  9740. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9741. $validation_failed = false;
  9742. $validation_error_msg = '';
  9743. if ($anime_script_id) {
  9744. if (empty($episode_arr['acts'])) {
  9745. $validation_failed = true;
  9746. $validation_error_msg = '未生成分镜剧本相关的内容';
  9747. } else {
  9748. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9749. $generated_roles = array_filter($generated_roles, function($role) {
  9750. return $role !== '旁白';
  9751. });
  9752. if (empty($generated_roles)) {
  9753. $validation_failed = true;
  9754. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9755. }
  9756. if (!$validation_failed && !empty($extra_roles)) {
  9757. $expected_roles = array_keys($extra_roles);
  9758. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9759. if (!empty($invalid_roles)) {
  9760. $validation_failed = true;
  9761. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9762. }
  9763. }
  9764. if (!$validation_failed && !empty($extra_scenes)) {
  9765. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9766. $expected_scenes = array_keys($extra_scenes);
  9767. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9768. if (!empty($invalid_scenes)) {
  9769. $validation_failed = true;
  9770. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9771. }
  9772. }
  9773. if (!$validation_failed && !empty($extra_props)) {
  9774. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9775. $expected_props = array_keys($extra_props);
  9776. $invalid_props = array_diff($generated_props, $expected_props);
  9777. if (!empty($invalid_props)) {
  9778. $validation_failed = true;
  9779. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9780. }
  9781. }
  9782. }
  9783. } else {
  9784. if (empty($episode_arr['acts'])) {
  9785. $validation_failed = true;
  9786. $validation_error_msg = '未生成分镜剧本相关的内容';
  9787. } else {
  9788. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9789. $generated_roles = array_filter($generated_roles, function($role) {
  9790. return $role !== '旁白';
  9791. });
  9792. if (empty($generated_roles)) {
  9793. $validation_failed = true;
  9794. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9795. }
  9796. }
  9797. }
  9798. } catch (\Exception $e) {
  9799. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9800. 'trace' => $e->getTraceAsString()
  9801. ]);
  9802. break;
  9803. }
  9804. }
  9805. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  9806. if ($validation_failed && $retry_count >= $max_retries) {
  9807. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9808. 'retry_count' => $retry_count,
  9809. 'last_error' => $validation_error_msg
  9810. ]);
  9811. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9812. 'error' => $validation_error_msg,
  9813. 'anime_id' => $anime_id
  9814. ]);
  9815. $validation_failed = false;
  9816. $validation_error_msg = '';
  9817. }
  9818. // 如果重试后仍然失败
  9819. if ($validation_failed) {
  9820. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9821. 'retry_count' => $retry_count,
  9822. 'last_error' => $validation_error_msg
  9823. ]);
  9824. try {
  9825. $now = date('Y-m-d H:i:s');
  9826. $records = [
  9827. [
  9828. 'uid' => $uid,
  9829. 'anime_id' => $anime_id,
  9830. 'sequence' => 1,
  9831. 'role' => 'user',
  9832. 'content' => $prompt,
  9833. 'created_at' => $now,
  9834. 'updated_at' => $now
  9835. ],
  9836. [
  9837. 'uid' => $uid,
  9838. 'anime_id' => $anime_id,
  9839. 'sequence' => 1,
  9840. 'role' => 'assistant',
  9841. 'content' => $fullContent,
  9842. 'created_at' => $now,
  9843. 'updated_at' => $now
  9844. ]
  9845. ];
  9846. DB::table('mp_anime_records')->insert($records);
  9847. } catch (\Exception $e) {
  9848. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9849. }
  9850. yield [
  9851. 'type' => 'done',
  9852. 'script' => [],
  9853. 'episode' => [],
  9854. 'answer' => $fullContent,
  9855. 'reasoning' => $fullReasoningContent,
  9856. 'usage' => $usage,
  9857. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9858. ];
  9859. return;
  9860. }
  9861. // 验证成功,记录日志
  9862. if ($retry_count > 0) {
  9863. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9864. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9865. }
  9866. }
  9867. $table_data = [
  9868. 'user_id' => $uid,
  9869. 'model' => $model,
  9870. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  9871. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  9872. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  9873. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  9874. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  9875. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  9876. 'art_style_type' => $input_art_style,
  9877. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  9878. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  9879. 'status' => '解析完成',
  9880. 'generate_status' => '待执行',
  9881. 'updated_at' => date('Y-m-d H:i:s')
  9882. ];
  9883. if ($anime_name) $table_data['anime_name'] = $anime_name;
  9884. // 如果是修改集数,则将content内容更新(会改变原文)
  9885. if (isset($episode_count) && $episode_count > 0) {
  9886. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  9887. $table_data['start_episode_sequence'] = 1;
  9888. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  9889. }else {
  9890. // 如果需要生成原文内容,从script_arr中提取
  9891. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  9892. $table_data['content'] = $script_arr['content'];
  9893. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  9894. if (!$table_data['content']) {
  9895. yield [
  9896. 'type' => 'done',
  9897. 'script' => [],
  9898. 'episode' => [],
  9899. 'answer' => $fullContent,
  9900. 'reasoning' => $fullReasoningContent,
  9901. 'usage' => $usage,
  9902. 'error' => '未生成剧本内容,请调整提示词再试'
  9903. ];
  9904. return;
  9905. }
  9906. }
  9907. if (isset($table_data['content']) && $table_data['content']) {
  9908. $chapters = splitContent($table_data['content']);
  9909. $chapter_count = count($chapters);
  9910. if ($chapter_count > 0) {
  9911. $table_data['start_episode_sequence'] = 1;
  9912. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  9913. }
  9914. }
  9915. }
  9916. if ($extra_products) {
  9917. $table_data['extra_products'] = json_encode($extra_products, 256);
  9918. }
  9919. $single_episode = [];
  9920. try {
  9921. DB::beginTransaction();
  9922. $now = date('Y-m-d H:i:s');
  9923. // 更新动漫大纲
  9924. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  9925. if (!$boolen) {
  9926. dLog('deepseek')->info('对话修改失败', $table_data);
  9927. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  9928. Utils::throwError('20003:对话修改失败');
  9929. }
  9930. // 保存对话记录
  9931. $records = [
  9932. [
  9933. 'uid' => $uid,
  9934. 'anime_id' => $anime_id,
  9935. 'sequence' => 0,
  9936. 'role' => 'user',
  9937. 'content' => $prompt,
  9938. 'created_at' => $now,
  9939. 'updated_at' => $now
  9940. ],
  9941. [
  9942. 'uid' => $uid,
  9943. 'anime_id' => $anime_id,
  9944. 'sequence' => 0,
  9945. 'role' => 'assistant',
  9946. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9947. 'content' => $fullContent,
  9948. 'created_at' => $now,
  9949. 'updated_at' => $now
  9950. ]
  9951. ];
  9952. // 保存对话记录
  9953. $boolen3 = DB::table('mp_anime_records')->insert($records);
  9954. if (!$boolen3) {
  9955. Utils::throwError('20003:对话记录保存失败');
  9956. }
  9957. // 单剧集模式:生成并保存剧集信息
  9958. if ($is_single) {
  9959. $anime_name = getProp($anime, 'anime_name', '未命名');
  9960. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9961. if (empty($episode_arr['acts'])) {
  9962. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  9963. }
  9964. $saveResult = $this->saveEpisodeVersionData(
  9965. $anime_id,
  9966. 1,
  9967. $episode_arr,
  9968. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9969. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9970. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9971. null,
  9972. null,
  9973. false,
  9974. $content,
  9975. $now,
  9976. $ref_products
  9977. );
  9978. $single_episode = $saveResult['episode'];
  9979. $episode_id = $saveResult['episode_id'];
  9980. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  9981. 'roles' => json_encode($saveResult['merged_roles'], 256),
  9982. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  9983. 'props' => json_encode($saveResult['merged_props'], 256),
  9984. 'updated_at' => $now
  9985. ]);
  9986. if ($boolen5 === false) {
  9987. Utils::throwError('20003:单剧集主表资源同步失败');
  9988. }
  9989. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  9990. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  9991. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  9992. $episode_record_content = '确认分镜大纲';
  9993. if ($content !== '') {
  9994. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  9995. }
  9996. $episode_records = [
  9997. [
  9998. 'uid' => $uid,
  9999. 'anime_id' => $anime_id,
  10000. 'role' => 'user',
  10001. 'content' => $episode_record_content,
  10002. 'sequence' => 1,
  10003. 'episode_id' => $episode_id,
  10004. 'created_at' => $now,
  10005. 'updated_at' => $now
  10006. ],
  10007. [
  10008. 'uid' => $uid,
  10009. 'anime_id' => $anime_id,
  10010. 'role' => 'assistant',
  10011. 'content' => $fullContent,
  10012. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10013. 'sequence' => 1,
  10014. 'episode_id' => $episode_id,
  10015. 'created_at' => $now,
  10016. 'updated_at' => $now
  10017. ]
  10018. ];
  10019. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  10020. if (!$boolen4) {
  10021. Utils::throwError('20003:单剧集分镜记录保存失败');
  10022. }
  10023. }
  10024. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10025. if ($is_single && !empty($single_episode)) {
  10026. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10027. 'anime_id' => $anime_id,
  10028. 'episode_id' => $episode_id ?? 0,
  10029. 'model' => $model,
  10030. 'source' => 'reGenerateAnimeForAce',
  10031. ]);
  10032. }
  10033. }catch (\Exception $e) {
  10034. DB::rollBack();
  10035. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  10036. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  10037. yield [
  10038. 'type' => 'done',
  10039. 'answer' => $fullContent,
  10040. 'reasoning' => $fullReasoningContent,
  10041. 'usage' => $usage,
  10042. 'error' => $e->getMessage(),
  10043. ];
  10044. return;
  10045. }
  10046. DB::commit();
  10047. dLog('deepseek')->info('保存完毕');
  10048. if ($is_single && !empty($single_episode)) {
  10049. // $this->batchSetGlobalRoleImg([
  10050. // 'anime_id' => $anime_id,
  10051. // ]);
  10052. // $this->batchSetGlobalSceneImg([
  10053. // 'anime_id' => $anime_id,
  10054. // ]);
  10055. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10056. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10057. }
  10058. $table_data['anime_id'] = $anime_id;
  10059. $table_data['roles'] = json_decode($table_data['roles'], true);
  10060. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  10061. $table_data['props'] = json_decode($table_data['props'], true);
  10062. unset($table_data['updated_at']);
  10063. unset($table_data['status']);
  10064. yield [
  10065. 'type' => 'done',
  10066. 'script' => $table_data,
  10067. 'episode' => $single_episode,
  10068. 'answer' => $fullContent,
  10069. 'reasoning' => $fullReasoningContent,
  10070. 'usage' => $usage
  10071. ];
  10072. }
  10073. public function chatForAce($data) {
  10074. $uid = Site::getUid();
  10075. // 积分余额预检(不足直接报错)
  10076. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10077. $anime_id = getProp($data, 'anime_id');
  10078. $file = getProp($data, 'file');
  10079. $content = getProp($data, 'content', '');
  10080. $bid = getProp($data, 'bid', 0);
  10081. $script_id = getProp($data, 'script_id', 0);
  10082. $episode_number = getProp($data, 'episode_number', 1);
  10083. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10084. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10085. if (!$anime) Utils::throwError('20003:该对话不存在!');
  10086. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  10087. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  10088. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  10089. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  10090. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  10091. $roles = is_array($roles) ? $roles : [];
  10092. $scenes = is_array($scenes) ? $scenes : [];
  10093. $extra_products = getProp($data, 'products', []);
  10094. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  10095. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  10096. $anime_script_id = getProp($anime, 'script_id');
  10097. if ($anime_script_id) {
  10098. $cpid = Site::getCpid();
  10099. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  10100. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10101. ->where('mapping.script_id', $anime_script_id)
  10102. ->where('product.cpid', $cpid)
  10103. ->where('product.is_deleted', 0);
  10104. // 如果提供了 episode_number,则过滤指定集数
  10105. if ($episode_number !== null && $episode_number !== '') {
  10106. $script_products_mappings->where('mapping.episode_number', $episode_number);
  10107. }
  10108. $mappings = $script_products_mappings->select(
  10109. 'mapping.product_id',
  10110. 'mapping.episode_number',
  10111. 'product.product_name',
  10112. 'product.type',
  10113. 'product.product',
  10114. 'product.pic_prompt',
  10115. 'product.url',
  10116. 'product.pic_task_id',
  10117. 'product.pic_task_status',
  10118. 'product.three_view_image_url'
  10119. )
  10120. ->get();
  10121. // 按 product_id 分组,合并 episode_number
  10122. $productMap = [];
  10123. foreach ($mappings as $item) {
  10124. $product_id = $item->product_id;
  10125. $product_name = $item->product_name;
  10126. // 处理product_name两边的符号
  10127. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  10128. if (!isset($productMap[$product_id])) {
  10129. $productMap[$product_id] = [
  10130. 'product_id' => $product_id,
  10131. 'product_name' => $product_name,
  10132. 'type' => (int)$item->type,
  10133. 'product' => (int)$item->product,
  10134. 'pic_prompt' => $item->pic_prompt,
  10135. 'url' => $item->url,
  10136. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  10137. 'pic_task_id' => $item->pic_task_id,
  10138. 'pic_task_status' => $item->pic_task_status,
  10139. 'episode_numbers' => [],
  10140. ];
  10141. }
  10142. // 添加 episode_number(去重)
  10143. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  10144. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  10145. }
  10146. }
  10147. // 将查询到的剧本资产合并到extra_products中
  10148. // 先构建extra_products的索引(以product_id+episode_number为key)
  10149. $extraProductsMap = [];
  10150. foreach ($extra_products as $item) {
  10151. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  10152. $extraProductsMap[$key] = $item;
  10153. }
  10154. // 合并剧本资产(去重:product_id+episode_number)
  10155. foreach ($productMap as $product) {
  10156. foreach ($product['episode_numbers'] as $ep_num) {
  10157. $key = $product['product_id'] . '_' . $ep_num;
  10158. // 如果不存在则添加
  10159. if (!isset($extraProductsMap[$key])) {
  10160. $extraProductsMap[$key] = [
  10161. 'product_id' => $product['product_id'],
  10162. 'product_name' => $product['product_name'],
  10163. 'type' => $product['type'],
  10164. 'product' => $product['product'],
  10165. 'pic_prompt' => $product['pic_prompt'],
  10166. 'url' => $product['url'],
  10167. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  10168. 'pic_task_id' => $product['pic_task_id'],
  10169. 'pic_task_status' => $product['pic_task_status'],
  10170. 'episode_number' => $ep_num,
  10171. ];
  10172. }
  10173. }
  10174. }
  10175. // 重新赋值给extra_products
  10176. $extra_products = array_values($extraProductsMap);
  10177. }
  10178. // 处理提示词
  10179. if ($prompt && $extra_products) {
  10180. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  10181. foreach($extra_products as $item) {
  10182. $product_name = getProp($item, 'product_name');
  10183. if ($product_name) {
  10184. // 替换 {product_name} 为 product_name
  10185. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  10186. }
  10187. }
  10188. }
  10189. // 获取最后一集序号
  10190. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  10191. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  10192. // 转换主体列表和场景列表的格式
  10193. // 获取参考主体或场景
  10194. if ((int)$episode_number === 1) {
  10195. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  10196. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  10197. }else {
  10198. $prev_episode_number = $episode_number - 1;
  10199. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  10200. }
  10201. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  10202. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  10203. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  10204. // 合并anime_products和extra_products(extra_products优先,去重)
  10205. $anime_products = getProp($anime, 'extra_products');
  10206. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  10207. $ref_products = [];
  10208. foreach($anime_products as $item) {
  10209. $product_name = getProp($item, 'product_name');
  10210. $ref_products[$product_name] = $item;
  10211. }
  10212. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  10213. $extra_roles = []; // 从extra_products中提取的角色
  10214. $extra_scenes = []; // 从extra_products中提取的场景
  10215. $extra_props = []; // 从extra_products中提取的道具
  10216. if ($extra_products && is_array($extra_products)) {
  10217. foreach($extra_products as $item) {
  10218. $product = (int)getProp($item, 'product');
  10219. $product_name = getProp($item, 'product_name');
  10220. if ($product_name == '旁白') continue;
  10221. $pic_prompt = getProp($item, 'pic_prompt');
  10222. $ref_products[$product_name] = $item;
  10223. if ($product === 1) {
  10224. // 角色
  10225. $extra_roles[$product_name] = [
  10226. 'role' => $product_name,
  10227. 'pic_prompt' => $pic_prompt,
  10228. 'url' => getProp($item, 'url', ''),
  10229. ];
  10230. } elseif ($product === 2) {
  10231. // 场景
  10232. $extra_scenes[$product_name] = [
  10233. 'scene' => $product_name,
  10234. 'pic_prompt' => $pic_prompt,
  10235. 'url' => getProp($item, 'url', ''),
  10236. ];
  10237. } elseif ($product === 3) {
  10238. // 道具
  10239. $extra_props[$product_name] = [
  10240. 'prop' => $product_name,
  10241. 'pic_prompt' => $pic_prompt,
  10242. 'url' => getProp($item, 'url', ''),
  10243. ];
  10244. }
  10245. }
  10246. }
  10247. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  10248. $merged_roles = [];
  10249. foreach($ref_roles as $role) {
  10250. $role_name = getProp($role, 'role');
  10251. if (!isset($extra_roles[$role_name])) {
  10252. $merged_roles[$role_name] = $role;
  10253. }
  10254. }
  10255. // 添加extra_roles
  10256. foreach($extra_roles as $role_name => $role) {
  10257. $merged_roles[$role_name] = $role;
  10258. }
  10259. $ref_roles = array_values($merged_roles);
  10260. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  10261. $merged_scenes = [];
  10262. foreach($ref_scenes as $scene) {
  10263. $scene_name = getProp($scene, 'scene');
  10264. if (!isset($extra_scenes[$scene_name])) {
  10265. $merged_scenes[$scene_name] = $scene;
  10266. }
  10267. }
  10268. // 添加extra_scenes
  10269. foreach($extra_scenes as $scene_name => $scene) {
  10270. $merged_scenes[$scene_name] = $scene;
  10271. }
  10272. $ref_scenes = array_values($merged_scenes);
  10273. // 合并ref_props和extra_props(extra_props优先,去重)
  10274. $merged_props = [];
  10275. foreach($ref_props as $prop) {
  10276. $prop_name = getProp($prop, 'prop');
  10277. if (!isset($extra_props[$prop_name])) {
  10278. $merged_props[$prop_name] = $prop;
  10279. }
  10280. }
  10281. // 添加extra_props
  10282. foreach($extra_props as $prop_name => $prop) {
  10283. $merged_props[$prop_name] = $prop;
  10284. }
  10285. $ref_props = array_values($merged_props);
  10286. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  10287. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  10288. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  10289. // 构建强制主体、场景和道具提示词
  10290. $forced_roles_prompt = "";
  10291. $forced_scenes_prompt = "";
  10292. $forced_props_prompt = "";
  10293. if (!empty($extra_roles)) {
  10294. $forced_roles_list = "";
  10295. foreach($extra_roles as $role_name => $role) {
  10296. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  10297. }
  10298. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  10299. }
  10300. if (!empty($extra_scenes)) {
  10301. $forced_scenes_list = "";
  10302. foreach($extra_scenes as $scene_name => $scene) {
  10303. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  10304. }
  10305. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  10306. }
  10307. if (!empty($extra_props)) {
  10308. $forced_props_list = "";
  10309. foreach($extra_props as $prop_name => $prop) {
  10310. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  10311. }
  10312. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  10313. }
  10314. if ($anime_script_id) {
  10315. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  10316. }else if ($roles_content) {
  10317. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  10318. 主体范围:\n {$roles_content}\n
  10319. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  10320. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10321. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10322. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10323. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10324. }else {
  10325. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  10326. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10327. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10328. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10329. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10330. }
  10331. if ($anime_script_id) {
  10332. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  10333. }else if ($scenes_content) {
  10334. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10335. 场景范围:\n {$scenes_content}\n
  10336. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  10337. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  10338. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10339. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10340. }else {
  10341. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10342. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  10343. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10344. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10345. }
  10346. if ($anime_script_id) {
  10347. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  10348. }else if ($props_content) {
  10349. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10350. 道具范围:\n {$props_content}\n
  10351. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  10352. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  10353. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10354. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10355. }else {
  10356. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10357. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  10358. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10359. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10360. }
  10361. // 提取文件内容
  10362. if ($file) {
  10363. $uploaded_content = $this->extractFileContent($file);
  10364. if (!$uploaded_content) {
  10365. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  10366. }
  10367. } elseif ($script_id) {
  10368. $uploaded_content = $this->getContentByScriptId($script_id);
  10369. if (!$uploaded_content) {
  10370. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  10371. }
  10372. } elseif ($bid) {
  10373. $uploaded_content = $this->getContentByBid($bid);
  10374. if (!$uploaded_content) {
  10375. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  10376. }
  10377. } elseif ($content) {
  10378. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  10379. }
  10380. // elseif ($prompt) {
  10381. // $uploaded_content = filterContent($prompt);
  10382. // }
  10383. else {
  10384. $uploaded_content = '';
  10385. }
  10386. // 美术风格
  10387. $input_art_style = getProp($data, 'art_style');
  10388. if (!$input_art_style) {
  10389. $mappedArtStyle = getProp($anime, 'art_style');
  10390. }else {
  10391. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  10392. }
  10393. if (!$mappedArtStyle) {
  10394. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  10395. }else {
  10396. if (strstr($mappedArtStyle, '基础画风风格词')) {
  10397. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  10398. }else {
  10399. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  10400. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  10401. }
  10402. }
  10403. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10404. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  10405. // 强制要求:
  10406. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  10407. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  10408. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  10409. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  10410. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  10411. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  10412. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  10413. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  10414. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  10415. // 10.分镜要和场景列表、人物主体保持一致\n
  10416. // 普通要求:
  10417. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10418. // {$role_demo}
  10419. // {$scene_demo}
  10420. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10421. // 4.1片段分割逻辑(优先级从高到低):
  10422. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10423. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10424. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10425. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10426. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10427. // - 片段数量格式为: 片段数量:8
  10428. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10429. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10430. // 4.3分镜结构:每个分镜包含以下字段:
  10431. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  10432. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  10433. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10434. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  10435. // - 运镜:场景+画面描述+运镜
  10436. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  10437. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10438. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10439. // 5.$mappedArtStyle_prompt\n\n
  10440. // 示例格式:\n
  10441. // 第1集:隐形的守护者
  10442. // ###故事梗概
  10443. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10444. // ###美术风格
  10445. // 基础画风风格词:胡金铨武侠
  10446. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10447. // ###主体列表
  10448. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10449. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10450. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10451. // ###场景列表
  10452. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10453. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10454. // ###分段剧本
  10455. // 片段数量:8
  10456. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10457. // ##片段1
  10458. // 时长:12s
  10459. // 分镜1
  10460. // 场景:边境小镇街道
  10461. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10462. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10463. // 配音台词:
  10464. // 背景音效:
  10465. // 分镜2
  10466. // 场景:悦来酒馆
  10467. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10468. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10469. // 配音台词:
  10470. // 背景音效:
  10471. // 分镜3
  10472. // 场景:悦来酒馆
  10473. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10474. // 运镜:从中景推向令牌特写。
  10475. // 配音台词:
  10476. // 背景音效:
  10477. // 分镜4
  10478. // 场景:悦来酒馆
  10479. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10480. // 运镜:极速推向酒水溅起的瞬间。
  10481. // 配音台词:
  10482. // 背景音效:
  10483. // 分镜5
  10484. // 镜头描述
  10485. // 场景:悦来酒馆
  10486. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10487. // 运镜:固定机位,利用倾斜构图制造压迫感。
  10488. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10489. // 背景音效:
  10490. // \n\n";
  10491. /*
  10492. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  10493. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  10494. // ===================================================================
  10495. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10496. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10497. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10498. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10499. 强制要求:
  10500. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10501. 普通要求:
  10502. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10503. {$role_demo}
  10504. {$scene_demo}
  10505. {$prop_demo}
  10506. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10507. 5.1片段分割逻辑(优先级从高到低):
  10508. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10509. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10510. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10511. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10512. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10513. - 片段数量格式为: 片段数量:8
  10514. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10515. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10516. 5.3分镜结构:每个分镜包含以下字段:
  10517. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10518. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10519. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10520. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10521. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10522. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10523. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10524. - 运镜:场景+画面描述+运镜
  10525. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10526. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10527. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10528. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10529. 6.《情绪-视听语言映射表》:
  10530. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10531. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10532. -----|---------|------------|----------------
  10533. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10534. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10535. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10536. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10537. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10538. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10539. -----|---------|------------|----------------
  10540. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10541. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10542. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10543. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10544. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10545. --------|---------|--------------|-------------
  10546. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10547. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10548. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10549. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10550. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10551. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10552. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10553. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10554. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10555. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10556. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10557. -----|---------|------------|------------
  10558. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10559. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10560. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10561. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10562. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10563. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10564. --------|---------|--------------|----------
  10565. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10566. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10567. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10568. 6.6 声音设计与潜意识影响 (Soundscape)
  10569. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10570. -----|---------|------------|------------------
  10571. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10572. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10573. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10574. 理论基石:
  10575. - The Five C's of Cinematography by Joseph V. Mascelli
  10576. - Film Art: An Introduction by David Bordwell
  10577. - Sight, Sound, Motion by Herbert Zettl
  10578. - Notes on the Cinematograph by Robert Bresson
  10579. \n\n
  10580. 7.{$mappedArtStyle_prompt}
  10581. 示例格式:\n
  10582. 第1集:隐形的守护者
  10583. ###故事梗概
  10584. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10585. ###美术风格
  10586. 基础画风风格词:胡金铨武侠
  10587. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10588. ###主体列表
  10589. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10590. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10591. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10592. ###场景列表
  10593. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10594. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10595. ###道具列表
  10596. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10597. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10598. ###分段剧本
  10599. 片段数量:8
  10600. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10601. ##片段1
  10602. 时长:12s
  10603. 分镜1
  10604. 出场角色:刀疤脸
  10605. 场景:边境小镇街道
  10606. 出场道具:酒杯-高脚杯
  10607. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10608. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10609. 配音台词:
  10610. 背景音效:
  10611. 分镜2
  10612. 出场角色:刀疤脸
  10613. 场景:悦来酒馆
  10614. 出场道具:酒杯-高脚杯
  10615. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10616. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10617. 配音台词:
  10618. 背景音效:
  10619. 分镜3
  10620. 出场角色:刀疤脸
  10621. 场景:悦来酒馆
  10622. 出场道具:酒杯-高脚杯
  10623. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10624. 运镜:从中景推向令牌特写。
  10625. 配音台词:
  10626. 背景音效:
  10627. 分镜4
  10628. 出场角色:刀疤脸
  10629. 场景:悦来酒馆
  10630. 出场道具:酒杯-高脚杯
  10631. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10632. 运镜:极速推向酒水溅起的瞬间。
  10633. 配音台词:
  10634. 背景音效:
  10635. 分镜5
  10636. 出场角色:刀疤脸
  10637. 场景:悦来酒馆
  10638. 出场道具:酒杯-高脚杯
  10639. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10640. 运镜:固定机位,利用倾斜构图制造压迫感。
  10641. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10642. 背景音效:
  10643. \n\n";
  10644. */
  10645. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10646. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10647. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10648. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10649. 强制要求:
  10650. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10651. 普通要求:
  10652. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  10653. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  10654. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  10655. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  10656. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10657. 5.1片段分割逻辑(优先级从高到低):
  10658. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10659. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10660. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10661. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10662. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10663. - 片段数量格式为: 片段数量:8
  10664. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10665. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10666. 5.3分镜结构:每个分镜包含以下字段:
  10667. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  10668. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10669. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10670. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10671. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10672. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10673. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10674. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10675. - 运镜:场景+画面描述+运镜
  10676. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10677. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10678. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10679. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10680. 6.《情绪-视听语言映射表》:
  10681. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10682. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10683. -----|---------|------------|----------------
  10684. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10685. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10686. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10687. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10688. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10689. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10690. -----|---------|------------|----------------
  10691. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10692. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10693. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10694. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10695. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10696. --------|---------|--------------|-------------
  10697. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10698. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10699. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10700. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10701. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10702. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10703. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10704. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10705. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10706. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10707. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10708. -----|---------|------------|------------
  10709. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10710. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10711. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10712. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10713. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10714. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10715. --------|---------|--------------|----------
  10716. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10717. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10718. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10719. 6.6 声音设计与潜意识影响 (Soundscape)
  10720. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10721. -----|---------|------------|------------------
  10722. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10723. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10724. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10725. 理论基石:
  10726. - The Five C's of Cinematography by Joseph V. Mascelli
  10727. - Film Art: An Introduction by David Bordwell
  10728. - Sight, Sound, Motion by Herbert Zettl
  10729. - Notes on the Cinematograph by Robert Bresson
  10730. \n\n
  10731. 7.美术风格要求见文末【本次生成数据-美术风格】。
  10732. 示例格式:\n
  10733. 第1集:隐形的守护者
  10734. ###故事梗概
  10735. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10736. ###美术风格
  10737. 基础画风风格词:胡金铨武侠
  10738. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10739. ###主体列表
  10740. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10741. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10742. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10743. ###场景列表
  10744. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10745. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10746. ###道具列表
  10747. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10748. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10749. ###分段剧本
  10750. 片段数量:8
  10751. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10752. ##片段1
  10753. 时长:12s
  10754. 分镜1
  10755. 出场角色:刀疤脸
  10756. 场景:边境小镇街道
  10757. 出场道具:酒杯-高脚杯
  10758. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10759. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10760. 配音台词:
  10761. 背景音效:
  10762. 分镜2
  10763. 出场角色:刀疤脸
  10764. 场景:悦来酒馆
  10765. 出场道具:酒杯-高脚杯
  10766. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10767. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10768. 配音台词:
  10769. 背景音效:
  10770. 分镜3
  10771. 出场角色:刀疤脸
  10772. 场景:悦来酒馆
  10773. 出场道具:酒杯-高脚杯
  10774. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10775. 运镜:从中景推向令牌特写。
  10776. 配音台词:
  10777. 背景音效:
  10778. 分镜4
  10779. 出场角色:刀疤脸
  10780. 场景:悦来酒馆
  10781. 出场道具:酒杯-高脚杯
  10782. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10783. 运镜:极速推向酒水溅起的瞬间。
  10784. 配音台词:
  10785. 背景音效:
  10786. 分镜5
  10787. 出场角色:刀疤脸
  10788. 场景:悦来酒馆
  10789. 出场道具:酒杯-高脚杯
  10790. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10791. 运镜:固定机位,利用倾斜构图制造压迫感。
  10792. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10793. 背景音效:
  10794. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  10795. 【本次剧集信息】剧集序号是{$episode_number}。
  10796. 【本次生成数据-主体列表】{$role_demo}
  10797. 【本次生成数据-场景列表】{$scene_demo}
  10798. 【本次生成数据-道具列表】{$prop_demo}
  10799. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  10800. \n\n";
  10801. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10802. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  10803. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  10804. $is_regenerate_version = true;
  10805. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  10806. $prompt = $origin_prompt;
  10807. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  10808. // 获取章节内容
  10809. $full_content = getProp($anime, 'content');
  10810. if ($uploaded_content) {
  10811. $full_content = $uploaded_content;
  10812. }
  10813. // 根据章节内容拆分章节
  10814. $chapters = splitContent($full_content);
  10815. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  10816. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  10817. $messages = [];
  10818. if ($prompt == '确认分镜大纲') {
  10819. // 暂时保留
  10820. $content = $chapter_content;
  10821. if ($is_single) $content = $full_content; // 单剧集使用全文
  10822. if (!$content) {
  10823. Utils::throwError('20003:章节内容无法获取,请确认');
  10824. }
  10825. $question = $is_single
  10826. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  10827. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  10828. // 构建消息
  10829. $messages[] =
  10830. [
  10831. 'role' => 'user',
  10832. 'content' => $question
  10833. ];
  10834. }else if ($prompt == '继续策划下一集') {
  10835. if ($is_single) {
  10836. Utils::throwError('20003:单剧集不支持继续策划下一集');
  10837. }
  10838. $content = $chapter_content;
  10839. if (!$content) {
  10840. Utils::throwError('20003:章节内容无法获取,请确认');
  10841. }
  10842. // 获取上一集最后记录
  10843. $prev_sequence = $episode_number - 1;
  10844. $messages = array_merge(
  10845. [
  10846. [
  10847. 'role' => 'system',
  10848. 'content' => $demo
  10849. ]
  10850. ],
  10851. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  10852. );
  10853. // 构建消息
  10854. $messages[] =
  10855. [
  10856. 'role' => 'user',
  10857. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  10858. ];
  10859. /*
  10860. // 旧版逻辑
  10861. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  10862. // 构建消息
  10863. $messages[] =
  10864. [
  10865. 'role' => 'user',
  10866. 'content' => $question
  10867. ];
  10868. */
  10869. // dd($messages);
  10870. }else {
  10871. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  10872. if (!$content) {
  10873. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  10874. }
  10875. if (!$content) {
  10876. Utils::throwError('20003:章节内容无法获取,请确认');
  10877. }
  10878. $messages = array_merge(
  10879. [
  10880. [
  10881. 'role' => 'system',
  10882. 'content' => $demo
  10883. ]
  10884. ],
  10885. $this->getEpisodeChatMessages($anime_id, $episode_number)
  10886. );
  10887. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  10888. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  10889. if ($origin_prompt) {
  10890. $question .= "本次修改要求如下:\n{$origin_prompt}";
  10891. }
  10892. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  10893. $messages[] = [
  10894. 'role' => 'user',
  10895. 'content' => "本集剧情内容:\n\n{$content}\n"
  10896. ];
  10897. $messages[] =
  10898. [
  10899. 'role' => 'user',
  10900. 'content' => $question
  10901. ];
  10902. }
  10903. // 处理文本模型
  10904. $model = getProp($data, 'model');
  10905. if (!$model) {
  10906. // 用户没有输入,从anime表获取
  10907. $model = getProp($anime, 'model');
  10908. if (!$model) {
  10909. // anime表也没有,使用默认值
  10910. $model = 'deepseek-v4-pro';
  10911. }
  10912. }
  10913. // 验证模型是否在可用模型表中
  10914. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10915. $model = 'deepseek-v4-pro';
  10916. }
  10917. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  10918. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  10919. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  10920. if ($model === 'deepseek-chat') {
  10921. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  10922. $model = 'deepseek-v4-flash';
  10923. $thinkingMode = 'disabled';
  10924. } elseif ($model === 'deepseek-reasoner') {
  10925. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  10926. $model = 'deepseek-v4-flash';
  10927. $thinkingMode = 'enabled';
  10928. }
  10929. $post_data = [
  10930. 'model' => $model,
  10931. 'messages' => $messages,
  10932. // 'max_tokens' => 8192,
  10933. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10934. 'frequency_penalty' => 0,
  10935. 'presence_penalty' => 0,
  10936. 'response_format' => ['type' => 'text'],
  10937. 'thinking' => ['type' => $thinkingMode],
  10938. 'stream' => true // 启用流式输出
  10939. ];
  10940. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10941. // 根据模型类型选择调用方法
  10942. $fullContent = '';
  10943. $fullReasoningContent = '';
  10944. $usage = [];
  10945. try {
  10946. $streamGenerator = $this->dispatchStreamByModel($post_data);
  10947. // 验证返回值类型
  10948. if (!is_iterable($streamGenerator)) {
  10949. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  10950. dLog('deepseek')->error('chat流式生成器无效', [
  10951. 'generator_type' => $errorType,
  10952. 'model' => $model,
  10953. 'anime_id' => $anime_id,
  10954. 'episode_number' => $episode_number
  10955. ]);
  10956. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  10957. 'type' => $errorType,
  10958. 'model' => $model
  10959. ]);
  10960. yield [
  10961. 'type' => 'error',
  10962. 'episode' => [],
  10963. 'answer' => '',
  10964. 'reasoning' => '',
  10965. 'usage' => [],
  10966. 'error' => '接口返回数据异常,请重新请求'
  10967. ];
  10968. return;
  10969. }
  10970. // 处理流式输出
  10971. foreach ($streamGenerator as $chunk) {
  10972. if (isset($chunk['type'])) {
  10973. if ($chunk['type'] === 'done') {
  10974. // 最终结果
  10975. $fullContent = $chunk['full_content'];
  10976. $fullReasoningContent = $chunk['full_reasoning'];
  10977. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  10978. } else {
  10979. // 逐块yield数据
  10980. yield $chunk;
  10981. }
  10982. }
  10983. }
  10984. } catch (\Exception $e) {
  10985. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  10986. 'model' => $model,
  10987. 'anime_id' => $anime_id,
  10988. 'episode_number' => $episode_number,
  10989. 'trace' => $e->getTraceAsString()
  10990. ]);
  10991. logDB('deepseek', 'error', 'chat流式处理失败', [
  10992. 'error' => $e->getMessage(),
  10993. 'model' => $model
  10994. ]);
  10995. yield [
  10996. 'type' => 'error',
  10997. 'episode' => [],
  10998. 'answer' => '',
  10999. 'reasoning' => '',
  11000. 'usage' => [],
  11001. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  11002. ];
  11003. return;
  11004. }
  11005. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  11006. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11007. dLog('deepseek')->info('完整内容: '.$fullContent);
  11008. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  11009. // 处理完整内容并返回最终结果
  11010. $episode_arr = handleEpisodeContentForAce($fullContent);
  11011. dLog('deepseek')->info('解析内容: ', $episode_arr);
  11012. logDB('deepseek', 'info', '解析内容', $episode_arr);
  11013. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  11014. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11015. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11016. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  11017. // }
  11018. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  11019. $max_retries = 3;
  11020. $retry_count = 0;
  11021. $validation_failed = false;
  11022. $validation_error_msg = '';
  11023. // 验证生成的内容
  11024. if ($anime_script_id) {
  11025. // 检查是否有acts数据
  11026. if (empty($episode_arr['acts'])) {
  11027. $validation_failed = true;
  11028. $validation_error_msg = '未生成分镜剧本相关的内容';
  11029. } else {
  11030. // 校验主体列表:不能为空主体(旁白不算)
  11031. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11032. // 过滤掉"旁白"角色
  11033. $generated_roles = array_filter($generated_roles, function($role) {
  11034. return $role !== '旁白';
  11035. });
  11036. if (empty($generated_roles)) {
  11037. $validation_failed = true;
  11038. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11039. }
  11040. // 仅当存在强制主体设定时校验主体列表
  11041. if (!$validation_failed && !empty($extra_roles)) {
  11042. $expected_roles = array_keys($extra_roles);
  11043. // 找出生成的主体中不在预期列表中的主体
  11044. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11045. if (!empty($invalid_roles)) {
  11046. $validation_failed = true;
  11047. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11048. }
  11049. }
  11050. // 仅当存在强制场景设定时校验场景列表
  11051. if (!$validation_failed && !empty($extra_scenes)) {
  11052. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11053. $expected_scenes = array_keys($extra_scenes);
  11054. // 找出生成的场景中不在预期列表中的场景
  11055. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11056. if (!empty($invalid_scenes)) {
  11057. $validation_failed = true;
  11058. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11059. }
  11060. }
  11061. // 仅当存在强制道具设定时校验道具列表
  11062. if (!$validation_failed && !empty($extra_props)) {
  11063. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11064. $expected_props = array_keys($extra_props);
  11065. // 找出生成的道具中不在预期列表中的道具
  11066. $invalid_props = array_diff($generated_props, $expected_props);
  11067. if (!empty($invalid_props)) {
  11068. $validation_failed = true;
  11069. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11070. }
  11071. }
  11072. }
  11073. } else {
  11074. // 如果没有anime_script_id,只检查是否有acts数据
  11075. if (empty($episode_arr['acts'])) {
  11076. $validation_failed = true;
  11077. $validation_error_msg = '未生成分镜剧本相关的内容';
  11078. } else {
  11079. // 校验主体列表:不能为空主体(旁白不算)
  11080. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11081. // 过滤掉"旁白"角色
  11082. $generated_roles = array_filter($generated_roles, function($role) {
  11083. return $role !== '旁白';
  11084. });
  11085. if (empty($generated_roles)) {
  11086. $validation_failed = true;
  11087. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11088. }
  11089. }
  11090. }
  11091. // 重试逻辑
  11092. while ($validation_failed && $retry_count < $max_retries) {
  11093. $retry_count++;
  11094. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  11095. 'reason' => $validation_error_msg,
  11096. 'anime_id' => $anime_id,
  11097. 'episode_number' => $episode_number
  11098. ]);
  11099. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  11100. 'reason' => $validation_error_msg,
  11101. 'anime_id' => $anime_id
  11102. ]);
  11103. // 发送流式重试提示
  11104. yield [
  11105. 'type' => 'retry',
  11106. 'retry_count' => $retry_count,
  11107. 'reason' => $validation_error_msg
  11108. ];
  11109. // 构建重试提示词
  11110. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  11111. if ($anime_script_id) {
  11112. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  11113. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11114. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  11115. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  11116. } else {
  11117. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11118. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  11119. }
  11120. // 添加重试消息到messages
  11121. $messages[] = [
  11122. 'role' => 'assistant',
  11123. 'content' => $fullContent
  11124. ];
  11125. $messages[] = [
  11126. 'role' => 'user',
  11127. 'content' => $retry_prompt
  11128. ];
  11129. // 更新post_data的messages
  11130. $post_data['messages'] = $messages;
  11131. // 重新调用API
  11132. try {
  11133. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11134. // 处理流式输出
  11135. $fullContent = '';
  11136. $fullReasoningContent = '';
  11137. foreach ($streamGenerator as $chunk) {
  11138. if (isset($chunk['type'])) {
  11139. if ($chunk['type'] === 'done') {
  11140. $fullContent = $chunk['full_content'];
  11141. $fullReasoningContent = $chunk['full_reasoning'];
  11142. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11143. } else {
  11144. yield $chunk;
  11145. }
  11146. }
  11147. }
  11148. // 重新解析内容
  11149. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11150. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  11151. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  11152. $episode_arr = handleEpisodeContentForAce($fullContent);
  11153. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  11154. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11155. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11156. // }
  11157. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  11158. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  11159. // 重新验证
  11160. $validation_failed = false;
  11161. $validation_error_msg = '';
  11162. if ($anime_script_id) {
  11163. if (empty($episode_arr['acts'])) {
  11164. $validation_failed = true;
  11165. $validation_error_msg = '未生成分镜剧本相关的内容';
  11166. } else {
  11167. // 校验主体列表:不能为空主体(旁白不算)
  11168. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11169. // 过滤掉"旁白"角色
  11170. $generated_roles = array_filter($generated_roles, function($role) {
  11171. return $role !== '旁白';
  11172. });
  11173. if (empty($generated_roles)) {
  11174. $validation_failed = true;
  11175. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11176. }
  11177. // 仅当存在强制主体设定时校验主体列表
  11178. if (!$validation_failed && !empty($extra_roles)) {
  11179. $expected_roles = array_keys($extra_roles);
  11180. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11181. if (!empty($invalid_roles)) {
  11182. $validation_failed = true;
  11183. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11184. }
  11185. }
  11186. // 仅当存在强制场景设定时校验场景列表
  11187. if (!$validation_failed && !empty($extra_scenes)) {
  11188. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11189. $expected_scenes = array_keys($extra_scenes);
  11190. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11191. if (!empty($invalid_scenes)) {
  11192. $validation_failed = true;
  11193. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11194. }
  11195. }
  11196. // 仅当存在强制道具设定时校验道具列表
  11197. if (!$validation_failed && !empty($extra_props)) {
  11198. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11199. $expected_props = array_keys($extra_props);
  11200. $invalid_props = array_diff($generated_props, $expected_props);
  11201. if (!empty($invalid_props)) {
  11202. $validation_failed = true;
  11203. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11204. }
  11205. }
  11206. }
  11207. } else {
  11208. if (empty($episode_arr['acts'])) {
  11209. $validation_failed = true;
  11210. $validation_error_msg = '未生成分镜剧本相关的内容';
  11211. } else {
  11212. // 校验主体列表:不能为空主体(旁白不算)
  11213. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11214. // 过滤掉"旁白"角色
  11215. $generated_roles = array_filter($generated_roles, function($role) {
  11216. return $role !== '旁白';
  11217. });
  11218. if (empty($generated_roles)) {
  11219. $validation_failed = true;
  11220. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11221. }
  11222. }
  11223. }
  11224. } catch (\Exception $e) {
  11225. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  11226. 'trace' => $e->getTraceAsString()
  11227. ]);
  11228. break;
  11229. }
  11230. }
  11231. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  11232. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  11233. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  11234. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  11235. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  11236. if ($validation_failed && $retry_count >= $max_retries) {
  11237. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  11238. 'retry_count' => $retry_count,
  11239. 'last_error' => $validation_error_msg
  11240. ]);
  11241. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  11242. 'error' => $validation_error_msg,
  11243. 'anime_id' => $anime_id
  11244. ]);
  11245. $validation_failed = false;
  11246. $validation_error_msg = '';
  11247. }
  11248. // 如果重试后仍然失败
  11249. if ($validation_failed) {
  11250. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  11251. 'retry_count' => $retry_count,
  11252. 'last_error' => $validation_error_msg
  11253. ]);
  11254. try {
  11255. $now = date('Y-m-d H:i:s');
  11256. $records = [
  11257. [
  11258. 'uid' => $uid,
  11259. 'anime_id' => $anime_id,
  11260. 'sequence' => $episode_number,
  11261. 'role' => 'user',
  11262. 'content' => $prompt,
  11263. 'created_at' => $now,
  11264. 'updated_at' => $now
  11265. ],
  11266. [
  11267. 'uid' => $uid,
  11268. 'anime_id' => $anime_id,
  11269. 'sequence' => $episode_number,
  11270. 'role' => 'assistant',
  11271. 'content' => $fullContent,
  11272. 'created_at' => $now,
  11273. 'updated_at' => $now
  11274. ]
  11275. ];
  11276. DB::table('mp_anime_records')->insert($records);
  11277. } catch (\Exception $e) {
  11278. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  11279. }
  11280. yield [
  11281. 'type' => 'done',
  11282. 'episode' => [],
  11283. 'answer' => $fullContent,
  11284. 'reasoning' => $fullReasoningContent,
  11285. 'usage' => $usage,
  11286. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  11287. ];
  11288. return;
  11289. }
  11290. // 验证成功,记录日志
  11291. if ($retry_count > 0) {
  11292. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  11293. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  11294. }
  11295. // 老逻辑
  11296. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  11297. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  11298. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  11299. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  11300. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  11301. $existing_props = is_array($existing_props) ? $existing_props : [];
  11302. $now = date('Y-m-d H:i:s');
  11303. try {
  11304. DB::beginTransaction();
  11305. $saveResult = $this->saveEpisodeVersionData(
  11306. $anime_id,
  11307. $episode_number,
  11308. $episode_arr,
  11309. $existing_roles,
  11310. $existing_scenes,
  11311. $existing_props,
  11312. $current_episode,
  11313. $base_episode,
  11314. $is_regenerate_version,
  11315. $content,
  11316. $now,
  11317. $ref_products
  11318. );
  11319. $episode = $saveResult['episode'];
  11320. $episode_id = $saveResult['episode_id'];
  11321. $merged_roles = $saveResult['merged_roles'];
  11322. $merged_scenes = $saveResult['merged_scenes'];
  11323. $merged_props = $saveResult['merged_props'];
  11324. $record_content = $origin_prompt;
  11325. if ($uploaded_content !== '') {
  11326. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  11327. }
  11328. $records = [
  11329. [
  11330. 'uid' => $uid,
  11331. 'anime_id' => $anime_id,
  11332. 'role' => 'user',
  11333. 'content' => $record_content,
  11334. 'sequence' => $episode_number,
  11335. 'episode_id' => $episode_id,
  11336. 'created_at' => $now,
  11337. 'updated_at' => $now
  11338. ],
  11339. [
  11340. 'uid' => $uid,
  11341. 'anime_id' => $anime_id,
  11342. 'role' => 'assistant',
  11343. 'content' => $fullContent,
  11344. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  11345. 'sequence' => $episode_number,
  11346. 'episode_id' => $episode_id,
  11347. 'created_at' => $now,
  11348. 'updated_at' => $now
  11349. ]
  11350. ];
  11351. $boolen4 = DB::table('mp_anime_records')->insert($records);
  11352. if (!$boolen4) {
  11353. Utils::throwError('20003:对话记录保存失败');
  11354. }
  11355. // 保存模型到anime表
  11356. $update_anime_data = [
  11357. 'model' => $model,
  11358. 'updated_at' => $now
  11359. ];
  11360. if ($uploaded_content) {
  11361. $update_anime_data['content'] = $uploaded_content;
  11362. }
  11363. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  11364. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11365. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11366. 'anime_id' => $anime_id,
  11367. 'episode_number' => $episode_number,
  11368. 'model' => $model,
  11369. 'source' => 'chatForAce',
  11370. ]);
  11371. }catch (\Exception $e) {
  11372. DB::rollBack();
  11373. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  11374. yield [
  11375. 'type' => 'done',
  11376. 'answer' => $fullContent,
  11377. 'reasoning' => $fullReasoningContent,
  11378. 'usage' => $usage,
  11379. 'error' => $e->getMessage(),
  11380. ];
  11381. return;
  11382. }
  11383. DB::commit();
  11384. if ($is_global_generate_pics) {
  11385. // // 批量生成全局角色图片
  11386. // $this->batchSetGlobalRoleImg([
  11387. // 'anime_id' => $anime_id,
  11388. // ], true);
  11389. // // 批量生成全局场景图片
  11390. // $this->batchSetGlobalSceneImg([
  11391. // 'anime_id' => $anime_id,
  11392. // ], true);
  11393. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  11394. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  11395. }
  11396. $episode['episode_id'] = $episode_id;
  11397. $episode['roles'] = $merged_roles;
  11398. $episode['scenes'] = $merged_scenes;
  11399. $episode['props'] = $merged_props;
  11400. $episode['end_episode_sequence'] = $end_episode_sequence;
  11401. // 获取mp_animes表中的视频参数
  11402. $episode['video_params'] = [
  11403. 'video_model' => getProp($anime, 'video_model'),
  11404. 'video_resolution' => getProp($anime, 'video_resolution'),
  11405. 'ratio' => getProp($anime, 'video_ratio'),
  11406. ];
  11407. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11408. yield [
  11409. 'type' => 'done',
  11410. 'episode' => $episode,
  11411. 'answer' => $fullContent,
  11412. 'reasoning' => $fullReasoningContent,
  11413. 'usage' => $usage
  11414. ];
  11415. }
  11416. /**
  11417. * chatForAce的非流式版本 - 用于定时任务
  11418. * 只获取最终 type=done 的数据,并验证必要字段
  11419. *
  11420. * @param array $data 请求数据
  11421. * @return array 生成结果
  11422. */
  11423. public function chatForAceNonStream($data) {
  11424. $finalResult = null;
  11425. // 调用流式方法,只保存 type=done 的数据
  11426. foreach ($this->chatForAce($data) as $chunk) {
  11427. // 只关注最终结果
  11428. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  11429. $finalResult = $chunk;
  11430. break; // 找到 done 就退出循环
  11431. }
  11432. }
  11433. // 验证最终结果
  11434. if (!$finalResult) {
  11435. return ['error' => '生成失败:未获取到最终结果'];
  11436. }
  11437. // 检查是否有错误
  11438. if (isset($finalResult['error']) && $finalResult['error']) {
  11439. return $finalResult;
  11440. }
  11441. // 验证必要字段
  11442. $episode = $finalResult['episode'] ?? [];
  11443. // 验证 roles(旁白不算主体,过滤后不能为空)
  11444. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  11445. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  11446. }
  11447. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  11448. return $role !== '旁白';
  11449. });
  11450. if (empty($nonNarratorRoles)) {
  11451. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  11452. }
  11453. // 验证 scenes
  11454. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  11455. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  11456. }
  11457. // 验证 props(道具可以为空,但必须存在且为数组)
  11458. if (!isset($episode['props']) || !is_array($episode['props'])) {
  11459. $episode['props'] = [];
  11460. }
  11461. // 验证 acts(分镜剧本)
  11462. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  11463. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  11464. }
  11465. // 更新验证后的 episode 数据
  11466. $finalResult['episode'] = $episode;
  11467. // 记录验证成功日志
  11468. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  11469. 'roles_count' => count($episode['roles']),
  11470. 'scenes_count' => count($episode['scenes']),
  11471. 'props_count' => count($episode['props']),
  11472. 'acts_count' => count($episode['acts'])
  11473. ]);
  11474. return $finalResult;
  11475. }
  11476. /**
  11477. * 批量生成多个分集
  11478. *
  11479. * @param array $data 请求数据
  11480. * @return array 任务信息
  11481. */
  11482. public function batchGenerateEpisodes($data) {
  11483. $uid = Site::getUid();
  11484. $cpid = Site::getCpid();
  11485. $anime_id = getProp($data, 'anime_id');
  11486. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  11487. $start_episode_number = getProp($data, 'start_episode_number');
  11488. $end_episode_number = getProp($data, 'end_episode_number');
  11489. if (!$anime_id) {
  11490. Utils::throwError('20003:anime_id参数缺失');
  11491. }
  11492. if ($generate_episode_number < 1) {
  11493. Utils::throwError('20003:生成集数必须大于0');
  11494. }
  11495. // 获取动漫信息
  11496. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11497. if (!$anime) {
  11498. Utils::throwError('20003:该剧集不存在');
  11499. }
  11500. // 检查是否是全能模式
  11501. if ((int)getProp($anime, 'ace_mode') !== 1) {
  11502. Utils::throwError('20003:只有全能模式才支持批量生成');
  11503. }
  11504. // 检查是否是多剧集模式
  11505. if ((int)getProp($anime, 'is_multi') !== 1) {
  11506. Utils::throwError('20003:单剧集不支持批量生成');
  11507. }
  11508. // 指定起始/结束剧集序号时的校验
  11509. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  11510. || ($end_episode_number !== null && $end_episode_number !== '');
  11511. if ($hasSpecifiedRange) {
  11512. if ($start_episode_number === null || $start_episode_number === ''
  11513. || $end_episode_number === null || $end_episode_number === '') {
  11514. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  11515. }
  11516. $start_episode_number = (int)$start_episode_number;
  11517. $end_episode_number = (int)$end_episode_number;
  11518. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  11519. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  11520. }
  11521. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  11522. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11523. ->where('anime_id', $anime_id)
  11524. ->where('is_default', 1)
  11525. ->max('episode_number');
  11526. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11527. $nextEpisodeNumber = $currentMaxEpisode + 1;
  11528. if ($start_episode_number !== $nextEpisodeNumber) {
  11529. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  11530. }
  11531. $startEpisodeNumber = $start_episode_number;
  11532. $endEpisodeNumber = $end_episode_number;
  11533. } else {
  11534. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  11535. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11536. ->where('anime_id', $anime_id)
  11537. ->where('is_default', 1)
  11538. ->max('episode_number');
  11539. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11540. // 确定起始集数
  11541. $startEpisodeNumber = $currentMaxEpisode + 1;
  11542. // 计算结束集数
  11543. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  11544. }
  11545. // 本次实际生成的集数
  11546. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  11547. // 检查是否超过总集数限制
  11548. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  11549. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  11550. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  11551. }
  11552. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  11553. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  11554. ->where('anime_id', $anime_id)
  11555. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11556. ->pluck('episode_number')
  11557. ->unique()
  11558. ->sort()
  11559. ->values()
  11560. ->toArray();
  11561. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  11562. ->where('anime_id', $anime_id)
  11563. ->where('is_default', 1)
  11564. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11565. ->pluck('episode_number')
  11566. ->unique()
  11567. ->sort()
  11568. ->values()
  11569. ->toArray();
  11570. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  11571. $duplicateMessages = [];
  11572. if (!empty($duplicatedBatchEpisodes)) {
  11573. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  11574. }
  11575. if (!empty($duplicatedAnimeEpisodes)) {
  11576. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  11577. }
  11578. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  11579. }
  11580. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  11581. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  11582. ->where('anime_id', $anime_id)
  11583. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11584. ->whereIn('status', ['pending', 'processing', 'completed'])
  11585. ->count();
  11586. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  11587. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  11588. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  11589. if ($needEpisodeCount > 0) {
  11590. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  11591. }
  11592. $now = date('Y-m-d H:i:s');
  11593. $createdTasks = [];
  11594. $skippedTasks = [];
  11595. // 为每一集创建详情记录
  11596. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  11597. // 检查是否已有该集的任务记录
  11598. $existingTask = DB::table('mp_batch_episode_generation_details')
  11599. ->where('anime_id', $anime_id)
  11600. ->where('episode_number', $episodeNumber)
  11601. ->first();
  11602. if ($existingTask) {
  11603. // 如果已存在且未完成,跳过
  11604. if (in_array($existingTask->status, ['pending', 'processing'])) {
  11605. $skippedTasks[] = $episodeNumber;
  11606. continue;
  11607. }
  11608. // 如果是失败状态,可以重新创建(删除旧记录)
  11609. if ($existingTask->status === 'failed') {
  11610. DB::table('mp_batch_episode_generation_details')
  11611. ->where('id', $existingTask->id)
  11612. ->delete();
  11613. }
  11614. // 如果是已完成状态,也跳过
  11615. if ($existingTask->status === 'completed') {
  11616. $skippedTasks[] = $episodeNumber;
  11617. continue;
  11618. }
  11619. }
  11620. // 准备任务数据
  11621. $taskData = [
  11622. 'anime_id' => $anime_id,
  11623. 'uid' => $uid,
  11624. 'cpid' => $cpid,
  11625. 'episode_number' => $episodeNumber,
  11626. 'status' => 'pending',
  11627. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  11628. 'retry_count' => 0,
  11629. 'created_at' => $now,
  11630. 'updated_at' => $now
  11631. ];
  11632. // 创建任务记录
  11633. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  11634. if ($taskId) {
  11635. $createdTasks[] = $episodeNumber;
  11636. }
  11637. }
  11638. if (empty($createdTasks)) {
  11639. if (!empty($skippedTasks)) {
  11640. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  11641. } else {
  11642. Utils::throwError('20003:创建批量生成任务失败');
  11643. }
  11644. }
  11645. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  11646. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  11647. $uid,
  11648. $cpid,
  11649. $anime_id,
  11650. $generate_episode_number,
  11651. $startEpisodeNumber,
  11652. $endEpisodeNumber
  11653. );
  11654. return [
  11655. 'anime_id' => $anime_id,
  11656. 'start_episode' => $startEpisodeNumber,
  11657. 'end_episode' => $endEpisodeNumber,
  11658. 'total_episodes' => $totalEpisodeCount,
  11659. 'created_episodes' => $createdTasks,
  11660. 'skipped_episodes' => $skippedTasks,
  11661. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  11662. "已创建: " . implode(',', $createdTasks) .
  11663. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  11664. 'task_center_id' => $taskCenterId
  11665. ];
  11666. }
  11667. /**
  11668. * 根据入参创建或复用批量生成分集的任务中心记录
  11669. *
  11670. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  11671. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  11672. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  11673. *
  11674. * @param int|string $uid
  11675. * @param int|string $cpid
  11676. * @param int|string $anime_id
  11677. * @param int $generate_episode_number
  11678. * @param int $startEpisodeNumber
  11679. * @param int $endEpisodeNumber
  11680. * @return int 任务中心ID
  11681. */
  11682. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  11683. $params = [
  11684. 'anime_id' => (int)$anime_id,
  11685. 'generate_episode_number' => (int)$generate_episode_number,
  11686. 'start_episode' => (int)$startEpisodeNumber,
  11687. 'end_episode' => (int)$endEpisodeNumber,
  11688. ];
  11689. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  11690. $paramsMd5 = md5(json_encode([
  11691. 'anime_id' => (int)$anime_id,
  11692. 'generate_episode_number' => (int)$generate_episode_number,
  11693. 'start_episode' => (int)$startEpisodeNumber,
  11694. 'end_episode' => (int)$endEpisodeNumber,
  11695. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  11696. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  11697. $existing = DB::table('mp_task_center')
  11698. ->where('uid', (int)$uid)
  11699. ->where('cpid', (int)$cpid)
  11700. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11701. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11702. ->where('params_md5', $paramsMd5)
  11703. ->orderBy('id', 'desc')
  11704. ->first();
  11705. if ($existing) {
  11706. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  11707. 'anime_id' => $anime_id,
  11708. 'task_center_id' => $existing->id,
  11709. 'params_md5' => $paramsMd5,
  11710. ]);
  11711. return (int)$existing->id;
  11712. }
  11713. $now = date('Y-m-d H:i:s');
  11714. DB::table('mp_task_center')->insertOrIgnore([
  11715. 'uid' => (int)$uid,
  11716. 'cpid' => (int)$cpid,
  11717. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  11718. 'title' => '批量生成分集',
  11719. 'ref_task_id' => 0,
  11720. 'status' => MpTaskCenter::STATUS_PROCESSING,
  11721. 'result' => null,
  11722. 'error_message' => null,
  11723. 'prompt' => null,
  11724. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  11725. 'params_md5' => $paramsMd5,
  11726. 'created_at' => $now,
  11727. 'updated_at' => $now,
  11728. ]);
  11729. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  11730. $taskId = (int)DB::table('mp_task_center')
  11731. ->where('uid', (int)$uid)
  11732. ->where('cpid', (int)$cpid)
  11733. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11734. ->where('params_md5', $paramsMd5)
  11735. ->orderBy('id', 'desc')
  11736. ->value('id');
  11737. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  11738. 'anime_id' => $anime_id,
  11739. 'task_center_id' => $taskId,
  11740. 'params_md5' => $paramsMd5,
  11741. ]);
  11742. return $taskId;
  11743. }
  11744. /**
  11745. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  11746. *
  11747. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  11748. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  11749. * 统一汇总更新,避免在每个更新点重复处理。
  11750. *
  11751. * @param int|string $animeId
  11752. * @return int 更新的任务中心记录数
  11753. */
  11754. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  11755. $animeId = (int)$animeId;
  11756. $updated = 0;
  11757. // 该 anime 是否还有未结束的详情任务
  11758. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  11759. ->where('anime_id', $animeId)
  11760. ->whereIn('status', ['pending', 'processing'])
  11761. ->exists();
  11762. // 扫描该 anime 相关的未完成任务中心记录
  11763. $tasks = DB::table('mp_task_center')
  11764. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11765. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11766. ->orderBy('id', 'desc')
  11767. ->limit(500)
  11768. ->get();
  11769. if ($hasUnfinished && !$tasks) {
  11770. return 0;
  11771. }
  11772. foreach ($tasks as $task) {
  11773. try {
  11774. $taskParams = json_decode((string)$task->params, true);
  11775. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  11776. continue;
  11777. }
  11778. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  11779. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  11780. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  11781. continue;
  11782. }
  11783. $details = DB::table('mp_batch_episode_generation_details')
  11784. ->where('anime_id', $animeId)
  11785. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  11786. ->get();
  11787. // 该批次范围内存在缺失记录,等待下一次检查
  11788. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  11789. continue;
  11790. }
  11791. $completedEpisodes = [];
  11792. $failedEpisodes = [];
  11793. $allFinished = true;
  11794. foreach ($details as $detail) {
  11795. if ($detail->status === 'completed') {
  11796. $completedEpisodes[] = $detail->episode_number;
  11797. } elseif ($detail->status === 'failed') {
  11798. $failedEpisodes[] = [
  11799. 'episode_number' => $detail->episode_number,
  11800. 'error_message' => $detail->error_message ?? '',
  11801. ];
  11802. } else {
  11803. // pending/processing(防御处理,正常不会走到)
  11804. $allFinished = false;
  11805. break;
  11806. }
  11807. }
  11808. if (!$allFinished) {
  11809. continue;
  11810. }
  11811. $result = json_encode([
  11812. 'anime_id' => $animeId,
  11813. 'start_episode' => $startEpisode,
  11814. 'end_episode' => $endEpisode,
  11815. 'total_episodes' => count($details),
  11816. 'completed_count' => count($completedEpisodes),
  11817. 'failed_count' => count($failedEpisodes),
  11818. 'completed_episodes' => $completedEpisodes,
  11819. 'failed_episodes' => $failedEpisodes,
  11820. ], JSON_UNESCAPED_UNICODE);
  11821. DB::table('mp_task_center')
  11822. ->where('id', $task->id)
  11823. ->update([
  11824. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  11825. 'result' => $result,
  11826. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  11827. 'updated_at' => date('Y-m-d H:i:s'),
  11828. ]);
  11829. $updated++;
  11830. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  11831. 'task_center_id' => $task->id,
  11832. 'anime_id' => $animeId,
  11833. 'start_episode' => $startEpisode,
  11834. 'end_episode' => $endEpisode,
  11835. ]);
  11836. } catch (\Exception $e) {
  11837. dLog('command')->error('更新批量生成分集任务中心异常', [
  11838. 'task_center_id' => $task->id,
  11839. 'anime_id' => $animeId,
  11840. 'error' => $e->getMessage(),
  11841. ]);
  11842. }
  11843. }
  11844. return $updated;
  11845. }
  11846. /**
  11847. * 获取批量生成任务状态
  11848. *
  11849. * @param array $data 请求数据
  11850. * @return array 任务状态信息
  11851. */
  11852. public function getBatchGenerationTaskStatus($data) {
  11853. $anime_id = getProp($data, 'anime_id');
  11854. if (!$anime_id) {
  11855. Utils::throwError('20003:anime_id参数缺失');
  11856. }
  11857. // 获取该anime的所有任务
  11858. $tasks = DB::table('mp_batch_episode_generation_details')
  11859. ->where('anime_id', $anime_id)
  11860. ->orderBy('episode_number')
  11861. ->get()
  11862. ->map(function($item) {
  11863. return [
  11864. 'id' => $item->id,
  11865. 'episode_number' => $item->episode_number,
  11866. 'status' => $item->status,
  11867. 'error_message' => $item->error_message,
  11868. 'retry_count' => $item->retry_count,
  11869. 'created_at' => $item->created_at,
  11870. 'updated_at' => $item->updated_at,
  11871. 'completed_at' => $item->completed_at
  11872. ];
  11873. })
  11874. ->toArray();
  11875. if (empty($tasks)) {
  11876. Utils::throwError('20003:该剧集没有批量生成任务');
  11877. }
  11878. // 统计各状态数量
  11879. $totalCount = count($tasks);
  11880. $pendingCount = 0;
  11881. $processingCount = 0;
  11882. $completedCount = 0;
  11883. $failedCount = 0;
  11884. $failed_episodes = [];
  11885. foreach ($tasks as $task) {
  11886. switch ($task['status']) {
  11887. case 'pending':
  11888. $pendingCount++;
  11889. break;
  11890. case 'processing':
  11891. $processingCount++;
  11892. break;
  11893. case 'completed':
  11894. $completedCount++;
  11895. break;
  11896. case 'failed':
  11897. $failedCount++;
  11898. // 组装失败分集对象(新对象):分集序号、错误原因
  11899. $failed_episodes[] = [
  11900. 'episode_number' => $task['episode_number'],
  11901. 'error_message' => $task['error_message'] ?? ''
  11902. ];
  11903. break;
  11904. }
  11905. }
  11906. // 计算进度百分比
  11907. $progress = 0;
  11908. if ($totalCount > 0) {
  11909. $progress = round(($completedCount / $totalCount) * 100, 2);
  11910. }
  11911. // 判断整体状态
  11912. $overallStatus = 'processing';
  11913. if ($completedCount === $totalCount) {
  11914. $overallStatus = 'completed';
  11915. } elseif ($pendingCount === $totalCount) {
  11916. $overallStatus = 'pending';
  11917. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  11918. $overallStatus = 'failed';
  11919. }
  11920. return [
  11921. 'anime_id' => $anime_id,
  11922. 'total_episodes' => $totalCount,
  11923. 'pending_count' => $pendingCount,
  11924. 'processing_count' => $processingCount,
  11925. 'completed_count' => $completedCount,
  11926. 'failed_count' => $failedCount,
  11927. 'progress' => $progress,
  11928. 'overall_status' => $overallStatus,
  11929. 'failed_episodes' => $failed_episodes,
  11930. 'tasks' => $tasks
  11931. ];
  11932. }
  11933. /**
  11934. * 将生成内容中不在强制列表中的资源合并进强制列表
  11935. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  11936. *
  11937. * @param array $generated 生成内容中的资源列表
  11938. * @param array $forced 强制资源列表(key为资源名称)
  11939. * @param string $type 资源类型:role、scene、prop
  11940. * @return array
  11941. */
  11942. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  11943. {
  11944. foreach ($generated as $item) {
  11945. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  11946. if ($name === null || $name === '') {
  11947. continue;
  11948. }
  11949. if ($name === '旁白') {
  11950. continue;
  11951. }
  11952. if (!isset($forced[$name])) {
  11953. $forced[$name] = $item;
  11954. }
  11955. }
  11956. return $forced;
  11957. }
  11958. /**
  11959. * 智能匹配并替换主体和场景名称
  11960. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  11961. *
  11962. * @param array $episode_arr 解析后的剧集数据
  11963. * @param array $extra_roles 强制主体设定(key为主体名称)
  11964. * @param array $extra_scenes 强制场景设定(key为场景名称)
  11965. * @return array 替换后的剧集数据
  11966. */
  11967. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  11968. $replaced_count = 0;
  11969. // 1. 处理主体列表
  11970. if (!empty($episode_arr['roles'])) {
  11971. foreach ($episode_arr['roles'] as &$role) {
  11972. $generated_role_name = $role['role'] ?? '';
  11973. // 跳过旁白
  11974. if ($generated_role_name === '旁白') {
  11975. continue;
  11976. }
  11977. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  11978. if (!isset($extra_roles[$generated_role_name])) {
  11979. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  11980. if ($matched_role) {
  11981. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  11982. $role['role'] = $matched_role;
  11983. $replaced_count++;
  11984. }
  11985. }
  11986. }
  11987. }
  11988. // 2. 处理场景列表
  11989. if (!empty($episode_arr['scenes'])) {
  11990. foreach ($episode_arr['scenes'] as &$scene) {
  11991. $generated_scene_name = $scene['scene'] ?? '';
  11992. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  11993. if (!isset($extra_scenes[$generated_scene_name])) {
  11994. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  11995. if ($matched_scene) {
  11996. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  11997. $scene['scene'] = $matched_scene;
  11998. $replaced_count++;
  11999. }
  12000. }
  12001. }
  12002. }
  12003. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  12004. if (!empty($episode_arr['acts'])) {
  12005. foreach ($episode_arr['acts'] as &$act) {
  12006. if (!empty($act['segments'])) {
  12007. foreach ($act['segments'] as &$segment) {
  12008. if (!empty($segment['segment_content'])) {
  12009. $original_content = $segment['segment_content'];
  12010. $replaced_content = $original_content;
  12011. // 替换场景名 - 在文本中查找并替换
  12012. foreach (array_keys($extra_scenes) as $full_scene_name) {
  12013. // 尝试找到可能的短名称
  12014. $potential_short_names = [];
  12015. // 提取场景名的主要部分(冒号之前)
  12016. if (mb_strpos($full_scene_name, ':') !== false) {
  12017. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12018. $potential_short_names[] = $short_name;
  12019. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  12020. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12021. $potential_short_names[] = $short_name;
  12022. }
  12023. // 替换场景字段中的短名称
  12024. foreach ($potential_short_names as $short_name) {
  12025. if ($short_name !== $full_scene_name) {
  12026. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  12027. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  12028. if ($new_content !== $replaced_content) {
  12029. $replaced_content = $new_content;
  12030. $replaced_count++;
  12031. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  12032. }
  12033. }
  12034. }
  12035. }
  12036. // 替换配音角色名(跳过旁白)
  12037. foreach (array_keys($extra_roles) as $full_role_name) {
  12038. if ($full_role_name === '旁白') {
  12039. continue;
  12040. }
  12041. // 尝试找到可能的短名称
  12042. $potential_short_names = [];
  12043. // 提取角色名的主要部分(短横线之前)
  12044. if (mb_strpos($full_role_name, '-') !== false) {
  12045. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  12046. $potential_short_names[] = $short_name;
  12047. }
  12048. // 替换配音台词中的短名称
  12049. foreach ($potential_short_names as $short_name) {
  12050. if ($short_name !== $full_role_name) {
  12051. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  12052. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  12053. if ($new_content !== $replaced_content) {
  12054. $replaced_content = $new_content;
  12055. $replaced_count++;
  12056. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  12057. }
  12058. }
  12059. }
  12060. }
  12061. // 如果有替换,更新segment_content
  12062. if ($replaced_content !== $original_content) {
  12063. $segment['segment_content'] = $replaced_content;
  12064. }
  12065. }
  12066. }
  12067. }
  12068. }
  12069. }
  12070. if ($replaced_count > 0) {
  12071. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  12072. 'replaced_count' => $replaced_count
  12073. ]);
  12074. }
  12075. return $episode_arr;
  12076. }
  12077. /**
  12078. * 查找匹配的名称
  12079. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  12080. *
  12081. * @param string $generated_name 生成的名称
  12082. * @param array $expected_names 预期的名称列表
  12083. * @return string|null 匹配到的名称,如果没有匹配则返回null
  12084. */
  12085. private function findMatchingName($generated_name, $expected_names) {
  12086. if (empty($generated_name)) {
  12087. return null;
  12088. }
  12089. // 尝试精确匹配
  12090. if (in_array($generated_name, $expected_names)) {
  12091. return $generated_name;
  12092. }
  12093. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  12094. foreach ($expected_names as $expected_name) {
  12095. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  12096. if (mb_strpos($expected_name, $generated_name) === 0) {
  12097. return $expected_name;
  12098. }
  12099. }
  12100. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  12101. // 这样可以处理一些变体,但优先级较低
  12102. foreach ($expected_names as $expected_name) {
  12103. if (mb_strpos($expected_name, $generated_name) !== false) {
  12104. return $expected_name;
  12105. }
  12106. }
  12107. return null;
  12108. }
  12109. /**
  12110. * 重新生成分段剧本
  12111. * @param array $data 包含以下字段:
  12112. * - prompt: string|null 用户修改要求(可选)
  12113. * - template_id: int|null 提示词模板ID(可选)
  12114. * - act_id: int|null 单个片段ID(与episode_id二选一)
  12115. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  12116. * @return array 返回生成结果
  12117. */
  12118. public function regenerateSegmentScript($data) {
  12119. $uid = Site::getUid();
  12120. $prompt = trim((string)getProp($data, 'prompt', ''));
  12121. $template_id = getProp($data, 'template_id', 0);
  12122. $act_id = getProp($data, 'act_id', 0);
  12123. $episode_id = getProp($data, 'episode_id', 0);
  12124. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  12125. // 单片段模式:act_id 可以是数据库真实ID(数字)或预览生成的虚拟ID(字符串),非空即单片段模式
  12126. $isActIdMode = !empty($act_id);
  12127. // 验证:prompt和template_id至少提供一个
  12128. if (empty($prompt) && empty($template_id)) {
  12129. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  12130. }
  12131. // 验证:act_id和episode_id二选一
  12132. if (empty($act_id) && empty($episode_id)) {
  12133. Utils::throwError('20003:请提供片段ID或剧集ID');
  12134. }
  12135. if (!empty($act_id) && !empty($episode_id)) {
  12136. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  12137. }
  12138. // 积分余额预检:act_id 单片段模式按 normal 档,episode_id 剧集模式按 special 档
  12139. $chargeType = $isActIdMode ? 'normal' : 'special';
  12140. if ($isActIdMode) {
  12141. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12142. } else {
  12143. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  12144. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  12145. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12146. }
  12147. // 如果提供了template_id,获取模板提示词
  12148. $template_prompt = '';
  12149. if ($template_id > 0) {
  12150. $template = DB::table('mp_prompt_templates')
  12151. ->where('id', $template_id)
  12152. ->where('is_deleted', 0)
  12153. ->first();
  12154. if (!$template) {
  12155. Utils::throwError('20003:提示词模板不存在或已删除');
  12156. }
  12157. $template_prompt = $template->template_prompt ?? '';
  12158. }
  12159. // 合并用户提示词和模板提示词(模板提示词与用户输入基本一致时只保留一个,避免重复提示词)
  12160. $final_prompt = '';
  12161. if (!empty($template_prompt)) {
  12162. $trimmedPrompt = trim((string)$prompt);
  12163. if ($trimmedPrompt !== '' && mb_strtolower($trimmedPrompt) === mb_strtolower(trim($template_prompt))) {
  12164. $final_prompt = $template_prompt;
  12165. } elseif (!empty($prompt)) {
  12166. $final_prompt = $template_prompt . "\n\n补充要求:" . $prompt;
  12167. } else {
  12168. $final_prompt = $template_prompt;
  12169. }
  12170. } else {
  12171. $final_prompt = $prompt;
  12172. }
  12173. // 获取需要重新生成的内容参考
  12174. $reference_content = '';
  12175. $target_episode_id = 0;
  12176. $target_anime_id = 0;
  12177. $target_episode_number = 0;
  12178. if ($isActIdMode) {
  12179. // 单个片段模式:获取该片段的内容
  12180. $segment = DB::table('mp_episode_segments')
  12181. ->where('id', $act_id)
  12182. ->first();
  12183. // 数据库不存在时,尝试从预览虚拟 act_id 保存的 redis 数据中恢复
  12184. if (!$segment) {
  12185. $previewData = Redis::get($this->buildActPreviewKey($act_id));
  12186. if ($previewData) {
  12187. $previewData = json_decode($previewData, true);
  12188. $segment = (object)[
  12189. 'anime_id' => getProp($previewData, 'anime_id'),
  12190. 'episode_id' => getProp($previewData, 'episode_id'),
  12191. 'episode_number' => getProp($previewData, 'episode_number'),
  12192. 'act_number' => getProp($previewData, 'act_number'),
  12193. 'act_duration' => getProp($previewData, 'act_duration'),
  12194. 'act_content' => getProp($previewData, 'act_content'),
  12195. ];
  12196. }
  12197. }
  12198. if (!$segment) {
  12199. Utils::throwError('20003:片段不存在');
  12200. }
  12201. $target_episode_id = $segment->episode_id;
  12202. $target_anime_id = $segment->anime_id;
  12203. $target_episode_number = $segment->episode_number;
  12204. $reference_content = $segment->act_content ?? '';
  12205. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12206. } else {
  12207. // 整个剧集模式:获取所有片段的内容
  12208. $segments = DB::table('mp_episode_segments')
  12209. ->where('episode_id', $episode_id)
  12210. ->orderBy('act_number')
  12211. ->get();
  12212. if ($segments->isEmpty()) {
  12213. Utils::throwError('20003:该剧集没有片段数据');
  12214. }
  12215. $target_episode_id = $episode_id;
  12216. $target_anime_id = $segments[0]->anime_id;
  12217. $target_episode_number = $segments[0]->episode_number;
  12218. // 拼接所有片段内容,保留格式用于AI理解
  12219. $act_contents = [];
  12220. foreach ($segments as $seg) {
  12221. $act_number = $seg->act_number;
  12222. $act_content = $seg->act_content ?? '';
  12223. if (!empty($act_content)) {
  12224. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  12225. }
  12226. }
  12227. $reference_content = implode("\n\n", $act_contents);
  12228. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  12229. if ($episode_content) {
  12230. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【原分段剧本内容】\n{$reference_content}";
  12231. //$reference_content = "\n\n【本集原始内容】\n{$episode_content}";
  12232. }else {
  12233. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12234. }
  12235. }
  12236. if (empty($reference_content)) {
  12237. Utils::throwError('20003:没有可参考的片段内容');
  12238. }
  12239. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  12240. $episode = DB::table('mp_anime_episodes')
  12241. ->where('id', $target_episode_id)
  12242. ->first();
  12243. if (!$episode) {
  12244. Utils::throwError('20003:剧集不存在');
  12245. }
  12246. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  12247. $anime_script_id = getProp($anime, 'script_id');
  12248. $intro = $episode->intro ?? '';
  12249. $art_style = $episode->art_style ?? '';
  12250. $roles = json_decode($episode->roles ?? '[]', true);
  12251. $scenes = json_decode($episode->scenes ?? '[]', true);
  12252. $props = json_decode($episode->props ?? '[]', true);
  12253. // 构建提示词中的主体列表和场景列表参考
  12254. $roles_ref = '';
  12255. if (!empty($roles) && is_array($roles)) {
  12256. $roles_list = [];
  12257. foreach ($roles as $role) {
  12258. $role_name = getProp($role, 'role', '');
  12259. $role_desc = getProp($role, 'description', '');
  12260. $pic_prompt = getProp($role, 'pic_prompt', '');
  12261. $voice_prompt = getProp($role, 'voice_prompt', '');
  12262. if (!empty($role_name)) {
  12263. $role_line = $role_name;
  12264. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  12265. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  12266. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  12267. $roles_list[] = $role_line;
  12268. }
  12269. }
  12270. if (!empty($roles_list)) {
  12271. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  12272. }
  12273. }
  12274. $scenes_ref = '';
  12275. if (!empty($scenes) && is_array($scenes)) {
  12276. $scenes_list = [];
  12277. foreach ($scenes as $scene) {
  12278. $scene_name = getProp($scene, 'scene', '');
  12279. $scene_desc = getProp($scene, 'description', '');
  12280. $pic_prompt = getProp($scene, 'pic_prompt', '');
  12281. if (!empty($scene_name)) {
  12282. $scene_line = $scene_name;
  12283. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  12284. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  12285. $scenes_list[] = $scene_line;
  12286. }
  12287. }
  12288. if (!empty($scenes_list)) {
  12289. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  12290. }
  12291. }
  12292. $props_ref = '';
  12293. if (!empty($props) && is_array($props)) {
  12294. $props_list = [];
  12295. foreach ($props as $prop) {
  12296. $prop_name = getProp($prop, 'prop', '');
  12297. $prop_desc = getProp($prop, 'description', '');
  12298. $pic_prompt = getProp($prop, 'pic_prompt', '');
  12299. if (!empty($prop_name)) {
  12300. $prop_line = $prop_name;
  12301. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  12302. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  12303. $props_list[] = $prop_line;
  12304. }
  12305. }
  12306. if (!empty($props_list)) {
  12307. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  12308. }
  12309. }
  12310. // 构建美术风格参考
  12311. $art_style_ref = '';
  12312. if (!empty($art_style)) {
  12313. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  12314. }
  12315. // 构建内容简介参考
  12316. $intro_ref = '';
  12317. if (!empty($intro)) {
  12318. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  12319. }
  12320. // 构建完整的AI提示词
  12321. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  12322. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  12323. $user_prompt .= $intro_ref;
  12324. $user_prompt .= $art_style_ref;
  12325. $user_prompt .= $reference_content;
  12326. $user_prompt .= "\n\n【生成要求】\n- 请以【原分段剧本内容】为蓝本,保留剧情脉络、角色、场景与分段结构,但必须围绕【用户要求】对相关片段进行实质性修改;若【用户要求】未指定具体修改点,也需对画面、运镜、台词等描述进行改写,禁止整段原样复制。\n";
  12327. // $user_prompt .= $roles_ref;
  12328. // $user_prompt .= $scenes_ref;
  12329. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  12330. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  12331. if ($isActIdMode) {
  12332. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12333. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12334. } else {
  12335. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12336. }
  12337. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  12338. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  12339. // 整集模式:强制生成与原来一致的片段数量
  12340. if ($episode_id > 0 && isset($segments)) {
  12341. $originSegmentCount = count($segments);
  12342. $user_prompt .= "- 本集原有{$originSegmentCount}个片段,必须严格生成{$originSegmentCount}个片段(##片段1 到 ##片段{$originSegmentCount}),不得多不得少。\n";
  12343. }
  12344. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  12345. if ($isActIdMode) {
  12346. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  12347. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12348. } else {
  12349. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  12350. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  12351. }
  12352. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  12353. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  12354. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  12355. $system_prompt .= "【强制要求】\n";
  12356. // $system_prompt .= "- 请严格参考【本集原始内容】或【原分段剧本内容】进行本次生成,注意新生成的分段剧本内容一定不要跟【原分段剧本内容】一致,要进行一定程度调整\n";
  12357. $system_prompt .= "- 【重要】必须参考【本集原始内容】与【原分段剧本内容】中的剧情脉络、角色、场景、道具和分段结构,但严禁原样复制或几乎照抄原文;必须围绕【用户要求】对相关内容进行实质性修改,若生成结果与【原分段剧本内容】完全一致或未体现用户要求,视为生成失败\n";
  12358. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:\n";
  12359. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)\n";
  12360. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  12361. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  12362. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  12363. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  12364. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  12365. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  12366. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  12367. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  12368. $segmentHeader = '';
  12369. if ($episode_id > 0) {
  12370. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  12371. }
  12372. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:\n" . $segmentHeader . "##片段1\n时长:12s\n分镜1\n出场角色:刀疤脸\n场景:边境小镇街道\n出场道具:酒杯-高脚杯\n画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。\n运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。\n配音台词:\n背景音效:\n\n分镜2\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。\n运镜:缓慢横移,掠过阴影中瑟缩的食客。\n配音台词:\n背景音效:\n\n分镜3\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。\n运镜:从中景推向令牌特写。\n配音台词:\n背景音效:\n\n分镜4\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。\n运镜:极速推向酒水溅起的瞬间。\n配音台词:\n背景音效:\n\n分镜5\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。\n运镜:固定机位,利用倾斜构图制造压迫感。\n配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?\n背景音效:";
  12373. // 获取模型配置
  12374. $model = getProp($data, 'model');
  12375. if (!$model) {
  12376. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  12377. }
  12378. // 验证模型是否在可用模型表中
  12379. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12380. $model = 'deepseek-v4-pro';
  12381. }
  12382. // 模型兼容性处理
  12383. $thinkingMode = 'disabled';
  12384. $reasoningEffort = 'high';
  12385. if ($model === 'deepseek-chat') {
  12386. $model = 'deepseek-v4-flash';
  12387. $thinkingMode = 'disabled';
  12388. } elseif ($model === 'deepseek-reasoner') {
  12389. $model = 'deepseek-v4-flash';
  12390. $thinkingMode = 'enabled';
  12391. }
  12392. // 构建消息
  12393. $messages = [
  12394. [
  12395. 'role' => 'system',
  12396. 'content' => $system_prompt
  12397. ],
  12398. [
  12399. 'role' => 'user',
  12400. 'content' => $user_prompt
  12401. ]
  12402. ];
  12403. // dd($messages);
  12404. // 构建请求参数
  12405. $post_data = [
  12406. 'model' => $model,
  12407. 'messages' => $messages,
  12408. 'temperature' => 1.4,
  12409. 'frequency_penalty' => 0.3,
  12410. 'presence_penalty' => 0,
  12411. 'response_format' => ['type' => 'text'],
  12412. 'thinking' => ['type' => $thinkingMode],
  12413. 'stream' => false // 非流式输出
  12414. ];
  12415. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12416. // 调用AI生成新的分段剧本
  12417. try {
  12418. $fullContent = '';
  12419. $usage = [];
  12420. // 根据模型类型选择调用方法
  12421. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  12422. if (is_array($chatResult)) {
  12423. $fullContent = $chatResult['fullContent'] ?? '';
  12424. $usage = $chatResult['usage'] ?? [];
  12425. }
  12426. $generated_content = $fullContent;
  12427. // 归一化"场景:"标签换行格式:场景:\n场景名\n => 场景:场景名\n,保证场景字段为一行
  12428. $generated_content = preg_replace('/场景[::]\s*\n\s*([^\n]+)/u', '场景:$1', $generated_content);
  12429. if (empty($generated_content)) {
  12430. Utils::throwError('20003:AI生成内容为空,请重试');
  12431. }
  12432. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  12433. 'act_id' => $act_id,
  12434. 'episode_id' => $episode_id,
  12435. 'content_length' => mb_strlen($generated_content),
  12436. 'content_head' => mb_substr($generated_content, 0, 500),
  12437. 'content_tail' => mb_substr($generated_content, -200),
  12438. ]);
  12439. // 解析生成的内容 - 按片段分割
  12440. $parsed_segments = [];
  12441. // 先在开头添加换行符,确保第1片段也能被正确分割
  12442. $normalizedText = "\n" . $generated_content;
  12443. $parts = preg_split('/\n\s*##/', $normalizedText);
  12444. foreach ($parts as $part) {
  12445. $part = trim($part);
  12446. if (empty($part)) continue;
  12447. // 匹配"片段X"格式
  12448. if (!preg_match('/^片段\d+/', $part)) {
  12449. continue;
  12450. }
  12451. // 分离标题和内容
  12452. $lines = explode("\n", $part, 2);
  12453. $actTitle = trim($lines[0]);
  12454. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  12455. // 解析标题,提取序号
  12456. $actNumber = 0;
  12457. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  12458. $actNumber = intval($segmentTitleMatch[1]);
  12459. } else {
  12460. $actNumber = count($parsed_segments) + 1;
  12461. }
  12462. // 提取时长(仅保留数字)
  12463. $actDuration = 0;
  12464. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  12465. $actDurationStr = trim($actDurationMatch[1]);
  12466. // 提取数字部分(支持整数和小数)
  12467. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  12468. $actDuration = (float)$numMatch[1];
  12469. }
  12470. }
  12471. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12472. if ($actDuration > 15) {
  12473. $actDuration = 15;
  12474. }
  12475. if ($actDuration < 4) {
  12476. $actDuration = 4;
  12477. }
  12478. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  12479. $cleaned_content = $this->cleanSegmentContent($actContent);
  12480. $parsed_segments[] = [
  12481. 'act_number' => $actNumber,
  12482. 'act_title' => $actTitle,
  12483. 'act_duration' => $actDuration,
  12484. 'act_content' => $cleaned_content,
  12485. ];
  12486. }
  12487. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  12488. if (empty($parsed_segments)) {
  12489. $fallbackContent = $this->cleanSegmentContent($generated_content);
  12490. if ($fallbackContent !== '') {
  12491. $fallbackDuration = 0;
  12492. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  12493. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  12494. $fallbackDuration = (float)$numMatch[1];
  12495. }
  12496. }
  12497. // 内容未带时长时,单片段模式沿用原片段的时长
  12498. if ($fallbackDuration <= 0 && $isActIdMode && !empty($segment->act_duration)) {
  12499. $fallbackDuration = (float)$segment->act_duration;
  12500. }
  12501. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12502. if ($fallbackDuration > 15) {
  12503. $fallbackDuration = 15;
  12504. }
  12505. if ($fallbackDuration < 4) {
  12506. $fallbackDuration = 4;
  12507. }
  12508. $parsed_segments[] = [
  12509. 'act_number' => 1,
  12510. 'act_title' => '片段1',
  12511. 'act_duration' => $fallbackDuration,
  12512. 'act_content' => $fallbackContent,
  12513. ];
  12514. }
  12515. }
  12516. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  12517. if ($isActIdMode && count($parsed_segments) > 1) {
  12518. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  12519. 'act_id' => $act_id,
  12520. 'original_count' => count($parsed_segments),
  12521. ]);
  12522. $parsed_segments = array_slice($parsed_segments, 0, 1);
  12523. }
  12524. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  12525. 'act_id' => $act_id,
  12526. 'episode_id' => $episode_id,
  12527. 'segment_count' => count($parsed_segments),
  12528. 'segments' => array_map(function ($seg) {
  12529. return [
  12530. 'act_number' => $seg['act_number'],
  12531. 'act_duration' => $seg['act_duration'],
  12532. 'content_length' => mb_strlen($seg['act_content']),
  12533. ];
  12534. }, $parsed_segments),
  12535. ]);
  12536. if (empty($parsed_segments)) {
  12537. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  12538. 'act_id' => $act_id,
  12539. 'episode_id' => $episode_id,
  12540. 'content_length' => mb_strlen($generated_content),
  12541. 'content_head' => mb_substr($generated_content, 0, 1000),
  12542. 'content_tail' => mb_substr($generated_content, -300),
  12543. ]);
  12544. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  12545. }
  12546. // 收集所有资产名称(角色、场景、道具)
  12547. $product_names = [];
  12548. // 收集角色名称
  12549. if (!empty($roles) && is_array($roles)) {
  12550. foreach ($roles as $role) {
  12551. $role_name = getProp($role, 'role', '');
  12552. if (!empty($role_name)) {
  12553. $product_names[] = $role_name;
  12554. }
  12555. }
  12556. }
  12557. // 收集场景名称
  12558. if (!empty($scenes) && is_array($scenes)) {
  12559. foreach ($scenes as $scene) {
  12560. $scene_name = getProp($scene, 'scene', '');
  12561. if (!empty($scene_name)) {
  12562. $product_names[] = $scene_name;
  12563. }
  12564. }
  12565. }
  12566. // 收集道具名称
  12567. if (!empty($props) && is_array($props)) {
  12568. foreach ($props as $prop) {
  12569. $prop_name = getProp($prop, 'prop', '');
  12570. if (!empty($prop_name)) {
  12571. $product_names[] = $prop_name;
  12572. }
  12573. }
  12574. }
  12575. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  12576. $product_names = array_unique($product_names);
  12577. usort($product_names, function($a, $b) {
  12578. return mb_strlen($b) - mb_strlen($a);
  12579. });
  12580. // 处理每个片段的 act_show_content
  12581. foreach ($parsed_segments as &$segment) {
  12582. $act_content = getProp($segment, 'act_content', '');
  12583. if (empty($act_content)) {
  12584. $segment['act_show_content'] = '';
  12585. continue;
  12586. }
  12587. $processed_content = $act_content;
  12588. // 统一替换所有资产名称为 {资产名} 格式
  12589. // 使用占位符避免嵌套替换问题
  12590. $placeholder_map = [];
  12591. $placeholder_index = 0;
  12592. foreach ($product_names as $product_name) {
  12593. // 转义特殊字符
  12594. $escaped_product = preg_quote($product_name, '/');
  12595. // 检查是否匹配且未被 {} 包裹
  12596. $processed_content = preg_replace_callback(
  12597. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  12598. function($matches) use (&$placeholder_map, &$placeholder_index) {
  12599. // 使用唯一占位符
  12600. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  12601. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  12602. $placeholder_index++;
  12603. return $placeholder;
  12604. },
  12605. $processed_content
  12606. );
  12607. }
  12608. // 将所有占位符替换回实际内容
  12609. foreach ($placeholder_map as $placeholder => $replacement) {
  12610. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  12611. }
  12612. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  12613. $shot_counter = 0;
  12614. $processed_content = preg_replace_callback(
  12615. // 兼容“【镜头 1】”“【分镜 1】”等分镜/镜头与数字间带空格的情况
  12616. '/【(?:镜头|分镜)\s*(\d+)】/u',
  12617. function($matches) use (&$shot_counter) {
  12618. $shot_counter++;
  12619. return '【镜头' . $shot_counter . '】';
  12620. },
  12621. $processed_content
  12622. );
  12623. $segment['act_show_content'] = $processed_content;
  12624. }
  12625. unset($segment); // 解除引用
  12626. // 保存到数据库
  12627. $now = date('Y-m-d H:i:s');
  12628. $saved_acts = []; // 用于记录保存后的片段信息
  12629. if ($isActIdMode) {
  12630. // 单个片段模式:更新单条记录
  12631. if (count($parsed_segments) > 0) {
  12632. $new_segment = $parsed_segments[0];
  12633. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  12634. if ($check_mode === 1) {
  12635. // 单片段预览生成即按 normal 档扣费
  12636. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12637. 'anime_id' => $target_anime_id,
  12638. 'episode_id' => $target_episode_id,
  12639. 'model' => $model,
  12640. 'source' => 'regenerateSegmentScript',
  12641. ], 'normal');
  12642. return [
  12643. 'check_mode' => 1,
  12644. 'act_id' => $act_id,
  12645. 'act_title' => getProp($new_segment, 'act_title', ''),
  12646. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12647. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  12648. ];
  12649. }
  12650. // 虚拟 act_id 仅用于预览/参考,不允许直接保存到数据库
  12651. if (!is_numeric($act_id)) {
  12652. Utils::throwError('20003:该片段不可直接保存');
  12653. }
  12654. $update_data = [
  12655. 'act_content' => getProp($new_segment, 'act_content', ''),
  12656. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  12657. 'act_title' => getProp($new_segment, 'act_title', ''),
  12658. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12659. 'updated_at' => $now,
  12660. ];
  12661. DB::table('mp_episode_segments')
  12662. ->where('id', $act_id)
  12663. ->update($update_data);
  12664. // 获取更新后的记录
  12665. $updated_act = DB::table('mp_episode_segments')
  12666. ->where('id', $act_id)
  12667. ->first();
  12668. if ($updated_act) {
  12669. $saved_acts[] = [
  12670. 'act_id' => $updated_act->id,
  12671. 'act_number' => $updated_act->act_number,
  12672. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  12673. 'act_content' => $updated_act->act_content,
  12674. 'act_show_content' => $updated_act->act_show_content,
  12675. 'video_url' => $updated_act->video_url ?? '',
  12676. 'video_duration' => $updated_act->video_duration ?? 0,
  12677. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  12678. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  12679. ];
  12680. }
  12681. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  12682. // 单片段模式成功扣费(normal 档)
  12683. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12684. 'anime_id' => $target_anime_id,
  12685. 'episode_id' => $target_episode_id,
  12686. 'model' => $model,
  12687. 'source' => 'regenerateSegmentScript',
  12688. ], 'normal');
  12689. }
  12690. } else {
  12691. // 预览确认模式(check_mode=1):不落库,返回展示参数供前端确认后调用 saveEpisodeActs 保存
  12692. if ($check_mode === 1) {
  12693. // 剧集模式预览生成即扣除积分并记录 token 明细(special 档)
  12694. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12695. 'anime_id' => $target_anime_id,
  12696. 'episode_id' => $target_episode_id,
  12697. 'model' => $model,
  12698. 'source' => 'regenerateSegmentScript',
  12699. ], 'special');
  12700. // 为每个片段生成虚拟 act_id 并写入 redis(1天有效),供后续按虚拟 act_id 恢复片段数据
  12701. $previewActs = [];
  12702. foreach ($parsed_segments as $seg) {
  12703. $virtualActId = 'preview_' . time() . '_' . uniqid();
  12704. Redis::setex($this->buildActPreviewKey($virtualActId), 86400, json_encode([
  12705. 'anime_id' => $target_anime_id,
  12706. 'episode_id' => $target_episode_id,
  12707. 'episode_number' => $target_episode_number,
  12708. 'act_number' => $seg['act_number'],
  12709. 'act_title' => $seg['act_title'],
  12710. 'act_duration' => $seg['act_duration'],
  12711. 'act_content' => $seg['act_content'],
  12712. 'act_show_content'=> $seg['act_show_content'],
  12713. ], JSON_UNESCAPED_UNICODE));
  12714. $previewActs[] = [
  12715. 'act_id' => $virtualActId,
  12716. 'act_number' => $seg['act_number'],
  12717. 'act_title' => $seg['act_title'],
  12718. 'act_duration' => $seg['act_duration'],
  12719. 'act_content' => $seg['act_content'],
  12720. 'act_show_content' => $seg['act_show_content'],
  12721. 'video_url' => '',
  12722. 'video_duration' => 0,
  12723. 'video_time_point_start' => 0,
  12724. 'video_time_point_end' => 0,
  12725. 'last_frame_url' => '',
  12726. 'current_type' => 0,
  12727. ];
  12728. }
  12729. return [
  12730. 'check_mode' => 1,
  12731. 'anime_id' => $target_anime_id,
  12732. 'episode_id' => $target_episode_id,
  12733. 'title' => getProp($episode, 'title', ''),
  12734. 'episode_number' => $target_episode_number,
  12735. 'is_generated' => getProp($episode, 'is_generated', 0),
  12736. 'acts' => $previewActs,
  12737. ];
  12738. }
  12739. // 整个剧集模式:删除原有记录并批量保存新记录
  12740. DB::beginTransaction();
  12741. try {
  12742. // 删除原有的所有片段记录
  12743. DB::table('mp_episode_segments')
  12744. ->where('episode_id', $target_episode_id)
  12745. ->delete();
  12746. // 批量插入新的片段记录
  12747. $segments_to_insert = [];
  12748. foreach ($parsed_segments as $index => $segment) {
  12749. $act_number = $index + 1;
  12750. $segments_to_insert[] = [
  12751. 'anime_id' => $target_anime_id,
  12752. 'episode_id' => $target_episode_id,
  12753. 'episode_number' => $target_episode_number,
  12754. 'act_number' => $act_number,
  12755. 'act_title' => getProp($segment, 'act_title', ''),
  12756. 'act_duration' => getProp($segment, 'act_duration', 0),
  12757. 'act_content' => getProp($segment, 'act_content', ''),
  12758. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  12759. 'created_at' => $now,
  12760. 'updated_at' => $now,
  12761. ];
  12762. }
  12763. if (!empty($segments_to_insert)) {
  12764. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12765. }
  12766. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(special 档,与保存同事务)
  12767. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12768. 'anime_id' => $target_anime_id,
  12769. 'episode_id' => $target_episode_id,
  12770. 'model' => $model,
  12771. 'source' => 'regenerateSegmentScript',
  12772. ], 'special');
  12773. DB::commit();
  12774. // 查询保存后的所有片段记录
  12775. $saved_segments = DB::table('mp_episode_segments')
  12776. ->where('episode_id', $target_episode_id)
  12777. ->orderBy('act_number')
  12778. ->get();
  12779. foreach ($saved_segments as $saved_segment) {
  12780. $saved_acts[] = [
  12781. 'act_id' => $saved_segment->id,
  12782. 'act_number' => $saved_segment->act_number,
  12783. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  12784. 'act_content' => $saved_segment->act_content,
  12785. 'act_show_content' => $saved_segment->act_show_content,
  12786. 'video_url' => $saved_segment->video_url ?? '',
  12787. 'video_duration' => $saved_segment->video_duration ?? 0,
  12788. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  12789. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  12790. ];
  12791. }
  12792. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  12793. 'episode_id' => $target_episode_id,
  12794. 'segments_count' => count($segments_to_insert)
  12795. ]);
  12796. } catch (\Exception $e) {
  12797. DB::rollBack();
  12798. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  12799. Utils::throwError('20003:保存失败,请重试');
  12800. }
  12801. }
  12802. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  12803. return [
  12804. 'anime_id' => $target_anime_id,
  12805. 'episode_id' => $target_episode_id,
  12806. 'title' => getProp($episode, 'title', ''),
  12807. 'episode_number' => $target_episode_number,
  12808. 'is_generated' => getProp($episode, 'is_generated', 0),
  12809. 'acts' => $saved_acts,
  12810. ];
  12811. } catch (\Exception $e) {
  12812. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  12813. throw $e;
  12814. }
  12815. }
  12816. /**
  12817. * 保存剧集片段(预览确认模式使用):删除旧数据并批量保存新数据到 mp_episode_segments
  12818. *
  12819. * 逻辑与 regenerateSegmentScript 的 episode_id + check_mode=0 保存保持一致。
  12820. *
  12821. * @param array $data 请求参数:episode_id 必填,acts 必填(预览返回的片段数组)
  12822. * @return array
  12823. */
  12824. public function saveEpisodeActs($data) {
  12825. $uid = Site::getUid();
  12826. $episode_id = (int)getProp($data, 'episode_id', 0);
  12827. $acts = getProp($data, 'acts', []);
  12828. if (!$episode_id) {
  12829. Utils::throwError('20003:请提供剧集ID');
  12830. }
  12831. if (!is_array($acts) || empty($acts)) {
  12832. Utils::throwError('20003:请提供片段数据');
  12833. }
  12834. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  12835. if (!$episode) {
  12836. Utils::throwError('20003:剧集不存在');
  12837. }
  12838. // 用户校验:只能调整自己的剧集
  12839. $anime = DB::table('mp_animes')->where('id', $episode->anime_id)->first();
  12840. if (!$anime || (int)$anime->user_id !== (int)$uid) {
  12841. Utils::throwError('20003:没有权限操作该剧集');
  12842. }
  12843. $anime_id = (int)$episode->anime_id;
  12844. $episode_number = (int)$episode->episode_number;
  12845. $now = date('Y-m-d H:i:s');
  12846. try {
  12847. DB::beginTransaction();
  12848. // 删除原有的所有片段记录
  12849. DB::table('mp_episode_segments')
  12850. ->where('episode_id', $episode_id)
  12851. ->delete();
  12852. // 批量插入新的片段记录
  12853. $segments_to_insert = [];
  12854. $index = 0;
  12855. foreach ($acts as $act) {
  12856. if (!is_array($act)) {
  12857. continue;
  12858. }
  12859. $index++;
  12860. $segments_to_insert[] = [
  12861. 'anime_id' => $anime_id,
  12862. 'episode_id' => $episode_id,
  12863. 'episode_number' => $episode_number,
  12864. 'act_number' => (int)getProp($act, 'act_number', $index),
  12865. 'act_title' => (string)getProp($act, 'act_title', ''),
  12866. 'act_duration' => (float)getProp($act, 'act_duration', 0),
  12867. 'act_content' => (string)getProp($act, 'act_content', ''),
  12868. // 'act_show_content' => (string)getProp($act, 'act_show_content', ''),
  12869. 'created_at' => $now,
  12870. 'updated_at' => $now,
  12871. ];
  12872. }
  12873. if (empty($segments_to_insert)) {
  12874. DB::rollBack();
  12875. Utils::throwError('20003:没有有效的片段数据');
  12876. }
  12877. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12878. DB::commit();
  12879. } catch (\Exception $e) {
  12880. DB::rollBack();
  12881. dLog('deepseek')->error('保存剧集片段失败: ' . $e->getMessage(), [
  12882. 'episode_id' => $episode_id,
  12883. ]);
  12884. Utils::throwError('20003:保存失败,请重试');
  12885. }
  12886. // 查询保存后的所有片段记录(数组化,与 episodeInfoForAce 处理一致)
  12887. $saved_segments = DB::table('mp_episode_segments')
  12888. ->where('episode_id', $episode_id)
  12889. ->orderBy('act_number')
  12890. ->get()
  12891. ->map(function ($value) {
  12892. return (array)$value;
  12893. })
  12894. ->toArray();
  12895. // 构造与 episodeInfoForAce 一致的 acts 与 total_duration
  12896. $acts = [];
  12897. $totalDuration = 0;
  12898. foreach ($saved_segments as $segment) {
  12899. $videoDuration = getProp($segment, 'video_duration');
  12900. $actDuration = getProp($segment, 'act_duration');
  12901. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  12902. $totalDuration += floatval($videoDuration);
  12903. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  12904. $totalDuration += floatval($actDuration);
  12905. } else {
  12906. $totalDuration += 5;
  12907. }
  12908. $acts[] = [
  12909. 'act_id' => getProp($segment, 'id'),
  12910. 'act_number' => getProp($segment, 'act_number'),
  12911. 'act_title' => getProp($segment, 'act_title'),
  12912. 'act_duration' => getProp($segment, 'act_duration'),
  12913. 'act_content' => getProp($segment, 'act_content'),
  12914. 'video_url' => getProp($segment, 'video_url'),
  12915. 'video_duration' => getProp($segment, 'video_duration', 0),
  12916. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  12917. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  12918. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  12919. 'current_type' => getProp($segment, 'current_type'),
  12920. ];
  12921. }
  12922. // 顶层与 episodeInfoForAce 一致
  12923. $result = [
  12924. 'episode_id' => $episode_id,
  12925. 'anime_id' => $anime_id,
  12926. 'episode_number' => $episode_number,
  12927. 'title' => getProp($episode, 'title'),
  12928. 'intro' => getProp($episode, 'intro'),
  12929. 'art_style' => getProp($episode, 'art_style'),
  12930. 'roles' => json_decode(getProp($episode, 'roles', '[]'), true),
  12931. 'scenes' => json_decode(getProp($episode, 'scenes', '[]'), true),
  12932. 'props' => getProp($episode, 'props') ? json_decode(getProp($episode, 'props'), true) : [],
  12933. 'is_generated' => getProp($episode, 'is_generated'),
  12934. 'acts' => array_values($acts),
  12935. 'total_duration' => intval(round($totalDuration)),
  12936. ];
  12937. // video_params(从 mp_animes 取,与 episodeInfoForAce 一致)
  12938. $animeRow = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  12939. $result['video_params'] = [
  12940. 'video_model' => getProp($animeRow, 'video_model'),
  12941. 'video_resolution' => getProp($animeRow, 'video_resolution'),
  12942. 'ratio' => getProp($animeRow, 'video_ratio'),
  12943. ];
  12944. return $result;
  12945. }
  12946. /**
  12947. * 预览虚拟 act_id 在 redis 中的键
  12948. *
  12949. * @param mixed $actId
  12950. * @return string
  12951. */
  12952. private function buildActPreviewKey($actId): string
  12953. {
  12954. return 'anime_act_preview:' . $actId;
  12955. }
  12956. /**
  12957. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  12958. *
  12959. * @param string $actContent
  12960. * @return string
  12961. */
  12962. private function cleanSegmentContent(string $actContent): string
  12963. {
  12964. $cleaned_content = '';
  12965. $content_lines = explode("\n", $actContent);
  12966. $is_capturing = false; // 标记是否开始捕获分镜内容
  12967. $count = 0;
  12968. foreach ($content_lines as $line) {
  12969. $trimmed_line = trim($line);
  12970. // 跳过时长、旁白音色等非分镜行
  12971. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  12972. continue;
  12973. }
  12974. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X,以及分镜/镜头与数字间带空格的情况)
  12975. if (preg_match('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  12976. $count++;
  12977. $is_capturing = true;
  12978. // 统一归一化为【分镜N】/【镜头N】(兼容“镜头 1”“【镜头 1】”等写法)
  12979. $trimmed_line = preg_replace('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', '【$1$2】', $trimmed_line);
  12980. if ($count > 1) {
  12981. $trimmed_line = "\n" . $trimmed_line;
  12982. }
  12983. }
  12984. if ($is_capturing && !empty($trimmed_line)) {
  12985. $cleaned_content .= $trimmed_line . "\n";
  12986. }
  12987. }
  12988. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  12989. return $cleaned_content;
  12990. }
  12991. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  12992. {
  12993. $episode_arr = [
  12994. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  12995. 'intro' => getProp($script_arr, 'intro'),
  12996. 'art_style' => getProp($script_arr, 'art_style'),
  12997. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  12998. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  12999. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  13000. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  13001. ];
  13002. if (empty($episode_arr['acts'])) {
  13003. $fallback_episode_arr = handleEpisodeContent($fullContent);
  13004. if (!empty($fallback_episode_arr['acts'])) {
  13005. $episode_arr = array_merge($fallback_episode_arr, [
  13006. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  13007. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  13008. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  13009. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  13010. ]);
  13011. }
  13012. }
  13013. // if (!getProp($episode_arr, 'episode_title')) {
  13014. // $episode_title = '';
  13015. // $episodes = getProp($script_arr, 'episodes', []);
  13016. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  13017. // $episode_title = '第1集:' . $episodes[0]['title'];
  13018. // }
  13019. // if (!$episode_title) {
  13020. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  13021. // }
  13022. // $episode_arr['episode_title'] = $episode_title;
  13023. // }
  13024. return $episode_arr;
  13025. }
  13026. private function saveEpisodeVersionData(
  13027. int $anime_id,
  13028. int $episode_number,
  13029. array $episode_arr,
  13030. array $existing_roles,
  13031. array $existing_scenes,
  13032. array $existing_props,
  13033. $current_episode,
  13034. $base_episode,
  13035. bool $is_regenerate_version,
  13036. string $content,
  13037. string $now,
  13038. array $ref_products = []
  13039. ): array {
  13040. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  13041. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  13042. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  13043. // 过滤掉关键字段为空的条目
  13044. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  13045. return !empty($item['role'] ?? null);
  13046. }));
  13047. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  13048. return !empty($item['scene'] ?? null);
  13049. }));
  13050. $merged_props = array_values(array_filter($generated_props, function ($item) {
  13051. return !empty($item['prop'] ?? null);
  13052. }));
  13053. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  13054. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  13055. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  13056. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  13057. $ace_mode = getProp($anime, 'ace_mode');
  13058. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  13059. $global_roles = json_decode(getProp($anime, 'roles'), true);
  13060. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  13061. $global_roles = is_array($global_roles) ? $global_roles : [];
  13062. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  13063. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  13064. $art_style_type = getProp($anime, 'art_style_type');
  13065. // 检查并创建 roles 的图片生成任务
  13066. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  13067. // 检查并创建 scenes 的图片生成任务
  13068. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  13069. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  13070. if ($arr && is_array($arr)) {
  13071. $merged_roles = $arr['roles'];
  13072. $merged_scenes = $arr['scenes'];
  13073. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  13074. }
  13075. // 确保数据是数组类型
  13076. if (!is_array($merged_roles)) {
  13077. dLog('deepseek')->error('merged_roles不是数组类型', [
  13078. 'type' => gettype($merged_roles),
  13079. 'value' => $merged_roles
  13080. ]);
  13081. $merged_roles = [];
  13082. }
  13083. if (!is_array($merged_scenes)) {
  13084. dLog('deepseek')->error('merged_scenes不是数组类型', [
  13085. 'type' => gettype($merged_scenes),
  13086. 'value' => $merged_scenes
  13087. ]);
  13088. $merged_scenes = [];
  13089. }
  13090. if (!is_array($merged_props)) {
  13091. dLog('deepseek')->error('merged_props不是数组类型', [
  13092. 'type' => gettype($merged_props),
  13093. 'value' => $merged_props
  13094. ]);
  13095. $merged_props = [];
  13096. }
  13097. // 同步新出现的主体和场景到全局
  13098. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  13099. $role_arr = [];
  13100. foreach ($merged_roles as $item) {
  13101. $role_arr[$item['role']] = $item;
  13102. }
  13103. $version_count = DB::table('mp_anime_episodes')
  13104. ->where('anime_id', $anime_id)
  13105. ->where('episode_number', $episode_number)
  13106. ->count('id');
  13107. $episode = [
  13108. 'anime_id' => $anime_id,
  13109. 'episode_number' => $episode_number,
  13110. 'title' => getProp($episode_arr, 'episode_title'),
  13111. 'content' => $content,
  13112. 'intro' => getProp($episode_arr, 'intro'),
  13113. 'art_style' => getProp($episode_arr, 'art_style'),
  13114. 'roles' => json_encode($merged_roles, 256),
  13115. 'scenes' => json_encode($merged_scenes, 256),
  13116. 'props' => json_encode($merged_props, 256),
  13117. 'generate_status' => '待执行',
  13118. 'generate_at' => $now,
  13119. 'is_default' => 1,
  13120. 'updated_at' => $now,
  13121. ];
  13122. $del_flag = false;
  13123. if ($is_regenerate_version) {
  13124. DB::table('mp_anime_episodes')
  13125. ->where('anime_id', $anime_id)
  13126. ->where('episode_number', $episode_number)
  13127. ->update(['is_default' => 0, 'updated_at' => $now]);
  13128. $episode['sequence'] = $version_count + 1;
  13129. $episode['created_at'] = $now;
  13130. $episode['cpid'] = Site::getCpid();
  13131. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13132. if (!$episode_id) {
  13133. Utils::throwError('20003:创建剧集版本失败');
  13134. }
  13135. } else {
  13136. $target_episode = $current_episode ?: $base_episode;
  13137. if ($target_episode) {
  13138. $episode_id = getProp($target_episode, 'id');
  13139. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  13140. DB::table('mp_anime_episodes')
  13141. ->where('anime_id', $anime_id)
  13142. ->where('episode_number', $episode_number)
  13143. ->where('id', '<>', $episode_id)
  13144. ->update(['is_default' => 0, 'updated_at' => $now]);
  13145. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  13146. if ($boolen === false) {
  13147. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  13148. Utils::throwError('20003:分集内容保存失败');
  13149. }
  13150. $del_flag = true;
  13151. } else {
  13152. DB::table('mp_anime_episodes')
  13153. ->where('anime_id', $anime_id)
  13154. ->where('episode_number', $episode_number)
  13155. ->update(['is_default' => 0, 'updated_at' => $now]);
  13156. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  13157. $episode['created_at'] = $now;
  13158. $episode['cpid'] = Site::getCpid();
  13159. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13160. if (!$episode_id) {
  13161. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  13162. Utils::throwError('20003:分集内容保存失败');
  13163. }
  13164. }
  13165. }
  13166. $segments = [];
  13167. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  13168. // 如果是第2集及以后,获取上一集的主体音色数据
  13169. $previous_roles_voice = [];
  13170. if ($episode_number >= 2) {
  13171. $previous_episode = DB::table('mp_anime_episodes')
  13172. ->where('anime_id', $anime_id)
  13173. ->where('episode_number', $episode_number - 1)
  13174. ->where('is_default', 1)
  13175. ->first();
  13176. if ($previous_episode) {
  13177. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  13178. if (is_array($previous_roles)) {
  13179. foreach ($previous_roles as $prev_role) {
  13180. $role_name = getProp($prev_role, 'role');
  13181. if ($role_name) {
  13182. $previous_roles_voice[$role_name] = [
  13183. 'voice_name' => getProp($prev_role, 'voice_name'),
  13184. 'voice_type' => getProp($prev_role, 'voice_type'),
  13185. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  13186. ];
  13187. $voice_prompt = getProp($prev_role, 'voice_prompt');
  13188. if ($voice_prompt) {
  13189. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  13190. }
  13191. }
  13192. }
  13193. }
  13194. }
  13195. }
  13196. // 将继承的音色数据同步到当前集的主体列表
  13197. if (!empty($previous_roles_voice)) {
  13198. foreach ($merged_roles as &$role) {
  13199. $role_name = getProp($role, 'role');
  13200. if ($role_name && isset($previous_roles_voice[$role_name])) {
  13201. // 强制继承上一集的音色数据
  13202. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  13203. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  13204. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  13205. // 如果上一集有 voice_prompt 则继承,否则跳过
  13206. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  13207. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  13208. }
  13209. }
  13210. }
  13211. unset($role); // 解除引用
  13212. // 更新 role_arr 以便后续使用
  13213. $role_arr = [];
  13214. foreach ($merged_roles as $item) {
  13215. $role_arr[$item['role']] = $item;
  13216. }
  13217. }
  13218. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  13219. $emotion_list = array_flip($emotion_list);
  13220. foreach ($acts as $act) {
  13221. $act_segments = getProp($act, 'segments', []);
  13222. if (!is_array($act_segments)) {
  13223. continue;
  13224. }
  13225. if ((int)$ace_mode === 1) {
  13226. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  13227. $merged_parts = [];
  13228. foreach ($act_segments as $seg) {
  13229. $seg_num = getProp($seg, 'segment_number');
  13230. $seg_content = getProp($seg, 'segment_content');
  13231. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  13232. }
  13233. $act_content = implode("\n", $merged_parts);
  13234. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13235. $segments[] = [
  13236. 'anime_id' => $anime_id,
  13237. 'episode_id' => $episode_id,
  13238. 'episode_number' => $episode_number,
  13239. 'act_number' => getProp($act, 'act_number'),
  13240. 'act_title' => getProp($act, 'act_title'),
  13241. 'act_duration' => getProp($act, 'act_duration'),
  13242. 'act_content' => $act_content,
  13243. 'created_at' => $now,
  13244. 'updated_at' => $now
  13245. ];
  13246. } else {
  13247. foreach ($act_segments as $segment) {
  13248. $voice_actor = getProp($segment, 'voice_actor');
  13249. // 优先从上一集继承音色数据
  13250. $timbre_info = [];
  13251. if (isset($previous_roles_voice[$voice_actor])) {
  13252. // 从上一集继承音色数据
  13253. $timbre_info = $previous_roles_voice[$voice_actor];
  13254. } elseif (isset($role_arr[$voice_actor])) {
  13255. // 使用当前集的主体音色数据
  13256. $timbre_info = $role_arr[$voice_actor];
  13257. }
  13258. $voice_type = getProp($timbre_info, 'voice_type');
  13259. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  13260. if ($timbre_emotion) {
  13261. $timbre_emotion = explode(',', $timbre_emotion);
  13262. } else {
  13263. $timbre_emotion = [];
  13264. }
  13265. $emotion = getProp($segment, 'emotion', '中性');
  13266. if (!in_array($emotion, $timbre_emotion)) {
  13267. $emotion = '中性';
  13268. }
  13269. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  13270. $segments[] = [
  13271. 'anime_id' => $anime_id,
  13272. 'episode_id' => $episode_id,
  13273. 'episode_number' => $episode_number,
  13274. 'act_number' => getProp($act, 'act_number'),
  13275. 'act_title' => getProp($act, 'act_title'),
  13276. 'act_duration' => getProp($act, 'act_duration'),
  13277. 'segment_id' => getProp($segment, 'segment_id'),
  13278. 'segment_number' => getProp($segment, 'segment_number'),
  13279. 'segment_content' => getProp($segment, 'segment_content'),
  13280. 'description' => getProp($segment, 'description'),
  13281. 'composition' => getProp($segment, 'composition'),
  13282. 'camera_movement' => getProp($segment, 'camera_movement'),
  13283. 'voice_actor' => $voice_actor,
  13284. 'dialogue' => getProp($segment, 'dialogue'),
  13285. 'frame_type' => getProp($segment, 'frame_type'),
  13286. 'scene' => getProp($segment, 'scene'),
  13287. 'characters' => getProp($segment, 'characters'),
  13288. 'tail_frame' => getProp($segment, 'tail_frame'),
  13289. 'voice_name' => getProp($timbre_info, 'voice_name'),
  13290. 'voice_type' => $voice_type,
  13291. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  13292. 'emotion' => $emotion,
  13293. 'emotion_type' => $emotion_type,
  13294. 'gender' => getProp($segment, 'gender', '0'),
  13295. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  13296. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  13297. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  13298. 'pitch' => getProp($segment, 'pitch', 0),
  13299. 'created_at' => $now,
  13300. 'updated_at' => $now
  13301. ];
  13302. }
  13303. }
  13304. }
  13305. if ($segments) {
  13306. if ($del_flag) {
  13307. DB::table('mp_episode_segments')
  13308. ->where('anime_id', $anime_id)
  13309. ->where('episode_id', $episode_id)
  13310. ->delete();
  13311. }
  13312. $boolen = DB::table('mp_episode_segments')->insert($segments);
  13313. if (!$boolen) {
  13314. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  13315. Utils::throwError('20003:分镜内容保存失败');
  13316. }
  13317. }
  13318. dLog('deepseek')->info('segments', $segments);
  13319. // ace_mode=1: acts 返回值按合并格式调整
  13320. if ((int)$ace_mode === 1) {
  13321. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  13322. $act_map = [];
  13323. foreach ($table_act_data as $item) {
  13324. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  13325. }
  13326. $restructured_acts = [];
  13327. foreach ($acts as $act) {
  13328. $act_segments = getProp($act, 'segments', []);
  13329. if (!is_array($act_segments)) {
  13330. continue;
  13331. }
  13332. $merged_parts = [];
  13333. foreach ($act_segments as $seg) {
  13334. $seg_num = getProp($seg, 'segment_number');
  13335. $seg_content = getProp($seg, 'segment_content');
  13336. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  13337. }
  13338. $act_content = implode("\n", $merged_parts);
  13339. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13340. $restructured_acts[] = [
  13341. 'anime_id' => $anime_id,
  13342. 'episode_id' => $episode_id,
  13343. 'episode_number' => $episode_number,
  13344. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  13345. 'act_number' => getProp($act, 'act_number'),
  13346. 'act_title' => getProp($act, 'act_title'),
  13347. 'act_duration' => getProp($act, 'act_duration'),
  13348. 'act_content' => $act_content,
  13349. 'created_at' => $now,
  13350. 'updated_at' => $now,
  13351. ];
  13352. }
  13353. $acts = $restructured_acts;
  13354. }
  13355. $episode['episode_id'] = $episode_id;
  13356. $episode['roles'] = $merged_roles;
  13357. $episode['scenes'] = $merged_scenes;
  13358. $episode['props'] = $merged_props;
  13359. $episode['acts'] = $acts;
  13360. return [
  13361. 'episode' => $episode,
  13362. 'episode_id' => $episode_id,
  13363. 'merged_roles' => $merged_roles,
  13364. 'merged_scenes' => $merged_scenes,
  13365. 'merged_props' => $merged_props,
  13366. ];
  13367. }
  13368. private function buildEpisodeItemContent(array $items, string $nameKey): string
  13369. {
  13370. $content = '';
  13371. foreach ($items as $item) {
  13372. $name = trim((string)getProp($item, $nameKey));
  13373. if ($name === '' || $name === '旁白') {
  13374. continue;
  13375. }
  13376. $description = trim((string)getProp($item, 'description'));
  13377. $content .= $name . ': ' . $description;
  13378. if ($nameKey == 'role') {
  13379. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13380. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13381. $voice_name = trim(getProp($item, 'voice_name'));
  13382. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13383. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  13384. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13385. }else {
  13386. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13387. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13388. }
  13389. $content .= "\n";
  13390. }
  13391. return trim($content);
  13392. }
  13393. private function getEpisodeChatContent($animeId, $sequence, $content) {
  13394. if ((int)$sequence <= 0) {
  13395. return [];
  13396. }
  13397. $origin_content = '';
  13398. if ($content) {
  13399. $origin_content = '本集剧情内容:'.$content;
  13400. }else {
  13401. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  13402. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  13403. }
  13404. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  13405. // 获取分集信息
  13406. $episode = DB::table('mp_anime_episodes')
  13407. ->where('anime_id', $animeId)
  13408. ->where('episode_number', $sequence)
  13409. ->where('is_default', 1)
  13410. ->first();
  13411. if (!$episode) {
  13412. return [];
  13413. }
  13414. $episode_id = getProp($episode, 'id');
  13415. $episode_number = getProp($episode, 'episode_number');
  13416. $title = getProp($episode, 'title');
  13417. $intro = getProp($episode, 'intro');
  13418. $art_style = getProp($episode, 'art_style');
  13419. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13420. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13421. // 组装纯文本内容
  13422. $content = '';
  13423. // 添加分集标题和梗概
  13424. $content .= "###第{$episode_number}集:{$title}\n\n";
  13425. $content .= "###故事梗概\n";
  13426. $content .= trim($intro) . "\n\n";
  13427. // 添加美术风格
  13428. $content .= "###美术风格\n";
  13429. $content .= trim($art_style) . "\n\n";
  13430. // 添加主体列表
  13431. $content .= "###主体列表\n";
  13432. $pangbai_voice_prompt = "";
  13433. foreach ($roles as $role) {
  13434. $name = getProp($role, 'role');
  13435. $description = getProp($role, 'description');
  13436. $pic_prompt = getProp($role, 'pic_prompt');
  13437. $voice_prompt = getProp($role, 'voice_prompt');
  13438. $voice_name = getProp($role, 'voice_name');
  13439. $content .= "{$name}: {$description}";
  13440. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13441. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13442. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13443. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  13444. $content .= "\n";
  13445. }
  13446. $content .= "\n";
  13447. // 添加场景列表
  13448. $content .= "###场景列表\n";
  13449. foreach ($scenes as $scene) {
  13450. $name = getProp($scene, 'scene');
  13451. $description = getProp($scene, 'description');
  13452. $pic_prompt = getProp($scene, 'pic_prompt');
  13453. $content .= "{$name}: {$description}";
  13454. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13455. $content .= "\n";
  13456. }
  13457. $content .= "\n";
  13458. // 获取分镜信息
  13459. $segments = DB::table('mp_episode_segments')
  13460. ->where('anime_id', $animeId)
  13461. ->where('episode_id', $episode_id)
  13462. ->orderBy('segment_number')
  13463. ->get();
  13464. if ($segments && count($segments) > 0) {
  13465. if ((int)$ace_mode === 1) {
  13466. $content .= "###分段剧本\n";
  13467. // 获取片段数量
  13468. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  13469. $content .= "片段数量:{$act_count}\n";
  13470. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  13471. $content .= "\n";
  13472. }else {
  13473. $content .= "###分镜剧本\n";
  13474. }
  13475. // 按幕分组
  13476. $currentAct = null;
  13477. foreach ($segments as $segment) {
  13478. $act_number = getProp($segment, 'act_number');
  13479. $act_title = getProp($segment, 'act_title');
  13480. $act_duration = getProp($segment, 'act_duration');
  13481. $segment_number = getProp($segment, 'segment_number');
  13482. $segment_content = getProp($segment, 'segment_content');
  13483. $scene_description = getProp($segment, 'scene_description');
  13484. $scene_name = getProp($segment, 'scene_name');
  13485. $composition = getProp($segment, 'composition');
  13486. $camera_movement = getProp($segment, 'camera_movement');
  13487. $voice_type = getProp($segment, 'voice_type');
  13488. $characters = getProp($segment, 'characters');
  13489. $dialogue = getProp($segment, 'dialogue');
  13490. $frame_type = getProp($segment, 'frame_type');
  13491. $tail_frame_description = getProp($segment, 'tail_frame_description');
  13492. // 判断是否是全能模式
  13493. if ((int)$ace_mode === 1) { // 全能模式
  13494. // 如果是新的分段,添加分段标题
  13495. if ($act_number !== $currentAct) {
  13496. $currentAct = $act_number;
  13497. $content .= "##{$act_title}\n";
  13498. $content .= "时长:{$act_duration}s\n";
  13499. }
  13500. }else {
  13501. // 如果是新的幕,添加幕标题
  13502. if ($act_number !== $currentAct) {
  13503. $currentAct = $act_number;
  13504. $content .= "##第{$act_number}幕:{$scene_name}\n";
  13505. }
  13506. }
  13507. // 添加分镜信息
  13508. $content .= "分镜{$segment_number}\n";
  13509. $content .= "分镜内容:\n{$segment_content}\n";
  13510. // $content .= "画面描述:{$scene_description}\n";
  13511. // $content .= "场景:{$scene_name}\n";
  13512. // $content .= "构图设计:{$composition}\n";
  13513. // $content .= "运镜调度:{$camera_movement}\n";
  13514. // if (!empty($voice_type)) {
  13515. // $content .= "配音角色:{$voice_type}\n";
  13516. // }
  13517. // if (!empty($characters)) {
  13518. // $content .= "出镜角色:{$characters}\n";
  13519. // }
  13520. // if (!empty($dialogue)) {
  13521. // $content .= "台词内容:\"{$dialogue}\"\n";
  13522. // }
  13523. // $content .= "画面类型:{$frame_type}\n";
  13524. // $content .= "尾帧描述:{$tail_frame_description}\n";
  13525. $content .= "\n";
  13526. }
  13527. }
  13528. $content = trim($content);
  13529. if($content) $content = "上集剧本内容:\n{$content}";
  13530. return [
  13531. [
  13532. 'role' => 'user',
  13533. 'content' => $origin_content
  13534. ],
  13535. [
  13536. 'role' => 'assistant',
  13537. 'content' => $content
  13538. ]
  13539. ];
  13540. }
  13541. private function getEpisodeChatMessages($animeId, $sequence): array
  13542. {
  13543. if ((int)$sequence <= 0) {
  13544. return [];
  13545. }
  13546. return DB::table('mp_anime_records')
  13547. ->where('anime_id', $animeId)
  13548. ->where('sequence', $sequence)
  13549. ->where('episode_id', '>', 0)
  13550. ->select('role', 'content')
  13551. ->orderBy('created_at')
  13552. ->orderBy('id')
  13553. ->get()
  13554. ->map(function ($value) {
  13555. return (array)$value;
  13556. })
  13557. ->toArray();
  13558. }
  13559. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  13560. {
  13561. $existingMap = [];
  13562. foreach ($existingItems as $item) {
  13563. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13564. if ($itemKey === '') {
  13565. continue;
  13566. }
  13567. $existingMap[$itemKey] = $item;
  13568. }
  13569. if (!$generatedItems) {
  13570. return array_values($existingItems);
  13571. }
  13572. $merged = [];
  13573. foreach ($generatedItems as $item) {
  13574. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13575. if ($itemKey === '') {
  13576. continue;
  13577. }
  13578. if (isset($existingMap[$itemKey])) {
  13579. if (trim((string)getProp($item, 'description')) === '') {
  13580. $merged[] = $existingMap[$itemKey];
  13581. continue;
  13582. }
  13583. // 检查内容是否发生变化
  13584. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  13585. if (!$isChanged) {
  13586. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  13587. $mergedItem = [
  13588. $nameKey => trim((string)getProp($item, $nameKey)),
  13589. 'description' => trim((string)getProp($item, 'description')),
  13590. ];
  13591. // 如果有 pic_prompt,添加到合并项中
  13592. $picPrompt = getProp($item, 'pic_prompt');
  13593. if (!empty($picPrompt)) {
  13594. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13595. }
  13596. // 继承现有项的 URL
  13597. $existingUrl = getProp($existingMap[$itemKey], 'url');
  13598. if (!empty($existingUrl)) {
  13599. $mergedItem['url'] = $existingUrl;
  13600. }
  13601. // 继承现有项的 task_id
  13602. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  13603. if (!empty($existingTaskId)) {
  13604. $mergedItem['task_id'] = $existingTaskId;
  13605. }
  13606. // 继承现有项的 task_status
  13607. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  13608. if (!empty($existingTaskStatus)) {
  13609. $mergedItem['task_status'] = $existingTaskStatus;
  13610. }
  13611. // 保留生成项的音色字段
  13612. $voiceName = getProp($item, 'voice_name');
  13613. if (!empty($voiceName)) {
  13614. $mergedItem['voice_name'] = $voiceName;
  13615. }
  13616. $voiceType = getProp($item, 'voice_type');
  13617. if (!empty($voiceType)) {
  13618. $mergedItem['voice_type'] = $voiceType;
  13619. }
  13620. $audioUrl = getProp($item, 'voice_audio_url');
  13621. if (!empty($audioUrl)) {
  13622. $mergedItem['voice_audio_url'] = $audioUrl;
  13623. }
  13624. $merged[] = $mergedItem;
  13625. } else {
  13626. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  13627. $mergedItem = [
  13628. $nameKey => trim((string)getProp($item, $nameKey)),
  13629. 'description' => trim((string)getProp($item, 'description')),
  13630. ];
  13631. // 如果有 pic_prompt,添加到合并项中
  13632. $picPrompt = getProp($item, 'pic_prompt');
  13633. if (!empty($picPrompt)) {
  13634. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13635. }
  13636. // 保留生成项的音色字段
  13637. $voiceName = getProp($item, 'voice_name');
  13638. if (!empty($voiceName)) {
  13639. $mergedItem['voice_name'] = $voiceName;
  13640. }
  13641. $voiceType = getProp($item, 'voice_type');
  13642. if (!empty($voiceType)) {
  13643. $mergedItem['voice_type'] = $voiceType;
  13644. }
  13645. $audioUrl = getProp($item, 'voice_audio_url');
  13646. if (!empty($audioUrl)) {
  13647. $mergedItem['voice_audio_url'] = $audioUrl;
  13648. }
  13649. // 不继承 URL、task_id 和 task_status(重置状态)
  13650. $merged[] = $mergedItem;
  13651. }
  13652. } else {
  13653. // 新增项,保留生成项的所有字段
  13654. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  13655. }
  13656. }
  13657. return $merged ?: array_values($existingItems);
  13658. }
  13659. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  13660. {
  13661. $resetItem = [
  13662. $nameKey => trim((string)getProp($item, $nameKey)),
  13663. 'description' => trim((string)getProp($item, 'description')),
  13664. ];
  13665. // 保留指定的字段
  13666. foreach ($preserveFields as $field) {
  13667. $value = getProp($item, $field);
  13668. if (!empty($value)) {
  13669. $resetItem[$field] = $value;
  13670. }
  13671. }
  13672. return $resetItem;
  13673. }
  13674. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  13675. {
  13676. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  13677. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  13678. if ($existingKey !== $generatedKey) {
  13679. return true;
  13680. }
  13681. // 比较 description 是否变化
  13682. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  13683. return true;
  13684. }
  13685. // 比较 pic_prompt 是否变化
  13686. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  13687. }
  13688. private function normalizeEpisodeResourceKey($value): string
  13689. {
  13690. $value = trim((string)$value);
  13691. if ($value === '') {
  13692. return '';
  13693. }
  13694. return strtolower((string)preg_replace('/\s+/u', '', $value));
  13695. }
  13696. // 生成全局角色图片
  13697. private function batchSetGlobalRoleImg($data, $is_force=false) {
  13698. $anime_id = getProp($data, 'anime_id');
  13699. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13700. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13701. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13702. $art_style = getProp($anime, 'art_style');
  13703. $update_flag = false;
  13704. foreach ($roles as &$role) {
  13705. $role_name = getProp($role, 'role');
  13706. if ($role_name == '旁白') continue;
  13707. // 优先使用 pic_prompt,如果没有则使用 description
  13708. $pic_prompt = getProp($role, 'pic_prompt');
  13709. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13710. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13711. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13712. // 参考图地址
  13713. $ref_img_url = getProp($role, 'url');
  13714. if (!$is_force && $ref_img_url) continue;
  13715. $update_flag = true;
  13716. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13717. try {
  13718. $params = [
  13719. 'prompt' => $description,
  13720. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  13721. 'ref_img_urls' => [],
  13722. // 计费锚点(动漫/剧本),用于积分明细归属统计
  13723. 'anime_id' => $anime_id,
  13724. ];
  13725. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13726. $task_id = $task->id;
  13727. if (!$task_id) {
  13728. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  13729. }
  13730. $role['task_id'] = $task_id;
  13731. $role['task_status'] = 'processing';
  13732. } catch (\Exception $e) {
  13733. Utils::throwError("20003:" . $e->getMessage());
  13734. }
  13735. }
  13736. if (!$update_flag) return true;
  13737. // 保存角色信息
  13738. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13739. 'roles' => json_encode($roles, 256),
  13740. 'generate_status' => '执行中',
  13741. 'generate_at' => date('Y-m-d H:i:s'),
  13742. 'updated_at' => date('Y-m-d H:i:s')
  13743. ]);
  13744. if (!$boolen) {
  13745. Utils::throwError('20003:保存角色信息失败');
  13746. }
  13747. return $boolen;
  13748. }
  13749. // 生成全局场景图片
  13750. private function batchSetGlobalSceneImg($data, $is_force=false) {
  13751. $anime_id = getProp($data, 'anime_id');
  13752. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13753. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13754. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13755. $art_style = getProp($anime, 'art_style');
  13756. $update_flag = false;
  13757. foreach ($scenes as &$scene) {
  13758. $scene_name = getProp($scene, 'scene');
  13759. // 优先使用 pic_prompt,如果没有则使用 description
  13760. $pic_prompt = getProp($scene, 'pic_prompt');
  13761. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13762. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  13763. // 参考图地址
  13764. $ref_img_url = getProp($scene, 'url');
  13765. if (!$is_force && $ref_img_url) continue;
  13766. $update_flag = true;
  13767. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13768. try {
  13769. $params = [
  13770. 'prompt' => $description,
  13771. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  13772. 'ref_img_urls' => [],
  13773. // 计费锚点(动漫/剧本),用于积分明细归属统计
  13774. 'anime_id' => $anime_id,
  13775. ];
  13776. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13777. $task_id = $task->id;
  13778. if (!$task_id) {
  13779. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  13780. }
  13781. $scene['task_id'] = $task_id;
  13782. $scene['task_status'] = 'processing';
  13783. } catch (\Exception $e) {
  13784. Utils::throwError("20003:" . $e->getMessage());
  13785. }
  13786. }
  13787. if (!$update_flag) return true;
  13788. // 保存角色信息
  13789. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13790. 'scenes' => json_encode($scenes, 256),
  13791. 'generate_status' => '执行中',
  13792. 'generate_at' => date('Y-m-d H:i:s'),
  13793. 'updated_at' => date('Y-m-d H:i:s')
  13794. ]);
  13795. if (!$boolen) {
  13796. Utils::throwError('20003:保存角色信息失败');
  13797. }
  13798. return $boolen;
  13799. }
  13800. // 生成分镜主体、场景和道具图片
  13801. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  13802. $character_prefix = '';
  13803. $scene_prefix = '';
  13804. $prop_prefix = '';
  13805. if ($art_style_type) {
  13806. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  13807. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  13808. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  13809. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  13810. }
  13811. $update_flag = false;
  13812. // 获取上一集的roles、scenes和props数据
  13813. $prev_roles = [];
  13814. $prev_scenes = [];
  13815. $prev_props = [];
  13816. if ($episode_number > 1) {
  13817. $prev_episode = DB::table('mp_anime_episodes')
  13818. ->where('anime_id', $anime_id)
  13819. ->where('episode_number', $episode_number - 1)
  13820. ->where('is_default', 1)
  13821. ->first();
  13822. if ($prev_episode) {
  13823. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  13824. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  13825. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  13826. dLog('deepseek')->info("获取上一集数据成功", [
  13827. 'anime_id' => $anime_id,
  13828. 'prev_episode_number' => $episode_number - 1,
  13829. 'prev_roles_count' => count($prev_roles),
  13830. 'prev_scenes_count' => count($prev_scenes),
  13831. 'prev_props_count' => count($prev_props)
  13832. ]);
  13833. }
  13834. }
  13835. // 处理角色图片生成
  13836. foreach ($roles as &$role) {
  13837. $role_name = getProp($role, 'role');
  13838. if ($role_name == '旁白') continue;
  13839. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  13840. if (isset($ref_products[$role_name])) {
  13841. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  13842. $role['three_view_image_url'] = isset($ref_products[$role_name]['three_view_image_url']) ? $ref_products[$role_name]['three_view_image_url'] : '';
  13843. if ($role['url']) continue;
  13844. }
  13845. $role_description = getProp($role, 'description');
  13846. $role_pic_prompt = getProp($role, 'pic_prompt');
  13847. $role_url = getProp($role, 'url');
  13848. // 检查是否可以从上一集继承
  13849. $inherited = false;
  13850. if (!$is_force && !empty($prev_roles)) {
  13851. foreach ($prev_roles as $prev_role) {
  13852. $prev_role_name = getProp($prev_role, 'role');
  13853. $prev_description = getProp($prev_role, 'description');
  13854. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  13855. $prev_url = getProp($prev_role, 'url');
  13856. $prev_task_id = getProp($prev_role, 'task_id');
  13857. $prev_task_status = getProp($prev_role, 'task_status');
  13858. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  13859. if ($role_name == $prev_role_name
  13860. && $role_description == $prev_description
  13861. && $role_pic_prompt == $prev_pic_prompt
  13862. && !empty($prev_url)) {
  13863. $role['task_id'] = $prev_task_id;
  13864. $role['task_status'] = $prev_task_status;
  13865. $role['url'] = $prev_url;
  13866. $inherited = true;
  13867. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  13868. 'anime_id' => $anime_id,
  13869. 'episode_number' => $episode_number,
  13870. 'task_id' => $prev_task_id,
  13871. 'url' => $prev_url
  13872. ]);
  13873. break;
  13874. }
  13875. }
  13876. }
  13877. // 如果已继承或已有url,跳过生成
  13878. if ($inherited || (!$is_force && $role_url)) {
  13879. continue;
  13880. }
  13881. // 优先使用 pic_prompt,如果没有则使用 description
  13882. $pic_prompt = getProp($role, 'pic_prompt');
  13883. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13884. $description = buildStylePromptPrefix($character_prefix) . "主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13885. $update_flag = true;
  13886. // 调用AIImageGenerationService的生成图片任务接口
  13887. try {
  13888. $params = [
  13889. 'prompt' => $description,
  13890. 'ref_img_urls' => [],
  13891. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  13892. 'anime_id' => $anime_id,
  13893. 'episode_number' => $episode_number,
  13894. ];
  13895. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13896. $task_id = $task->id;
  13897. if (!$task_id) {
  13898. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  13899. continue; // 不中断,继续处理其他角色
  13900. }
  13901. $role['task_id'] = $task_id;
  13902. $role['task_status'] = 'processing';
  13903. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  13904. 'anime_id' => $anime_id,
  13905. 'episode_number' => $episode_number,
  13906. 'task_id' => $task_id
  13907. ]);
  13908. } catch (\Exception $e) {
  13909. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  13910. // 不抛出异常,继续处理其他角色
  13911. }
  13912. }
  13913. // 处理场景图片生成
  13914. foreach ($scenes as &$scene) {
  13915. $scene_name = getProp($scene, 'scene');
  13916. $scene_description = getProp($scene, 'description');
  13917. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  13918. $scene_url = getProp($scene, 'url');
  13919. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  13920. if (isset($ref_products[$scene_name])) {
  13921. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  13922. $scene['three_view_image_url'] = isset($ref_products[$scene_name]['three_view_image_url']) ? $ref_products[$scene_name]['three_view_image_url'] : '';
  13923. if ($scene['url']) continue;
  13924. }
  13925. // 检查是否可以从上一集继承
  13926. $inherited = false;
  13927. if (!$is_force && !empty($prev_scenes)) {
  13928. foreach ($prev_scenes as $prev_scene) {
  13929. $prev_scene_name = getProp($prev_scene, 'scene');
  13930. $prev_description = getProp($prev_scene, 'description');
  13931. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  13932. $prev_url = getProp($prev_scene, 'url');
  13933. $prev_task_id = getProp($prev_scene, 'task_id');
  13934. $prev_task_status = getProp($prev_scene, 'task_status');
  13935. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  13936. if ($scene_name == $prev_scene_name
  13937. && $scene_description == $prev_description
  13938. && $scene_pic_prompt == $prev_pic_prompt
  13939. && !empty($prev_url)) {
  13940. $scene['task_id'] = $prev_task_id;
  13941. $scene['task_status'] = $prev_task_status;
  13942. $scene['url'] = $prev_url;
  13943. $inherited = true;
  13944. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  13945. 'anime_id' => $anime_id,
  13946. 'episode_number' => $episode_number,
  13947. 'task_id' => $prev_task_id,
  13948. 'url' => $prev_url
  13949. ]);
  13950. break;
  13951. }
  13952. }
  13953. }
  13954. // 如果已继承或已有url,跳过生成
  13955. if ($inherited || (!$is_force && $scene_url)) {
  13956. continue;
  13957. }
  13958. // 优先使用 pic_prompt,如果没有则使用 description
  13959. $pic_prompt = getProp($scene, 'pic_prompt');
  13960. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13961. $description = buildStylePromptPrefix($scene_prefix) . "场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13962. $update_flag = true;
  13963. // 调用AIImageGenerationService的生成图片任务接口
  13964. try {
  13965. $params = [
  13966. 'prompt' => $description,
  13967. 'ref_img_urls' => [],
  13968. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  13969. 'anime_id' => $anime_id,
  13970. 'episode_number' => $episode_number,
  13971. ];
  13972. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13973. $task_id = $task->id;
  13974. if (!$task_id) {
  13975. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  13976. continue; // 不中断,继续处理其他场景
  13977. }
  13978. $scene['task_id'] = $task_id;
  13979. $scene['task_status'] = 'processing';
  13980. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  13981. 'anime_id' => $anime_id,
  13982. 'episode_number' => $episode_number,
  13983. 'task_id' => $task_id
  13984. ]);
  13985. } catch (\Exception $e) {
  13986. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  13987. // 不抛出异常,继续处理其他场景
  13988. }
  13989. }
  13990. // 处理道具图片生成(逻辑与场景一致)
  13991. foreach ($props as &$prop) {
  13992. $prop_name = getProp($prop, 'prop');
  13993. $prop_description = getProp($prop, 'description');
  13994. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  13995. $prop_url = getProp($prop, 'url');
  13996. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  13997. if (isset($ref_products[$prop_name])) {
  13998. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  13999. $prop['three_view_image_url'] = isset($ref_products[$prop_name]['three_view_image_url']) ? $ref_products[$prop_name]['three_view_image_url'] : '';
  14000. if ($prop['url']) continue;
  14001. }
  14002. // 检查是否可以从上一集继承
  14003. $inherited = false;
  14004. if (!$is_force && !empty($prev_props)) {
  14005. foreach ($prev_props as $prev_prop) {
  14006. $prev_prop_name = getProp($prev_prop, 'prop');
  14007. $prev_description = getProp($prev_prop, 'description');
  14008. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  14009. $prev_url = getProp($prev_prop, 'url');
  14010. $prev_task_id = getProp($prev_prop, 'task_id');
  14011. $prev_task_status = getProp($prev_prop, 'task_status');
  14012. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  14013. if ($prop_name == $prev_prop_name
  14014. && $prop_description == $prev_description
  14015. && $prop_pic_prompt == $prev_pic_prompt
  14016. && !empty($prev_url)) {
  14017. $prop['task_id'] = $prev_task_id;
  14018. $prop['task_status'] = $prev_task_status;
  14019. $prop['url'] = $prev_url;
  14020. $inherited = true;
  14021. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  14022. 'anime_id' => $anime_id,
  14023. 'episode_number' => $episode_number,
  14024. 'task_id' => $prev_task_id,
  14025. 'url' => $prev_url
  14026. ]);
  14027. break;
  14028. }
  14029. }
  14030. }
  14031. // 如果已继承或已有url,跳过生成
  14032. if ($inherited || (!$is_force && $prop_url)) {
  14033. continue;
  14034. }
  14035. // 优先使用 pic_prompt,如果没有则使用 description
  14036. $pic_prompt = getProp($prop, 'pic_prompt');
  14037. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  14038. $description = buildStylePromptPrefix($prop_prefix) . "道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14039. $update_flag = true;
  14040. // 调用AIImageGenerationService的生成图片任务接口
  14041. try {
  14042. $params = [
  14043. 'prompt' => $description,
  14044. 'ref_img_urls' => [],
  14045. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  14046. 'anime_id' => $anime_id,
  14047. 'episode_number' => $episode_number,
  14048. ];
  14049. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14050. $task_id = $task->id;
  14051. if (!$task_id) {
  14052. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  14053. continue; // 不中断,继续处理其他道具
  14054. }
  14055. $prop['task_id'] = $task_id;
  14056. $prop['task_status'] = 'processing';
  14057. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  14058. 'anime_id' => $anime_id,
  14059. 'episode_number' => $episode_number,
  14060. 'task_id' => $task_id
  14061. ]);
  14062. } catch (\Exception $e) {
  14063. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  14064. // 不抛出异常,继续处理其他道具
  14065. }
  14066. }
  14067. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14068. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  14069. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  14070. // // 保存剧集的角色和场景信息
  14071. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  14072. // 'roles' => json_encode($roles, 256),
  14073. // 'scenes' => json_encode($scenes, 256),
  14074. // 'generate_status' => '执行中',
  14075. // 'generate_at' => date('Y-m-d H:i:s'),
  14076. // 'updated_at' => date('Y-m-d H:i:s')
  14077. // ]);
  14078. // if (!$boolen) {
  14079. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  14080. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  14081. // }
  14082. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  14083. // 'episode_id' => $episode_id,
  14084. 'roles_count' => count($roles),
  14085. 'scenes_count' => count($scenes),
  14086. 'props_count' => count($props)
  14087. ]);
  14088. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14089. }
  14090. /**
  14091. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  14092. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  14093. *
  14094. * @param int $anime_id 动漫对话ID
  14095. * @param array $episode_roles 剧集角色数据
  14096. * @param array $episode_scenes 剧集场景数据
  14097. * @param array $episode_props 剧集道具数据
  14098. * @return bool
  14099. */
  14100. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  14101. // 获取全局数据
  14102. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14103. if (!$anime) {
  14104. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14105. return false;
  14106. }
  14107. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14108. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14109. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  14110. $roles_added = false;
  14111. $roles_updated = false;
  14112. $scenes_added = false;
  14113. $props_added = false;
  14114. // 处理角色同步
  14115. foreach ($episode_roles as $episode_role) {
  14116. $episode_role_name = getProp($episode_role, 'role');
  14117. $episode_description = getProp($episode_role, 'description');
  14118. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14119. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  14120. // 跳过旁白
  14121. if ($episode_role_name == '旁白') {
  14122. continue;
  14123. }
  14124. // 检查全局中是否已存在相同的角色
  14125. $exists = false;
  14126. $global_role_index = -1;
  14127. foreach ($global_roles as $index => $global_role) {
  14128. $global_role_name = getProp($global_role, 'role');
  14129. $global_description = getProp($global_role, 'description');
  14130. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14131. // 如果role、description、pic_prompt三项都一致,则认为已存在
  14132. if ($episode_role_name == $global_role_name
  14133. && $episode_description == $global_description
  14134. && $episode_pic_prompt == $global_pic_prompt) {
  14135. $exists = true;
  14136. $global_role_index = $index;
  14137. break;
  14138. }
  14139. }
  14140. // 如果不存在,则添加到全局
  14141. if (!$exists) {
  14142. $global_roles[] = $episode_role;
  14143. $roles_added = true;
  14144. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  14145. 'anime_id' => $anime_id,
  14146. 'role' => $episode_role_name
  14147. ]);
  14148. } else {
  14149. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  14150. if (!empty($episode_voice_prompt)) {
  14151. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  14152. // 如果全局没有voice_prompt或与剧集不一致,则更新
  14153. if ($global_voice_prompt !== $episode_voice_prompt) {
  14154. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  14155. $roles_updated = true;
  14156. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  14157. 'anime_id' => $anime_id,
  14158. 'role' => $episode_role_name,
  14159. 'voice_prompt' => $episode_voice_prompt
  14160. ]);
  14161. }
  14162. }
  14163. }
  14164. }
  14165. // 处理场景同步
  14166. foreach ($episode_scenes as $episode_scene) {
  14167. $episode_scene_name = getProp($episode_scene, 'scene');
  14168. $episode_description = getProp($episode_scene, 'description');
  14169. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14170. // 检查全局中是否已存在相同的场景
  14171. $exists = false;
  14172. foreach ($global_scenes as $global_scene) {
  14173. $global_scene_name = getProp($global_scene, 'scene');
  14174. $global_description = getProp($global_scene, 'description');
  14175. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14176. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  14177. if ($episode_scene_name == $global_scene_name
  14178. && $episode_description == $global_description
  14179. && $episode_pic_prompt == $global_pic_prompt) {
  14180. $exists = true;
  14181. break;
  14182. }
  14183. }
  14184. // 如果不存在,则添加到全局
  14185. if (!$exists) {
  14186. $global_scenes[] = $episode_scene;
  14187. $scenes_added = true;
  14188. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  14189. 'anime_id' => $anime_id,
  14190. 'scene' => $episode_scene_name
  14191. ]);
  14192. }
  14193. }
  14194. // 处理道具同步(逻辑与场景一致)
  14195. foreach ($episode_props as $episode_prop) {
  14196. $episode_prop_name = getProp($episode_prop, 'prop');
  14197. $episode_description = getProp($episode_prop, 'description');
  14198. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  14199. // 检查全局中是否已存在相同的道具
  14200. $exists = false;
  14201. foreach ($global_props as $global_prop) {
  14202. $global_prop_name = getProp($global_prop, 'prop');
  14203. $global_description = getProp($global_prop, 'description');
  14204. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  14205. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  14206. if ($episode_prop_name == $global_prop_name
  14207. && $episode_description == $global_description
  14208. && $episode_pic_prompt == $global_pic_prompt) {
  14209. $exists = true;
  14210. break;
  14211. }
  14212. }
  14213. // 如果不存在,则添加到全局
  14214. if (!$exists) {
  14215. $global_props[] = $episode_prop;
  14216. $props_added = true;
  14217. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  14218. 'anime_id' => $anime_id,
  14219. 'prop' => $episode_prop_name
  14220. ]);
  14221. }
  14222. }
  14223. // 如果有新增或更新,则更新全局数据
  14224. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  14225. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14226. if ($roles_added || $roles_updated) {
  14227. $update_data['roles'] = json_encode($global_roles, 256);
  14228. }
  14229. if ($scenes_added) {
  14230. $update_data['scenes'] = json_encode($global_scenes, 256);
  14231. }
  14232. if ($props_added) {
  14233. $update_data['props'] = json_encode($global_props, 256);
  14234. }
  14235. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  14236. dLog('deepseek')->info('剧集数据同步到全局完成', [
  14237. 'anime_id' => $anime_id,
  14238. 'roles_added' => $roles_added,
  14239. 'roles_updated' => $roles_updated,
  14240. 'scenes_added' => $scenes_added,
  14241. 'props_added' => $props_added,
  14242. 'global_roles_count' => count($global_roles),
  14243. 'global_scenes_count' => count($global_scenes),
  14244. 'global_props_count' => count($global_props)
  14245. ]);
  14246. }
  14247. return true;
  14248. }
  14249. /**
  14250. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  14251. *
  14252. * @param int $anime_id 动漫对话ID
  14253. * @param int $episode_id 分集ID
  14254. * @return bool
  14255. */
  14256. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  14257. // 获取全局角色和场景数据
  14258. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14259. if (!$anime) {
  14260. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14261. return false;
  14262. }
  14263. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14264. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14265. // 获取指定的分集
  14266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  14267. if (!$episode) {
  14268. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  14269. return false;
  14270. }
  14271. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  14272. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  14273. $roles_updated = false;
  14274. $scenes_updated = false;
  14275. // 继承角色的task_id、task_status和url
  14276. foreach ($episode_roles as &$episode_role) {
  14277. $episode_role_name = getProp($episode_role, 'role');
  14278. $episode_description = getProp($episode_role, 'description');
  14279. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14280. $episode_url = getProp($episode_role, 'url');
  14281. // 跳过旁白角色
  14282. if ($episode_role_name == '旁白') {
  14283. continue;
  14284. }
  14285. // 如果剧集中已有URL,跳过
  14286. if (!empty($episode_url)) {
  14287. continue;
  14288. }
  14289. // 遍历全局角色数据,查找匹配的角色
  14290. foreach ($global_roles as $global_role) {
  14291. $global_role_name = getProp($global_role, 'role');
  14292. $global_description = getProp($global_role, 'description');
  14293. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14294. $global_url = getProp($global_role, 'url');
  14295. $global_task_id = getProp($global_role, 'task_id');
  14296. $global_task_status = getProp($global_role, 'task_status');
  14297. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14298. if ($episode_role_name == $global_role_name
  14299. && $episode_description == $global_description
  14300. && $episode_pic_prompt == $global_pic_prompt) {
  14301. // 继承 task_id、task_status 和 url
  14302. if (!empty($global_task_id)) {
  14303. $episode_role['task_id'] = $global_task_id;
  14304. $episode_role['task_status'] = $global_task_status;
  14305. $roles_updated = true;
  14306. dLog('deepseek')->info('剧集角色继承全局task_id', [
  14307. 'episode_id' => $episode_id,
  14308. 'role' => $episode_role_name,
  14309. 'task_id' => $global_task_id,
  14310. 'task_status' => $global_task_status
  14311. ]);
  14312. }
  14313. if (!empty($global_url)) {
  14314. $episode_role['url'] = $global_url;
  14315. $roles_updated = true;
  14316. dLog('deepseek')->info('剧集角色继承全局url', [
  14317. 'episode_id' => $episode_id,
  14318. 'role' => $episode_role_name,
  14319. 'url' => $global_url
  14320. ]);
  14321. }
  14322. break;
  14323. }
  14324. }
  14325. }
  14326. // 继承场景的task_id、task_status和url
  14327. foreach ($episode_scenes as &$episode_scene) {
  14328. $episode_scene_name = getProp($episode_scene, 'scene');
  14329. $episode_description = getProp($episode_scene, 'description');
  14330. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14331. $episode_url = getProp($episode_scene, 'url');
  14332. // 如果剧集中已有URL,跳过
  14333. if (!empty($episode_url)) {
  14334. continue;
  14335. }
  14336. // 遍历全局场景数据,查找匹配的场景
  14337. foreach ($global_scenes as $global_scene) {
  14338. $global_scene_name = getProp($global_scene, 'scene');
  14339. $global_description = getProp($global_scene, 'description');
  14340. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14341. $global_url = getProp($global_scene, 'url');
  14342. $global_task_id = getProp($global_scene, 'task_id');
  14343. $global_task_status = getProp($global_scene, 'task_status');
  14344. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14345. if ($episode_scene_name == $global_scene_name
  14346. && $episode_description == $global_description
  14347. && $episode_pic_prompt == $global_pic_prompt) {
  14348. // 继承 task_id、task_status 和 url
  14349. if (!empty($global_task_id)) {
  14350. $episode_scene['task_id'] = $global_task_id;
  14351. $episode_scene['task_status'] = $global_task_status;
  14352. $scenes_updated = true;
  14353. dLog('deepseek')->info('剧集场景继承全局task_id', [
  14354. 'episode_id' => $episode_id,
  14355. 'scene' => $episode_scene_name,
  14356. 'task_id' => $global_task_id,
  14357. 'task_status' => $global_task_status
  14358. ]);
  14359. }
  14360. if (!empty($global_url)) {
  14361. $episode_scene['url'] = $global_url;
  14362. $scenes_updated = true;
  14363. dLog('deepseek')->info('剧集场景继承全局url', [
  14364. 'episode_id' => $episode_id,
  14365. 'scene' => $episode_scene_name,
  14366. 'url' => $global_url
  14367. ]);
  14368. }
  14369. break;
  14370. }
  14371. }
  14372. }
  14373. // 如果有更新,则保存到数据库
  14374. if ($roles_updated || $scenes_updated) {
  14375. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14376. if ($roles_updated) {
  14377. $update_data['roles'] = json_encode($episode_roles, 256);
  14378. }
  14379. if ($scenes_updated) {
  14380. $update_data['scenes'] = json_encode($episode_scenes, 256);
  14381. }
  14382. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  14383. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  14384. 'episode_id' => $episode_id,
  14385. 'roles_updated' => $roles_updated,
  14386. 'scenes_updated' => $scenes_updated
  14387. ]);
  14388. }
  14389. return true;
  14390. }
  14391. public function chatChangeImg($data) {
  14392. // 文生文计费预检(normal 档)
  14393. $uid = Site::getUid();
  14394. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  14395. $segment = getProp($data, 'segment');
  14396. $segment_content = getProp($segment, 'segment_content');
  14397. $prompt = getProp($data, 'prompt');
  14398. $ref_img = getProp($data, 'ref_img');
  14399. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  14400. // 处理文本模型
  14401. $model = getProp($data, 'model');
  14402. if (!$model) {
  14403. // 用户没有输入,从anime表获取
  14404. $segment_id = getProp($segment, 'segment_id');
  14405. if ($segment_id) {
  14406. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  14407. if ($episode_id) {
  14408. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  14409. if ($anime_id) {
  14410. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  14411. }
  14412. }
  14413. }
  14414. if (!$model) {
  14415. // anime表也没有,使用默认值
  14416. $model = 'doubao-seed-2-0-mini-260215';
  14417. }
  14418. }
  14419. // 验证模型是否在可用模型表中
  14420. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  14421. $model = 'doubao-seed-2-0-mini-260215';
  14422. }
  14423. $messages[] =
  14424. [
  14425. 'role' => 'user',
  14426. 'content' => $question
  14427. ];
  14428. $post_data = [
  14429. 'model' => $model,
  14430. 'messages' => $messages,
  14431. // 'max_tokens' => 8192,
  14432. 'temperature' => 0.7,
  14433. 'frequency_penalty' => 0,
  14434. 'presence_penalty' => 0,
  14435. 'response_format' => ['type' => 'text'],
  14436. 'stream' => false // 是否启用流式输出
  14437. ];
  14438. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14439. if (is_array($chatResult)) {
  14440. extract($chatResult);
  14441. }else {
  14442. Utils::throwError('20003: 接口调用失败!');
  14443. }
  14444. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  14445. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  14446. 'model' => $model,
  14447. 'source' => 'chatChangeImg',
  14448. ], 'normal');
  14449. return [
  14450. 'type' => 'done',
  14451. // 'episode' => $episode,
  14452. 'answer' => $fullContent,
  14453. 'reasoning' => $fullReasoningContent,
  14454. 'usage' => $usage
  14455. ];
  14456. }
  14457. /**
  14458. * 仅调用 deepseek 对话接口(非流式)
  14459. *
  14460. * @param array $post_data
  14461. * @param int $timeout
  14462. * @return array
  14463. */
  14464. private function chatOnly($post_data, $timeout = 1800) {
  14465. $post_data['max_tokens'] = 300000;
  14466. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  14467. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  14468. $response = $result->getBody()->getContents();
  14469. $response_arr = json_decode($response, true);
  14470. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  14471. $fullContent = '';
  14472. $fullReasoningContent = [];
  14473. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14474. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14475. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14476. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  14477. }
  14478. return [
  14479. 'fullContent' => $fullContent,
  14480. 'fullReasoningContent' => $fullReasoningContent,
  14481. 'usage' => $usage
  14482. ];
  14483. }
  14484. /**
  14485. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  14486. *
  14487. * @param string $errorMessage
  14488. * @return string|null
  14489. */
  14490. public function analyzeErrorMessage($errorMessage)
  14491. {
  14492. try {
  14493. $post_data = [
  14494. 'model' => 'deepseek-v4-flash',
  14495. 'messages' => [
  14496. [
  14497. 'role' => 'system',
  14498. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  14499. ],
  14500. [
  14501. 'role' => 'user',
  14502. 'content' => (string)$errorMessage,
  14503. ],
  14504. ],
  14505. 'temperature' => 0.3,
  14506. 'frequency_penalty' => 0,
  14507. 'presence_penalty' => 0,
  14508. 'response_format' => ['type' => 'text'],
  14509. 'stream' => false,
  14510. ];
  14511. $result = $this->chatOnly($post_data, 8);
  14512. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  14513. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  14514. 'model' => 'deepseek-v4-flash',
  14515. 'source' => 'analyzeErrorMessage',
  14516. ], 'deepseek-v4-flash');
  14517. $content = trim((string)($result['fullContent'] ?? ''));
  14518. if ($content === '') {
  14519. return null;
  14520. }
  14521. return mb_substr($content, 0, 50);
  14522. } catch (\Exception $e) {
  14523. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  14524. 'error_message' => $errorMessage
  14525. ]);
  14526. return null;
  14527. }
  14528. }
  14529. // 仅调用 GPT-5.4 对话接口(非流式)
  14530. private function gpt54ChatOnly($post_data) {
  14531. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  14532. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  14533. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  14534. if ($modelName === 'gpt-5.4') {
  14535. $modelName = 'gpt-5.6-terra';
  14536. $post_data['model'] = $modelName;
  14537. }
  14538. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  14539. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  14540. $usedLunaFallback = false;
  14541. if (empty($apiKey)) {
  14542. Utils::throwError('20003:GPT-5.4 API Key未配置');
  14543. }
  14544. // 先探活,服务不可用时自动重试
  14545. $this->ensureGptServiceAvailable($apiKey);
  14546. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14547. // 移除 thinking 参数,GPT-5.4 不支持
  14548. if (isset($post_data['thinking'])) {
  14549. unset($post_data['thinking']);
  14550. }
  14551. if (isset($post_data['reasoning_effort'])) {
  14552. unset($post_data['reasoning_effort']);
  14553. }
  14554. // GPT-5.x(推理型上游)只接受默认 temperature(1),传入其他值会返回 400:
  14555. // Unsupported value: 'temperature' does not support 1.35 with this model.
  14556. // Only the default (1) value is supported.
  14557. unset($post_data['temperature']);
  14558. $post_data['max_completion_tokens'] = 100000;
  14559. // GPT-5.x 上游不支持 max_tokens,与 gpt54StreamResponse 保持一致,显式移除避免 400。
  14560. unset($post_data['max_tokens']);
  14561. // GPT-5.x 上游不接受 frequency_penalty / presence_penalty,移除默认值 0 不影响行为。
  14562. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  14563. // 确保 stream 为 false
  14564. $post_data['stream'] = false;
  14565. $maxRetries = $this->gptRetryTimes();
  14566. $interval = $this->gptRetryInterval();
  14567. $attempt = 0;
  14568. while (true) {
  14569. try {
  14570. $headers = [
  14571. 'Authorization' => 'Bearer ' . $apiKey,
  14572. 'Content-Type' => 'application/json'
  14573. ];
  14574. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  14575. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  14576. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  14577. 'json' => $post_data,
  14578. 'headers' => $headers
  14579. ]);
  14580. $response = $result->getBody()->getContents();
  14581. $response_arr = json_decode($response, true);
  14582. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  14583. $fullContent = '';
  14584. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14585. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14586. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14587. }
  14588. return [
  14589. 'fullContent' => $fullContent,
  14590. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  14591. 'usage' => $usage
  14592. ];
  14593. } catch (\Exception $e) {
  14594. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  14595. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  14596. $usedLunaFallback = true;
  14597. $apiKey = $lunaApiKey;
  14598. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  14599. continue;
  14600. }
  14601. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  14602. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  14603. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  14604. throw $e;
  14605. }
  14606. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  14607. 'retry' => $attempt + 1,
  14608. 'max_retries' => $maxRetries,
  14609. 'error' => $e->getMessage()
  14610. ]);
  14611. sleep($interval);
  14612. $attempt++;
  14613. }
  14614. }
  14615. }
  14616. public function getContentByBid($bid) {
  14617. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  14618. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  14619. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  14620. $content = '';
  14621. foreach ($chapters as $chapter) {
  14622. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  14623. }
  14624. return $content;
  14625. }
  14626. public function getContentByScriptId($script_id) {
  14627. $content = '';
  14628. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  14629. if ($contents) {
  14630. $content = implode(PHP_EOL, $contents);
  14631. }else {
  14632. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  14633. }
  14634. return $content;
  14635. }
  14636. /**
  14637. * 根据文件类型提取文本内容
  14638. *
  14639. * @param mixed $file 文件对象或文件路径
  14640. * @return string
  14641. */
  14642. public function extractFileContent($file) {
  14643. // 获取文件路径和扩展名
  14644. if (is_string($file)) {
  14645. $filePath = $file;
  14646. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  14647. } else {
  14648. // Laravel UploadedFile 对象
  14649. $filePath = $file->getRealPath();
  14650. $extension = strtolower($file->getClientOriginalExtension());
  14651. }
  14652. $content = '';
  14653. switch ($extension) {
  14654. case 'txt':
  14655. $content = $this->extractTxtContent($filePath);
  14656. break;
  14657. case 'pdf':
  14658. $content = $this->extractPdfContent($filePath);
  14659. break;
  14660. case 'doc':
  14661. case 'docx':
  14662. $content = $this->extractWordContent($filePath);
  14663. break;
  14664. // case 'jpg':
  14665. // case 'jpeg':
  14666. // case 'png':
  14667. // case 'gif':
  14668. // case 'bmp':
  14669. // case 'webp':
  14670. // $content = $this->extractImageContent($filePath);
  14671. // break;
  14672. default:
  14673. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  14674. }
  14675. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  14676. if (!mb_check_encoding($content, 'UTF-8')) {
  14677. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  14678. $content = $cleaned === false ? $content : $cleaned;
  14679. }
  14680. return $content;
  14681. }
  14682. /**
  14683. * 提取 TXT 文件内容
  14684. */
  14685. private function extractTxtContent($filePath) {
  14686. if (!file_exists($filePath)) {
  14687. Utils::throwError('20003:文件不存在');
  14688. }
  14689. $content = file_get_contents($filePath);
  14690. // 尝试检测并转换编码
  14691. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  14692. if ($encoding && $encoding !== 'UTF-8') {
  14693. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  14694. }
  14695. return trim($content);
  14696. }
  14697. /**
  14698. * 提取 PDF 文件内容
  14699. */
  14700. private function extractPdfContent($filePath) {
  14701. if (!file_exists($filePath)) {
  14702. Utils::throwError('20003:文件不存在');
  14703. }
  14704. try {
  14705. $parser = new PdfParser();
  14706. $pdf = $parser->parseFile($filePath);
  14707. $content = $pdf->getText();
  14708. return trim($content);
  14709. } catch (\Exception $e) {
  14710. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  14711. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  14712. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  14713. }
  14714. }
  14715. /**
  14716. * 提取 Word 文件内容(支持 doc 和 docx)
  14717. */
  14718. private function extractWordContent($filePath) {
  14719. if (!file_exists($filePath)) {
  14720. Utils::throwError('20003:文件不存在');
  14721. }
  14722. try {
  14723. $phpWord = WordIOFactory::load($filePath);
  14724. $content = '';
  14725. foreach ($phpWord->getSections() as $section) {
  14726. foreach ($section->getElements() as $element) {
  14727. $content .= $this->extractWordElementText($element);
  14728. // 段落边界补换行(段落内的软换行已在元素递归中处理)
  14729. $content .= "\n";
  14730. }
  14731. }
  14732. return trim($content);
  14733. } catch (\Exception $e) {
  14734. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  14735. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  14736. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  14737. }
  14738. }
  14739. /**
  14740. * 递归提取 Word 元素中的文本
  14741. */
  14742. private function extractWordElementText($element) {
  14743. $text = '';
  14744. if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak
  14745. || $element instanceof \PhpOffice\PhpWord\Element\LineBreak) {
  14746. // 软换行:保留 Word 中的换行显示,避免"第X集"标题与正文粘连
  14747. $text .= "\n";
  14748. } elseif (method_exists($element, 'getElements')) {
  14749. foreach ($element->getElements() as $childElement) {
  14750. $text .= $this->extractWordElementText($childElement);
  14751. }
  14752. } elseif (method_exists($element, 'getText')) {
  14753. $text .= $element->getText();
  14754. }
  14755. return $text;
  14756. }
  14757. /**
  14758. * 提取图片内容(使用火山引擎 OCR)
  14759. */
  14760. private function extractImageContent($filePath) {
  14761. if (!file_exists($filePath)) {
  14762. Utils::throwError('20003:文件不存在');
  14763. }
  14764. try {
  14765. // 读取图片并转换为 base64
  14766. $imageData = file_get_contents($filePath);
  14767. $base64Image = base64_encode($imageData);
  14768. // 调用火山引擎 OCR 服务
  14769. $content = $this->callVolcEngineOCR($base64Image);
  14770. return trim($content);
  14771. } catch (\Exception $e) {
  14772. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  14773. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  14774. Utils::throwError('20003:图片识别失败');
  14775. }
  14776. }
  14777. /**
  14778. * 调用火山引擎 OCR 服务识别图片文字
  14779. *
  14780. * @param string $base64Image base64 编码的图片数据
  14781. * @return string 识别的文字内容
  14782. */
  14783. private function callVolcEngineOCR($base64Image) {
  14784. $method = 'POST';
  14785. $service = 'cv';
  14786. $host = 'visual.volcengineapi.com';
  14787. $region = env('VOLC_REGION', 'cn-north-1');
  14788. $access_key = env('VOLC_AK');
  14789. $secret_key = env('VOLC_SK');
  14790. $action = 'OCRNormal';
  14791. $version = '2020-08-26';
  14792. if (!$access_key || !$secret_key) {
  14793. Utils::throwError('20003:请配置火山引擎 AK/SK');
  14794. }
  14795. // 请求体
  14796. $body = json_encode([
  14797. 'image_base64' => $base64Image
  14798. ]);
  14799. // 生成签名
  14800. $headers = $this->getVolcEngineSignHeaders(
  14801. $method, $service, $host, $region,
  14802. "Action={$action}&Version={$version}",
  14803. $access_key, $secret_key, $body
  14804. );
  14805. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14806. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  14807. 'headers' => $headers,
  14808. 'body' => $body
  14809. ]);
  14810. $response_arr = json_decode($response->getBody()->getContents(), true);
  14811. // 提取识别的文字
  14812. $textLines = [];
  14813. if (isset($response_arr['data']['line_texts'])) {
  14814. $textLines = $response_arr['data']['line_texts'];
  14815. } elseif (isset($response_arr['data']['ocr_infos'])) {
  14816. foreach ($response_arr['data']['ocr_infos'] as $info) {
  14817. if (isset($info['text'])) {
  14818. $textLines[] = $info['text'];
  14819. }
  14820. }
  14821. }
  14822. if (empty($textLines)) {
  14823. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  14824. return '';
  14825. }
  14826. return implode("\n", $textLines);
  14827. }
  14828. /**
  14829. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  14830. */
  14831. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  14832. $contentType = 'application/json';
  14833. $accept = 'application/json';
  14834. // 获取当前UTC时间
  14835. $t = new DateTime('now', new DateTimeZone('UTC'));
  14836. $xDate = $t->format('Ymd\THis\Z');
  14837. $dateStamp = $t->format('Ymd');
  14838. // 计算 body 的 sha256 哈希
  14839. $payloadHash = hash('sha256', $body);
  14840. // 1. 拼接规范请求串
  14841. $canonicalUri = '/';
  14842. $canonicalQueryString = $queryString;
  14843. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  14844. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  14845. $canonicalRequest = implode("\n", [
  14846. $method,
  14847. $canonicalUri,
  14848. $canonicalQueryString,
  14849. $canonicalHeaders,
  14850. $signedHeaders,
  14851. $payloadHash
  14852. ]);
  14853. // 2. 拼接待签名字符串
  14854. $algorithm = 'HMAC-SHA256';
  14855. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  14856. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  14857. $stringToSign = implode("\n", [
  14858. $algorithm,
  14859. $xDate,
  14860. $credentialScope,
  14861. $hashedCanonicalRequest
  14862. ]);
  14863. // 3. 计算签名
  14864. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  14865. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  14866. // 4. 添加签名到请求头
  14867. $authorizationHeader = sprintf(
  14868. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  14869. $algorithm,
  14870. $access_key,
  14871. $credentialScope,
  14872. $signedHeaders,
  14873. $signature
  14874. );
  14875. return [
  14876. 'Accept' => $accept,
  14877. 'Content-Type' => $contentType,
  14878. 'Host' => $host,
  14879. 'X-Date' => $xDate,
  14880. 'X-Content-Sha256'=> $payloadHash,
  14881. 'Authorization' => $authorizationHeader
  14882. ];
  14883. }
  14884. public function generateScriptWords($cid, $model = 'r1') {
  14885. ini_set('max_execution_time', 0);
  14886. if (!$cid) Utils::throwError('20003: 请选择章节!');
  14887. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  14888. // 模型兼容性处理和思考模式设置
  14889. $thinkingMode = 'disabled';
  14890. $reasoningEffort = 'high';
  14891. if ($model == 'r1') {
  14892. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  14893. $thinkingMode = 'enabled';
  14894. } else {
  14895. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  14896. $thinkingMode = 'disabled';
  14897. }
  14898. $messages = [
  14899. [
  14900. 'role' => 'system',
  14901. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  14902. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  14903. 2.非对话部分请全部用旁白角色代替
  14904. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  14905. ],
  14906. [
  14907. 'role' => 'user',
  14908. 'content' => $content
  14909. ]
  14910. ];
  14911. $post_data = [
  14912. 'model' => $model,
  14913. 'messages' => $messages,
  14914. // 'max_tokens' => 8192,
  14915. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  14916. 'frequency_penalty' => 0,
  14917. 'presence_penalty' => 0,
  14918. 'thinking' => ['type' => $thinkingMode],
  14919. 'response_format' => [
  14920. 'type' => 'text'
  14921. ],
  14922. 'stream' => false
  14923. ];
  14924. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  14925. // 根据模型类型选择调用方法
  14926. $fullContent = '';
  14927. $usage = [];
  14928. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14929. if (is_array($chatResult)) {
  14930. $fullContent = $chatResult['fullContent'];
  14931. $usage = $chatResult['usage'] ?? [];
  14932. }
  14933. // 仅记录 token 使用明细(不扣积分)
  14934. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  14935. 'model' => $model,
  14936. 'cid' => $cid,
  14937. 'source' => 'generateScriptWords',
  14938. ], $model);
  14939. return $fullContent;
  14940. }
  14941. /**
  14942. * 智能化解析集数信息
  14943. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  14944. *
  14945. * @param string $prompt 用户输入的提示词
  14946. * @return int|null 解析出的集数,如果没有找到则返回null
  14947. */
  14948. private function extractEpisodeNumber($prompt)
  14949. {
  14950. if (empty($prompt)) {
  14951. return null;
  14952. }
  14953. // 定义各种可能的表达模式
  14954. $patterns = [
  14955. // 基本模式:改成N集、调整成N集、修改成N集
  14956. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  14957. // 扩展模式:分成N集、拆分成N集、分割成N集
  14958. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  14959. // 数量模式:N集、共N集、总共N集
  14960. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  14961. // 制作模式:制作N集、生成N集、创建N集
  14962. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  14963. // 计划模式:计划N集、预计N集、打算N集
  14964. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  14965. // 需要模式:需要N集、要N集
  14966. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  14967. // 中文数字模式:改成三集、调整成五集等
  14968. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  14969. // 英文数字模式
  14970. '/(?: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',
  14971. ];
  14972. // 中文数字转阿拉伯数字的映射
  14973. $chineseNumbers = [
  14974. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  14975. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  14976. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  14977. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  14978. ];
  14979. // 逐个尝试匹配模式
  14980. foreach ($patterns as $pattern) {
  14981. if (preg_match($pattern, $prompt, $matches)) {
  14982. $number = trim($matches[1]);
  14983. // 如果是中文数字,转换为阿拉伯数字
  14984. if (isset($chineseNumbers[$number])) {
  14985. return $chineseNumbers[$number];
  14986. }
  14987. // 如果是阿拉伯数字,直接返回
  14988. if (is_numeric($number)) {
  14989. $episodeNum = intval($number);
  14990. // 合理性检查:集数应该在1-100之间
  14991. if ($episodeNum >= 1 && $episodeNum <= 100) {
  14992. return $episodeNum;
  14993. }
  14994. }
  14995. }
  14996. }
  14997. return null;
  14998. }
  14999. /**
  15000. * 调用火山引擎对话(Chat) API
  15001. *
  15002. * @param array $params 包含以下参数:
  15003. * - model: 模型ID(必填)
  15004. * - messages: 消息列表(必填)
  15005. * - stream: 是否流式输出(可选,默认false)
  15006. * - max_tokens: 最大输出token数(可选)
  15007. * - temperature: 采样温度(可选,默认1)
  15008. * - top_p: 核采样概率(可选,默认0.7)
  15009. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  15010. * - presence_penalty: 存在惩罚系数(可选,默认0)
  15011. * - stop: 停止词(可选)
  15012. * - tools: 工具列表(可选)
  15013. * @return array|Generator 非流式返回数组,流式返回生成器
  15014. */
  15015. public function volcEngineChatCompletion(array $params)
  15016. {
  15017. // 百度 GLM 已由 dispatchStreamByModel / dispatchChatOnlyByModel 统一分发,此处不再转发
  15018. $frontModel = getProp($params, 'model', '');
  15019. if (in_array($frontModel, $this->baidu_glm_text_models, true)) {
  15020. Utils::throwError('20003:百度GLM模型请使用统一分发方法dispatchStreamByModel/dispatchChatOnlyByModel调用');
  15021. }
  15022. $apiKey = env('VOLC_AI_API_KEY');
  15023. if (empty($apiKey)) {
  15024. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  15025. }
  15026. // 构建请求参数
  15027. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  15028. $requestData = [
  15029. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  15030. 'messages' => $params['messages'] ?? [],
  15031. ];
  15032. if (!in_array($originalModel, $this->valid_text_models)) {
  15033. Utils::throwError('20003:该模型不支持!');
  15034. }
  15035. // 添加可选参数
  15036. if (isset($params['stream'])) {
  15037. $requestData['stream'] = $params['stream'];
  15038. }
  15039. if (isset($params['stream_options'])) {
  15040. $requestData['stream_options'] = $params['stream_options'];
  15041. }
  15042. if (isset($params['max_tokens'])) {
  15043. $requestData['max_tokens'] = $params['max_tokens'];
  15044. }else if (isset($params['max_completion_tokens'])) {
  15045. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  15046. }else {
  15047. $requestData['max_completion_tokens'] = 100000;
  15048. }
  15049. if (isset($params['temperature'])) {
  15050. $requestData['temperature'] = $params['temperature'];
  15051. }
  15052. if (isset($params['top_p'])) {
  15053. $requestData['top_p'] = $params['top_p'];
  15054. }
  15055. if (isset($params['frequency_penalty'])) {
  15056. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  15057. }
  15058. if (isset($params['presence_penalty'])) {
  15059. $requestData['presence_penalty'] = $params['presence_penalty'];
  15060. }
  15061. if (isset($params['stop'])) {
  15062. $requestData['stop'] = $params['stop'];
  15063. }
  15064. if (isset($params['tools'])) {
  15065. $requestData['tools'] = $params['tools'];
  15066. }
  15067. if (isset($params['tool_choice'])) {
  15068. $requestData['tool_choice'] = $params['tool_choice'];
  15069. }
  15070. if (isset($params['response_format'])) {
  15071. $requestData['response_format'] = $params['response_format'];
  15072. }
  15073. if (isset($params['thinking'])) {
  15074. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  15075. if (is_array($params['thinking'])) {
  15076. $requestData['thinking'] = $params['thinking'];
  15077. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  15078. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15079. }
  15080. } else {
  15081. $requestData['thinking'] = ['type' => $params['thinking']];
  15082. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  15083. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15084. }
  15085. }
  15086. } else {
  15087. $requestData['thinking'] = ['type' => 'disabled'];
  15088. }
  15089. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  15090. $client = new Client(['verify' => false, 'timeout' => 1800]);
  15091. try {
  15092. // 判断是否为流式输出
  15093. $isStream = isset($params['stream']) && $params['stream'] === true;
  15094. if ($isStream) {
  15095. // 流式输出
  15096. // 流式请求默认声明返回 usage(未显式传参时)
  15097. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  15098. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  15099. } else {
  15100. // 非流式输出
  15101. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15102. 'headers' => [
  15103. 'Authorization' => 'Bearer ' . $apiKey,
  15104. 'Content-Type' => 'application/json',
  15105. ],
  15106. 'json' => $requestData
  15107. ]);
  15108. $responseData = json_decode($response->getBody(), true);
  15109. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  15110. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  15111. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  15112. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  15113. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  15114. }
  15115. return [
  15116. 'fullContent' => $fullContent,
  15117. 'fullReasoningContent' => $fullReasoningContent,
  15118. 'usage' => $usage
  15119. ];
  15120. }
  15121. } catch (\Exception $e) {
  15122. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  15123. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  15124. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  15125. }
  15126. }
  15127. /**
  15128. * 火山引擎对话API流式输出
  15129. *
  15130. * @param Client $client HTTP客户端
  15131. * @param string $apiKey API密钥
  15132. * @param array $requestData 请求数据
  15133. * @return Generator
  15134. */
  15135. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  15136. {
  15137. try {
  15138. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15139. 'headers' => [
  15140. 'Authorization' => 'Bearer ' . $apiKey,
  15141. 'Content-Type' => 'application/json',
  15142. ],
  15143. 'json' => $requestData,
  15144. 'stream' => true
  15145. ]);
  15146. $body = $response->getBody();
  15147. $buffer = '';
  15148. $fullContent = '';
  15149. $fullReasoningContent = '';
  15150. $usage = [];
  15151. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  15152. // 逐行读取流式响应
  15153. while (!$body->eof()) {
  15154. $chunk = $body->read(1024);
  15155. $buffer .= $chunk;
  15156. // 按行分割
  15157. $lines = explode("\n", $buffer);
  15158. $buffer = array_pop($lines);
  15159. foreach ($lines as $line) {
  15160. $line = trim($line);
  15161. if (empty($line)) {
  15162. continue;
  15163. }
  15164. // 检查是否是SSE数据行
  15165. if (strpos($line, 'data: ') !== 0) {
  15166. continue;
  15167. }
  15168. $data = substr($line, 6);
  15169. if ($data === '[DONE]') {
  15170. dLog('deepseek')->info('收到结束标记');
  15171. break 2;
  15172. }
  15173. try {
  15174. $json = json_decode($data, true);
  15175. if (json_last_error() !== JSON_ERROR_NONE) {
  15176. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  15177. continue;
  15178. }
  15179. if (isset($json['choices'][0]['delta'])) {
  15180. $delta = $json['choices'][0]['delta'];
  15181. // 处理思维链内容
  15182. if (isset($delta['reasoning_content'])) {
  15183. $fullReasoningContent .= $delta['reasoning_content'];
  15184. yield [
  15185. 'type' => 'reasoning',
  15186. 'content' => $delta['reasoning_content'],
  15187. 'full_reasoning' => $fullReasoningContent
  15188. ];
  15189. }
  15190. // 处理回答内容
  15191. if (isset($delta['content'])) {
  15192. $fullContent .= $delta['content'];
  15193. yield [
  15194. 'type' => 'content',
  15195. 'content' => $delta['content'],
  15196. ];
  15197. }
  15198. }
  15199. // 获取使用统计信息
  15200. if (isset($json['usage'])) {
  15201. $usage = $json['usage'];
  15202. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  15203. }
  15204. } catch (\Exception $e) {
  15205. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  15206. continue;
  15207. }
  15208. }
  15209. }
  15210. dLog('deepseek')->info('流式读取完成', [
  15211. 'content_length' => strlen($fullContent),
  15212. 'reasoning_length' => strlen($fullReasoningContent)
  15213. ]);
  15214. yield [
  15215. 'type' => 'done',
  15216. 'full_content' => $fullContent,
  15217. 'full_reasoning' => $fullReasoningContent,
  15218. 'usage' => $usage
  15219. ];
  15220. } catch (\Exception $e) {
  15221. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  15222. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  15223. throw $e;
  15224. }
  15225. }
  15226. /**
  15227. * 检查并创建图片生成任务
  15228. *
  15229. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  15230. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  15231. * @param string $nameKey 资源名称字段('role' 或 'scene')
  15232. * @param string $art_style 美术风格
  15233. * @return array 更新后的资源列表
  15234. */
  15235. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  15236. {
  15237. // 确保参数为数组
  15238. $merged_items = is_array($merged_items) ? $merged_items : [];
  15239. $global_items = is_array($global_items) ? $global_items : [];
  15240. // 构建全局资源映射表,用于快速查找
  15241. $global_map = [];
  15242. foreach ($global_items as $item) {
  15243. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  15244. if ($itemKey === '') {
  15245. continue;
  15246. }
  15247. $global_map[$itemKey] = $item;
  15248. }
  15249. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  15250. foreach ($merged_items as &$item) {
  15251. $item_name = getProp($item, $nameKey);
  15252. $item_description = getProp($item, 'description');
  15253. // $item_url = getProp($item, 'url');
  15254. // // 如果已有图片URL,跳过
  15255. // if (!empty($item_url)) {
  15256. // continue;
  15257. // }
  15258. // 如果是旁白角色,跳过
  15259. if ($nameKey === 'role' && $item_name === '旁白') {
  15260. continue;
  15261. }
  15262. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  15263. if ($itemKey === '') {
  15264. continue;
  15265. }
  15266. $need_create_task = false;
  15267. // 条件1:在全局资源中找不到匹配的名称
  15268. if (!isset($global_map[$itemKey])) {
  15269. $need_create_task = true;
  15270. } else {
  15271. // 条件2:名称匹配但描述或 pic_prompt 不一致
  15272. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  15273. $current_description = trim((string)$item_description);
  15274. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  15275. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  15276. // 如果 description 或 pic_prompt 有变化,需要重新生成
  15277. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  15278. $need_create_task = true;
  15279. }
  15280. }
  15281. // 如果需要创建任务,调用图片生成服务
  15282. if ($need_create_task) {
  15283. try {
  15284. // 优先使用 pic_prompt,如果没有则使用 description
  15285. $pic_prompt = getProp($item, 'pic_prompt');
  15286. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  15287. // 添加美术风格前缀
  15288. if ($art_style) {
  15289. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  15290. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  15291. $description = "{$prefix}:{$description}";
  15292. }
  15293. $params = [
  15294. 'prompt' => $description,
  15295. 'ref_img_urls' => []
  15296. ];
  15297. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  15298. $task_id = $task->id;
  15299. if ($task_id) {
  15300. $item['task_id'] = $task_id;
  15301. $item['task_status'] = 'processing';
  15302. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15303. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  15304. }
  15305. } catch (\Exception $e) {
  15306. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15307. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  15308. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  15309. // 不抛出异常,继续处理其他资源
  15310. }
  15311. }
  15312. }
  15313. return $merged_items;
  15314. }
  15315. /**
  15316. * 同步新出现的主体和场景到全局
  15317. *
  15318. * @param int $anime_id 动漫ID
  15319. * @param array $merged_roles 合并后的角色列表
  15320. * @param array $merged_scenes 合并后的场景列表
  15321. * @param array $global_roles 全局角色列表
  15322. * @param array $global_scenes 全局场景列表
  15323. * @return void
  15324. */
  15325. private function syncNewResourcesToGlobal(
  15326. int $anime_id,
  15327. array $merged_roles,
  15328. array $merged_scenes,
  15329. array $global_roles,
  15330. array $global_scenes
  15331. ): void {
  15332. // 构建全局角色映射表
  15333. $global_role_map = [];
  15334. foreach ($global_roles as $role) {
  15335. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  15336. if ($roleKey !== '') {
  15337. $global_role_map[$roleKey] = $role;
  15338. }
  15339. }
  15340. // 构建全局场景映射表
  15341. $global_scene_map = [];
  15342. foreach ($global_scenes as $scene) {
  15343. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  15344. if ($sceneKey !== '') {
  15345. $global_scene_map[$sceneKey] = $scene;
  15346. }
  15347. }
  15348. $need_update = false;
  15349. $new_global_roles = $global_roles;
  15350. $new_global_scenes = $global_scenes;
  15351. // 检查并添加新角色到全局
  15352. foreach ($merged_roles as $role) {
  15353. $role_name = getProp($role, 'role');
  15354. // 跳过旁白
  15355. if ($role_name === '旁白') {
  15356. continue;
  15357. }
  15358. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  15359. if ($roleKey === '') {
  15360. continue;
  15361. }
  15362. // 如果全局中不存在该角色,添加到全局
  15363. if (!isset($global_role_map[$roleKey])) {
  15364. $new_global_roles[] = [
  15365. 'role' => $role_name,
  15366. 'description' => getProp($role, 'description', ''),
  15367. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  15368. 'voice_name' => getProp($role, 'voice_name', ''),
  15369. 'voice_type' => getProp($role, 'voice_type', ''),
  15370. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  15371. 'url' => getProp($role, 'url', ''),
  15372. 'task_id' => getProp($role, 'task_id', ''),
  15373. 'task_status' => getProp($role, 'task_status', ''),
  15374. ];
  15375. $global_role_map[$roleKey] = true; // 标记已添加
  15376. $need_update = true;
  15377. dLog('deepseek')->info("新角色同步到全局", [
  15378. 'anime_id' => $anime_id,
  15379. 'role' => $role_name,
  15380. 'task_id' => getProp($role, 'task_id', ''),
  15381. ]);
  15382. }
  15383. // else {
  15384. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15385. // $global_role = $global_role_map[$roleKey];
  15386. // if (is_array($global_role)) {
  15387. // $updated = false;
  15388. // $update_fields = [];
  15389. // // 检查描述是否更新
  15390. // $current_description = trim((string)getProp($role, 'description'));
  15391. // $global_description = trim((string)getProp($global_role, 'description'));
  15392. // if ($current_description !== '' && $current_description !== $global_description) {
  15393. // $updated = true;
  15394. // $update_fields[] = 'description';
  15395. // }
  15396. // // 检查pic_prompt是否更新
  15397. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  15398. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  15399. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15400. // $updated = true;
  15401. // $update_fields[] = 'pic_prompt';
  15402. // }
  15403. // // 检查图片任务信息是否更新
  15404. // $current_task_id = getProp($role, 'task_id');
  15405. // $global_task_id = getProp($global_role, 'task_id');
  15406. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15407. // $updated = true;
  15408. // $update_fields[] = 'task_id';
  15409. // }
  15410. // // 如果有更新,同步到全局
  15411. // if ($updated) {
  15412. // foreach ($new_global_roles as &$global_role_item) {
  15413. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  15414. // if ($global_role_key === $roleKey) {
  15415. // if (in_array('description', $update_fields)) {
  15416. // $global_role_item['description'] = $current_description;
  15417. // }
  15418. // if (in_array('pic_prompt', $update_fields)) {
  15419. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  15420. // }
  15421. // if (in_array('task_id', $update_fields)) {
  15422. // $global_role_item['task_id'] = $current_task_id;
  15423. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  15424. // $global_role_item['url'] = getProp($role, 'url', '');
  15425. // }
  15426. // break;
  15427. // }
  15428. // }
  15429. // $need_update = true;
  15430. // dLog('deepseek')->info("角色信息更新到全局", [
  15431. // 'anime_id' => $anime_id,
  15432. // 'role' => $role_name,
  15433. // 'update_fields' => implode(',', $update_fields),
  15434. // ]);
  15435. // }
  15436. // }
  15437. // }
  15438. }
  15439. // 检查并添加新场景到全局
  15440. foreach ($merged_scenes as $scene) {
  15441. $scene_name = getProp($scene, 'scene');
  15442. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  15443. if ($sceneKey === '') {
  15444. continue;
  15445. }
  15446. // 如果全局中不存在该场景,添加到全局
  15447. if (!isset($global_scene_map[$sceneKey])) {
  15448. $new_global_scenes[] = [
  15449. 'scene' => $scene_name,
  15450. 'description' => getProp($scene, 'description', ''),
  15451. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  15452. 'url' => getProp($scene, 'url', ''),
  15453. 'task_id' => getProp($scene, 'task_id', ''),
  15454. 'task_status' => getProp($scene, 'task_status', ''),
  15455. ];
  15456. $global_scene_map[$sceneKey] = true; // 标记已添加
  15457. $need_update = true;
  15458. dLog('deepseek')->info("新场景同步到全局", [
  15459. 'anime_id' => $anime_id,
  15460. 'scene' => $scene_name,
  15461. 'task_id' => getProp($scene, 'task_id', ''),
  15462. ]);
  15463. }
  15464. // else {
  15465. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15466. // $global_scene = $global_scene_map[$sceneKey];
  15467. // if (is_array($global_scene)) {
  15468. // $updated = false;
  15469. // $update_fields = [];
  15470. // // 检查描述是否更新
  15471. // $current_description = trim((string)getProp($scene, 'description'));
  15472. // $global_description = trim((string)getProp($global_scene, 'description'));
  15473. // if ($current_description !== '' && $current_description !== $global_description) {
  15474. // $updated = true;
  15475. // $update_fields[] = 'description';
  15476. // }
  15477. // // 检查pic_prompt是否更新
  15478. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  15479. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  15480. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15481. // $updated = true;
  15482. // $update_fields[] = 'pic_prompt';
  15483. // }
  15484. // // 检查图片任务信息是否更新
  15485. // $current_task_id = getProp($scene, 'task_id');
  15486. // $global_task_id = getProp($global_scene, 'task_id');
  15487. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15488. // $updated = true;
  15489. // $update_fields[] = 'task_id';
  15490. // }
  15491. // // 如果有更新,同步到全局
  15492. // if ($updated) {
  15493. // foreach ($new_global_scenes as &$global_scene_item) {
  15494. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  15495. // if ($global_scene_key === $sceneKey) {
  15496. // if (in_array('description', $update_fields)) {
  15497. // $global_scene_item['description'] = $current_description;
  15498. // }
  15499. // if (in_array('pic_prompt', $update_fields)) {
  15500. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  15501. // }
  15502. // if (in_array('task_id', $update_fields)) {
  15503. // $global_scene_item['task_id'] = $current_task_id;
  15504. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  15505. // $global_scene_item['url'] = getProp($scene, 'url', '');
  15506. // }
  15507. // break;
  15508. // }
  15509. // }
  15510. // $need_update = true;
  15511. // dLog('deepseek')->info("场景信息更新到全局", [
  15512. // 'anime_id' => $anime_id,
  15513. // 'scene' => $scene_name,
  15514. // 'update_fields' => implode(',', $update_fields),
  15515. // ]);
  15516. // }
  15517. // }
  15518. // }
  15519. }
  15520. // 如果有新增或更新,更新数据库
  15521. if ($need_update) {
  15522. $update_data = [
  15523. 'roles' => json_encode($new_global_roles, 256),
  15524. 'scenes' => json_encode($new_global_scenes, 256),
  15525. 'updated_at' => date('Y-m-d H:i:s'),
  15526. ];
  15527. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  15528. if ($result !== false) {
  15529. dLog('deepseek')->info("全局角色和场景更新成功", [
  15530. 'anime_id' => $anime_id,
  15531. 'roles_count' => count($new_global_roles),
  15532. 'scenes_count' => count($new_global_scenes),
  15533. ]);
  15534. } else {
  15535. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  15536. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  15537. }
  15538. }
  15539. }
  15540. }