DeepSeekService.php 950 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464
  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. return $this->getArtStylePromptMappings($normalizedInput);
  2807. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2808. // foreach ($mapping['aliases'] as $alias) {
  2809. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2810. // if ($normalizedAlias === '') {
  2811. // continue;
  2812. // }
  2813. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2814. // return $mapping['prompt'];
  2815. // }
  2816. // }
  2817. // }
  2818. return '';
  2819. }
  2820. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2821. // 优先从画风表读取;character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2822. $row = DB::table('mp_art_styles')
  2823. ->where('art_style', $inputArtStyle)
  2824. ->where('is_deleted', 0)
  2825. ->first(['character_prefix', 'scene_prefix', 'prompt']);
  2826. if ($row) {
  2827. $prompt = (string)$row->prompt;
  2828. $result = [
  2829. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2830. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2831. ];
  2832. // 前缀与通用提示词均不存在时返回空数组
  2833. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2834. return [];
  2835. }
  2836. return $result;
  2837. }
  2838. $stylePrefixes = [
  2839. '唯美真人风格' => [
  2840. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2841. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2842. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2843. ],
  2844. '真人古风风格' => [
  2845. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2846. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2847. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2848. ],
  2849. '日系动漫风格' => [
  2850. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2851. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2852. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2853. ],
  2854. '国漫风格' => [
  2855. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2856. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2857. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2858. ],
  2859. 'Q版卡通风格' => [
  2860. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2861. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2862. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2863. ],
  2864. '简约扁平风格' => [
  2865. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2866. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2867. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2868. ],
  2869. '武侠风格' => [
  2870. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2871. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2872. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2873. ],
  2874. '古风仙侠风格' => [
  2875. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2876. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2877. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2878. ],
  2879. '新中式水墨风格' => [
  2880. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2881. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2882. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2883. ],
  2884. '写实插画风格' => [
  2885. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2886. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2887. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2888. ],
  2889. '3D卡通风格' => [
  2890. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2891. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2892. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2893. ],
  2894. '条漫风格' => [
  2895. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2896. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2897. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2898. ],
  2899. '赛博朋克风格' => [
  2900. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2901. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2902. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2903. ],
  2904. '暗黑悬疑风格' => [
  2905. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2906. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2907. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2908. ],
  2909. '治愈清新风格' => [
  2910. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2911. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2912. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2913. ]
  2914. ];
  2915. if (isset($stylePrefixes[$inputArtStyle])) {
  2916. $item = $stylePrefixes[$inputArtStyle];
  2917. $prompt = (string)($item['prompt'] ?? '');
  2918. // 前缀缺失时用通用 prompt 兜底
  2919. $result = [
  2920. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2921. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2922. ];
  2923. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2924. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2925. return [];
  2926. }
  2927. return $result;
  2928. }
  2929. return [];
  2930. }
  2931. private function normalizeArtStyleInput($value): string
  2932. {
  2933. $value = trim((string)$value);
  2934. if ($value === '') {
  2935. return '';
  2936. }
  2937. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2938. return mb_strtolower($value, 'UTF-8');
  2939. }
  2940. private function replaceArtStyleSection(string $content, string $artStyle): string
  2941. {
  2942. if ($content === '' || $artStyle === '') {
  2943. return $content;
  2944. }
  2945. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2946. if (!preg_match($pattern, $content)) {
  2947. return $content;
  2948. }
  2949. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2950. }
  2951. /**
  2952. * 解开模型偶发返回的 JSON 包装内容
  2953. *
  2954. * @param mixed $content 模型返回的原始内容
  2955. * @return mixed 解开后的内容(若无法解开则原样返回)
  2956. */
  2957. private function unwrapJsonWrappedContent($content) {
  2958. $trimmed = ltrim((string)$content);
  2959. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2960. return $content;
  2961. }
  2962. $decoded = json_decode($trimmed, true);
  2963. if (!is_array($decoded)) {
  2964. return $content;
  2965. }
  2966. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2967. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2968. return $decoded[$key];
  2969. }
  2970. }
  2971. return $content;
  2972. }
  2973. /**
  2974. * 流式文生文统一分发:根据模型路由到对应提供商的流式实现
  2975. *
  2976. * @param array $post_data 请求参数(含 model / messages / stream 等)
  2977. * @return \Generator
  2978. */
  2979. public function dispatchStreamByModel($post_data) {
  2980. // 强制按流式模式分发
  2981. $post_data['stream'] = true;
  2982. $model = (string)getProp($post_data, 'model', '');
  2983. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2984. // DeepSeek 官方模型
  2985. return $this->deepSeekStreamResponse($post_data);
  2986. } else if (in_array($model, $this->gpt_text_models)) {
  2987. // GPT 模型
  2988. return $this->gpt54StreamResponse($post_data);
  2989. } else if (in_array($model, $this->gemini_text_models)) {
  2990. // Gemini 模型
  2991. return $this->geminiStreamResponse($post_data, $model);
  2992. } else if (in_array($model, $this->baidu_glm_text_models)) {
  2993. // 百度 AI 网关 GLM 模型
  2994. return $this->baiduGLMStreamResponse($post_data);
  2995. } else if (in_array($model, $this->valid_text_models)) {
  2996. // 火山引擎等其他模型
  2997. return $this->volcEngineChatCompletion($post_data);
  2998. }
  2999. Utils::throwError('20003:不支持的模型: ' . $model);
  3000. }
  3001. /**
  3002. * 非流式文生文统一分发:根据模型路由到对应提供商的非流式实现
  3003. *
  3004. * @param array $post_data 请求参数(含 model / messages / stream 等)
  3005. * @return array
  3006. */
  3007. public function dispatchChatOnlyByModel($post_data) {
  3008. // 强制按非流式模式分发
  3009. $post_data['stream'] = false;
  3010. $model = (string)getProp($post_data, 'model', '');
  3011. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3012. // DeepSeek 官方模型
  3013. return $this->chatOnly($post_data);
  3014. } else if (in_array($model, $this->gpt_text_models)) {
  3015. // GPT 模型
  3016. return $this->gpt54ChatOnly($post_data);
  3017. } else if (in_array($model, $this->gemini_text_models)) {
  3018. // Gemini 模型
  3019. return $this->geminiChatOnly($post_data, $model);
  3020. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3021. // 百度 AI 网关 GLM 模型
  3022. return $this->baiduGLMChatOnly($post_data);
  3023. } else if (in_array($model, $this->valid_text_models)) {
  3024. // 火山引擎等其他模型
  3025. return $this->volcEngineChatCompletion($post_data);
  3026. }
  3027. Utils::throwError('20003:不支持的模型: ' . $model);
  3028. }
  3029. /**
  3030. * 百度 AI 网关 GLM 流式实现(OpenAI Chat Completions 协议)
  3031. *
  3032. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3033. * @return \Generator
  3034. */
  3035. private function baiduGLMStreamResponse($post_data) {
  3036. $payload = $this->buildBaiduGLMPayload($post_data, true);
  3037. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3038. try {
  3039. $response = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3040. 'json' => $payload,
  3041. 'headers' => $this->baiduGLMHeaders(),
  3042. 'stream' => true,
  3043. ]);
  3044. } catch (\Exception $e) {
  3045. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3046. dLog('deepseek')->error('百度GLM流式请求建立失败: ' . $e->getMessage(), [
  3047. 'payload' => $payload,
  3048. 'detail' => $errorDetail,
  3049. ]);
  3050. Utils::throwError('20003:百度GLM流式请求失败: ' . $errorDetail);
  3051. }
  3052. $body = $response->getBody();
  3053. $buffer = '';
  3054. $fullContent = '';
  3055. $fullReasoning = '';
  3056. $usage = [];
  3057. dLog('deepseek')->info('开始读取百度GLM流式响应');
  3058. try {
  3059. while (!$body->eof()) {
  3060. $chunk = $body->read(1024);
  3061. $buffer .= $chunk;
  3062. $lines = explode("\n", $buffer);
  3063. $buffer = array_pop($lines);
  3064. foreach ($lines as $line) {
  3065. $line = trim($line);
  3066. if (empty($line)) {
  3067. continue;
  3068. }
  3069. if (strpos($line, 'data: ') !== 0) {
  3070. dLog('deepseek')->warning('百度GLM非SSE数据行', ['line' => $line]);
  3071. continue;
  3072. }
  3073. $data = substr($line, 6);
  3074. if ($data === '[DONE]') {
  3075. dLog('deepseek')->info('百度GLM收到结束标记');
  3076. break 2;
  3077. }
  3078. try {
  3079. $json = json_decode($data, true);
  3080. if (json_last_error() !== JSON_ERROR_NONE) {
  3081. dLog('deepseek')->warning('百度GLM JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3082. continue;
  3083. }
  3084. if (isset($json['choices'][0]['delta'])) {
  3085. $delta = $json['choices'][0]['delta'];
  3086. // 思考链内容(兼容 reasoning_content / reasoning 两种字段)
  3087. $reasoningDelta = '';
  3088. if (isset($delta['reasoning_content']) && is_string($delta['reasoning_content'])) {
  3089. $reasoningDelta = $delta['reasoning_content'];
  3090. } elseif (isset($delta['reasoning']) && is_string($delta['reasoning'])) {
  3091. $reasoningDelta = $delta['reasoning'];
  3092. }
  3093. if ($reasoningDelta !== '') {
  3094. $fullReasoning .= $reasoningDelta;
  3095. yield [
  3096. 'type' => 'reasoning',
  3097. 'content' => $reasoningDelta,
  3098. 'full_reasoning' => $fullReasoning,
  3099. ];
  3100. }
  3101. // 正文内容
  3102. if (isset($delta['content']) && is_string($delta['content'])) {
  3103. $fullContent .= $delta['content'];
  3104. yield [
  3105. 'type' => 'content',
  3106. 'content' => $delta['content'],
  3107. ];
  3108. }
  3109. }
  3110. if (isset($json['usage'])) {
  3111. $usage = $json['usage'];
  3112. }
  3113. } catch (\Exception $e) {
  3114. dLog('deepseek')->error('百度GLM解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3115. continue;
  3116. }
  3117. }
  3118. }
  3119. } catch (\Exception $e) {
  3120. dLog('deepseek')->error('百度GLM流式读取中断: ' . $e->getMessage());
  3121. throw $e;
  3122. }
  3123. dLog('deepseek')->info('百度GLM流式读取完成', [
  3124. 'content_length' => strlen($fullContent),
  3125. 'reasoning_length' => strlen($fullReasoning),
  3126. ]);
  3127. yield [
  3128. 'type' => 'done',
  3129. 'full_content' => $fullContent,
  3130. 'full_reasoning' => $fullReasoning,
  3131. 'usage' => $usage,
  3132. ];
  3133. }
  3134. /**
  3135. * 百度 AI 网关 GLM 非流式实现(OpenAI Chat Completions 协议)
  3136. *
  3137. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3138. * @return array
  3139. */
  3140. private function baiduGLMChatOnly($post_data) {
  3141. $payload = $this->buildBaiduGLMPayload($post_data, false);
  3142. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3143. try {
  3144. $result = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3145. 'json' => $payload,
  3146. 'headers' => $this->baiduGLMHeaders(),
  3147. ]);
  3148. $response_arr = json_decode($result->getBody()->getContents(), true);
  3149. dLog('deepseek')->info('百度GLM非流式请求完成', ['response' => $response_arr]);
  3150. $fullContent = '';
  3151. $fullReasoningContent = '';
  3152. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  3153. if (isset($response_arr['choices'][0]['message'])) {
  3154. $message = $response_arr['choices'][0]['message'];
  3155. if (isset($message['content']) && is_string($message['content'])) {
  3156. $fullContent = $message['content'];
  3157. }
  3158. if (isset($message['reasoning_content']) && is_string($message['reasoning_content'])) {
  3159. $fullReasoningContent = $message['reasoning_content'];
  3160. } elseif (isset($message['reasoning']) && is_string($message['reasoning'])) {
  3161. $fullReasoningContent = $message['reasoning'];
  3162. }
  3163. }
  3164. return [
  3165. 'fullContent' => $fullContent,
  3166. 'fullReasoningContent' => $fullReasoningContent,
  3167. 'usage' => $usage,
  3168. ];
  3169. } catch (\Exception $e) {
  3170. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3171. dLog('deepseek')->error('百度GLM非流式请求失败: ' . $e->getMessage(), [
  3172. 'payload' => $payload,
  3173. 'detail' => $errorDetail,
  3174. ]);
  3175. Utils::throwError('20003:百度GLM请求失败: ' . $errorDetail);
  3176. }
  3177. }
  3178. /**
  3179. * 组装百度 AI 网关 GLM 请求参数
  3180. *
  3181. * @param array $data 请求参数
  3182. * @param bool $stream 是否流式
  3183. * @return array
  3184. */
  3185. private function buildBaiduGLMPayload(array $data, bool $stream): array
  3186. {
  3187. if (empty(env('BAIDU_GLM_AK'))) {
  3188. Utils::throwError('20003:百度GLM API Key未配置,请检查环境变量BAIDU_GLM_AK');
  3189. }
  3190. $frontModel = (string)getProp($data, 'model', '');
  3191. $externalModel = isset(BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel])
  3192. ? BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel]
  3193. : '';
  3194. if ($externalModel === '') {
  3195. Utils::throwError('20003:不支持的百度GLM模型: ' . $frontModel);
  3196. }
  3197. $messages = getProp($data, 'messages', []);
  3198. if (empty($messages)) {
  3199. Utils::throwError('20003:请提供有效的对话内容');
  3200. }
  3201. // OpenAI Chat Completions 标准参数白名单。
  3202. // 注意:thinking 不在白名单中,由下方按模型单独控制
  3203. // (glm-5.2 支持关闭思考,glm-5.3 强制思考、不接受 thinking 参数)。
  3204. $allowedKeys = [
  3205. 'temperature',
  3206. 'top_p',
  3207. 'max_tokens',
  3208. 'max_completion_tokens',
  3209. 'reasoning_effort',
  3210. 'frequency_penalty',
  3211. 'presence_penalty',
  3212. 'stop',
  3213. 'response_format',
  3214. 'stream_options',
  3215. 'tools',
  3216. 'tool_choice',
  3217. 'user',
  3218. 'seed',
  3219. ];
  3220. $payload = [
  3221. 'model' => $externalModel,
  3222. 'messages' => $messages,
  3223. 'stream' => $stream,
  3224. ];
  3225. foreach ($allowedKeys as $key) {
  3226. if (array_key_exists($key, $data) && $data[$key] !== null && $data[$key] !== '') {
  3227. $payload[$key] = $data[$key];
  3228. }
  3229. }
  3230. // ================= 思考模式策略(仅百度 GLM)=================
  3231. // 规则:调用方传了的参数以其为准,未传则按模型默认策略补齐。
  3232. // glm-5.2:支持关闭思考,默认关闭(thinking.disabled),可显著缩短响应时间
  3233. // glm-5.3:强制思考,网关不接受 thinking 参数(传 disabled 会返回 400),
  3234. // 因此统一不下发 thinking,只下发 reasoning_effort,默认 low
  3235. $validEfforts = ['low', 'high', 'max'];
  3236. // 调用方传入的 thinking(兼容 'enabled' 字符串与 ['type' => 'enabled'] 数组两种写法)
  3237. $inputThinking = null;
  3238. if (array_key_exists('thinking', $data)) {
  3239. $rawThinking = $data['thinking'];
  3240. if (is_array($rawThinking)) {
  3241. $rawThinking = getProp($rawThinking, 'type', null);
  3242. }
  3243. if (in_array($rawThinking, ['enabled', 'disabled'], true)) {
  3244. $inputThinking = $rawThinking;
  3245. }
  3246. }
  3247. // 调用方传入的思考强度;百度网关只接受 low / high / max,其它取值(如 none)视为未传
  3248. $inputEffort = null;
  3249. if (isset($payload['reasoning_effort']) && in_array($payload['reasoning_effort'], $validEfforts, true)) {
  3250. $inputEffort = $payload['reasoning_effort'];
  3251. }
  3252. unset($payload['reasoning_effort']);
  3253. if ($externalModel === 'glm-5.3') {
  3254. // glm-5.3 始终思考:即使传入 disabled(或未传)也强制走 reasoning_effort
  3255. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3256. } else {
  3257. // glm-5.2 支持关闭思考:未显式开启思考时默认关闭
  3258. $thinkingType = ($inputThinking === 'enabled') ? 'enabled' : 'disabled';
  3259. $payload['thinking'] = ['type' => $thinkingType];
  3260. if ($thinkingType === 'enabled') {
  3261. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3262. }
  3263. }
  3264. if ($stream && !isset($payload['stream_options'])) {
  3265. $payload['stream_options'] = ['include_usage' => true];
  3266. }
  3267. if (!isset($payload['max_tokens']) && !isset($payload['max_completion_tokens'])) {
  3268. // GLM-5.x 输出上限较高,给长文生成留足空间
  3269. $payload['max_tokens'] = 100000;
  3270. }
  3271. return $payload;
  3272. }
  3273. /**
  3274. * 百度 AI 网关 GLM 鉴权请求头
  3275. *
  3276. * @return array
  3277. */
  3278. private function baiduGLMHeaders(): array
  3279. {
  3280. return [
  3281. 'Authorization' => 'Bearer ' . env('BAIDU_GLM_AK'),
  3282. 'Content-Type' => 'application/json; charset=UTF-8',
  3283. 'Accept' => 'text/event-stream',
  3284. ];
  3285. }
  3286. /**
  3287. * 从 Guzzle 异常响应体中提取百度 AI 网关返回的错误信息
  3288. *
  3289. * @param \Exception $e
  3290. * @return string
  3291. */
  3292. private function extractBaiduGLMErrorDetail(\Exception $e): string
  3293. {
  3294. $detail = $e->getMessage();
  3295. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3296. try {
  3297. $responseBody = (string)$e->getResponse()->getBody();
  3298. $decoded = json_decode($responseBody, true);
  3299. if (is_array($decoded)) {
  3300. if (isset($decoded['error']['message']) && $decoded['error']['message'] !== '') {
  3301. $detail = $decoded['error']['message'];
  3302. } elseif (isset($decoded['message']) && $decoded['message'] !== '') {
  3303. $detail = $decoded['message'];
  3304. } elseif (isset($decoded['error']) && is_string($decoded['error'])) {
  3305. $detail = $decoded['error'];
  3306. }
  3307. } elseif ($responseBody !== '') {
  3308. $detail = $responseBody;
  3309. }
  3310. } catch (\Throwable $parseError) {
  3311. // 保留原始异常信息
  3312. }
  3313. }
  3314. return mb_substr($detail, 0, 500);
  3315. }
  3316. private function deepSeekStreamResponse($post_data) {
  3317. // 设置最大输出tokens
  3318. $post_data['max_tokens'] = 300000;
  3319. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3320. $post_data['stream_options'] = ['include_usage' => true];
  3321. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3322. $response = $client->post($this->url, [
  3323. 'json' => $post_data,
  3324. 'headers' => $this->headers,
  3325. 'stream' => true // 启用流式响应
  3326. ]);
  3327. $body = $response->getBody();
  3328. $fullContent = '';
  3329. $fullReasoningContent = '';
  3330. $usage = [];
  3331. $buffer = '';
  3332. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  3333. // 逐行读取流式响应
  3334. while (!$body->eof()) {
  3335. $chunk = $body->read(1024); // 每次读取 1KB
  3336. $buffer .= $chunk;
  3337. // 按行分割
  3338. $lines = explode("\n", $buffer);
  3339. // 保留最后一个不完整的行
  3340. $buffer = array_pop($lines);
  3341. foreach ($lines as $line) {
  3342. $line = trim($line);
  3343. // 跳过空行
  3344. if (empty($line)) {
  3345. continue;
  3346. }
  3347. // 检查是否是 SSE 数据行
  3348. if (strpos($line, 'data: ') !== 0) {
  3349. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3350. continue;
  3351. }
  3352. $data = substr($line, 6); // 移除 "data: " 前缀
  3353. if ($data === '[DONE]') {
  3354. dLog('deepseek')->info('收到结束标记');
  3355. break 2; // 跳出两层循环
  3356. }
  3357. try {
  3358. $json = json_decode($data, true);
  3359. if (json_last_error() !== JSON_ERROR_NONE) {
  3360. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3361. continue;
  3362. }
  3363. if (isset($json['choices'][0]['delta'])) {
  3364. $delta = $json['choices'][0]['delta'];
  3365. // 处理思维链内容(仅 deepseek-reasoner 模型)
  3366. if (isset($delta['reasoning_content'])) {
  3367. $fullReasoningContent .= $delta['reasoning_content'];
  3368. yield [
  3369. 'type' => 'reasoning',
  3370. 'content' => $delta['reasoning_content'],
  3371. 'full_reasoning' => $fullReasoningContent
  3372. ];
  3373. }
  3374. // 处理最终回答内容
  3375. if (isset($delta['content'])) {
  3376. $fullContent .= $delta['content'];
  3377. yield [
  3378. 'type' => 'content',
  3379. 'content' => $delta['content'],
  3380. ];
  3381. }
  3382. }
  3383. // 获取使用统计信息
  3384. if (isset($json['usage'])) {
  3385. $usage = $json['usage'];
  3386. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3387. }
  3388. } catch (\Exception $e) {
  3389. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3390. continue;
  3391. }
  3392. }
  3393. }
  3394. dLog('deepseek')->info('流式读取完成', [
  3395. 'content_length' => strlen($fullContent),
  3396. 'reasoning_length' => strlen($fullReasoningContent)
  3397. ]);
  3398. yield [
  3399. 'type' => 'done',
  3400. 'full_content' => $fullContent,
  3401. 'full_reasoning' => $fullReasoningContent,
  3402. 'usage' => $usage
  3403. ];
  3404. }
  3405. /**
  3406. * GPT 重试次数(env 可配置,默认 5 次)
  3407. */
  3408. private function gptRetryTimes()
  3409. {
  3410. return (int)env('GPT_RETRY_TIMES', 5);
  3411. }
  3412. /**
  3413. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  3414. */
  3415. private function gptRetryInterval()
  3416. {
  3417. return (int)env('GPT_RETRY_INTERVAL', 10);
  3418. }
  3419. /**
  3420. * 判断 GPT 请求异常是否可重试
  3421. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  3422. */
  3423. private function isGptRetryableException(\Exception $e)
  3424. {
  3425. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  3426. return false;
  3427. }
  3428. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3429. $status = $e->getResponse()->getStatusCode();
  3430. return $status >= 500 || $status == 429;
  3431. }
  3432. return true;
  3433. }
  3434. /**
  3435. * GPT 中转站探活:GET /v1/models,5 秒短超时
  3436. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  3437. */
  3438. private function checkGptServiceAvailable($apiKey = null)
  3439. {
  3440. if ($apiKey === null) {
  3441. $apiKey = env('GPT_54_API_KEY');
  3442. }
  3443. if (empty($apiKey)) {
  3444. return false;
  3445. }
  3446. try {
  3447. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  3448. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  3449. 'headers' => [
  3450. 'Authorization' => 'Bearer ' . $apiKey,
  3451. 'Content-Type' => 'application/json'
  3452. ]
  3453. ]);
  3454. $status = $response->getStatusCode();
  3455. return $status < 500 && $status != 429;
  3456. } catch (\Exception $e) {
  3457. return false;
  3458. }
  3459. }
  3460. /**
  3461. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  3462. * 全部失败抛出友好错误
  3463. */
  3464. private function ensureGptServiceAvailable($apiKey = null)
  3465. {
  3466. $maxRetries = $this->gptRetryTimes();
  3467. $interval = $this->gptRetryInterval();
  3468. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  3469. if ($this->checkGptServiceAvailable($apiKey)) {
  3470. return;
  3471. }
  3472. if ($attempt < $maxRetries) {
  3473. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  3474. 'retry' => $attempt + 1,
  3475. 'max_retries' => $maxRetries
  3476. ]);
  3477. sleep($interval);
  3478. }
  3479. }
  3480. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  3481. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  3482. 'max_retries' => $maxRetries,
  3483. 'interval' => $interval
  3484. ]);
  3485. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  3486. }
  3487. /**
  3488. * GPT 流式输出处理方法
  3489. *
  3490. * @param array $post_data GPT API请求参数
  3491. * @return \Generator 返回生成器,用于流式输出
  3492. */
  3493. private function gpt54StreamResponse($post_data) {
  3494. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  3495. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  3496. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  3497. if ($modelName === 'gpt-5.4') {
  3498. $modelName = 'gpt-5.6-terra';
  3499. $post_data['model'] = $modelName;
  3500. }
  3501. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  3502. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  3503. $usedLunaFallback = false;
  3504. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  3505. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  3506. if (empty($apiKey)) {
  3507. Utils::throwError('20003:GPT API Key未配置');
  3508. }
  3509. // 先探活,服务不可用时自动重试
  3510. $this->ensureGptServiceAvailable($apiKey);
  3511. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  3512. // 移除 thinking 参数,GPT-5.4 不支持
  3513. if (isset($post_data['thinking'])) {
  3514. unset($post_data['thinking']);
  3515. }
  3516. if (isset($post_data['reasoning_effort'])) {
  3517. unset($post_data['reasoning_effort']);
  3518. }
  3519. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  3520. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  3521. $post_data['max_completion_tokens'] = 100000;
  3522. // GPT-5.x 上游仅支持 max_completion_tokens,同时携带 max_tokens 会返回 400:
  3523. // Unsupported parameter: 'max_tokens' is not supported with this model.
  3524. // 这里显式移除,防止调用方在 post_data 中残留 max_tokens。
  3525. unset($post_data['max_tokens']);
  3526. // GPT-5.x(推理型上游)不接受 frequency_penalty / presence_penalty:
  3527. // Unsupported parameter: 'frequency_penalty' is not supported with this model.
  3528. // 调用方默认传 0,移除后采样行为不变,显式清理避免 400。
  3529. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  3530. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3531. $post_data['stream_options'] = ['include_usage' => true];
  3532. $maxRetries = $this->gptRetryTimes();
  3533. $interval = $this->gptRetryInterval();
  3534. $attempt = 0;
  3535. while (true) {
  3536. $fullContent = '';
  3537. $usage = [];
  3538. $buffer = '';
  3539. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  3540. $isJsonRequest = isset($post_data['response_format'])
  3541. && is_array($post_data['response_format'])
  3542. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  3543. $suspectJsonWrap = false;
  3544. $pendingContent = '';
  3545. $requestStartedAt = microtime(true);
  3546. $headers = [
  3547. 'Authorization' => 'Bearer ' . $apiKey,
  3548. 'Content-Type' => 'application/json',
  3549. 'Accept' => 'text/event-stream'
  3550. ];
  3551. try {
  3552. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  3553. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  3554. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  3555. 'json' => $post_data,
  3556. 'headers' => $headers,
  3557. 'stream' => true // 启用流式响应
  3558. ]);
  3559. $body = $response->getBody();
  3560. dLog('deepseek')->info('开始读取 GPT 流式响应');
  3561. // 逐行读取流式响应
  3562. while (!$body->eof()) {
  3563. // 长时间没有任何内容返回时,切换备用 Key 重试
  3564. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3565. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3566. }
  3567. $chunk = $body->read(1024); // 每次读取 1KB
  3568. $buffer .= $chunk;
  3569. // 按行分割
  3570. $lines = explode("\n", $buffer);
  3571. // 保留最后一个不完整的行
  3572. $buffer = array_pop($lines);
  3573. foreach ($lines as $line) {
  3574. $line = trim($line);
  3575. // 跳过空行
  3576. if (empty($line)) {
  3577. continue;
  3578. }
  3579. // 检查是否是 SSE 数据行
  3580. if (strpos($line, 'data: ') !== 0) {
  3581. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3582. continue;
  3583. }
  3584. $data = substr($line, 6); // 移除 "data: " 前缀
  3585. if ($data === '[DONE]') {
  3586. dLog('deepseek')->info('收到结束标记');
  3587. break 2; // 跳出 foreach 和流读取循环
  3588. }
  3589. try {
  3590. $json = json_decode($data, true);
  3591. if (json_last_error() !== JSON_ERROR_NONE) {
  3592. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3593. continue;
  3594. }
  3595. if (isset($json['choices'][0]['delta'])) {
  3596. $delta = $json['choices'][0]['delta'];
  3597. // 处理回答内容
  3598. if (isset($delta['content'])) {
  3599. $fullContent .= $delta['content'];
  3600. $trimmed = ltrim($fullContent);
  3601. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3602. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3603. $suspectJsonWrap = true;
  3604. }
  3605. if (!$suspectJsonWrap) {
  3606. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3607. $chunkSize = 256;
  3608. $chunkLength = mb_strlen($delta['content']);
  3609. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3610. yield [
  3611. 'type' => 'content',
  3612. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3613. ];
  3614. }
  3615. } else {
  3616. $pendingContent .= $delta['content'];
  3617. }
  3618. }
  3619. }
  3620. // 获取使用统计信息
  3621. if (isset($json['usage'])) {
  3622. $usage = $json['usage'];
  3623. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3624. }
  3625. } catch (\Exception $e) {
  3626. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3627. continue;
  3628. }
  3629. }
  3630. }
  3631. dLog('deepseek')->info('流式读取完成', [
  3632. 'content_length' => strlen($fullContent)
  3633. ]);
  3634. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3635. if ($suspectJsonWrap) {
  3636. $decoded = json_decode(trim($fullContent), true);
  3637. $unwrapped = null;
  3638. if (is_array($decoded)) {
  3639. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3640. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3641. $unwrapped = $decoded[$key];
  3642. break;
  3643. }
  3644. }
  3645. }
  3646. if ($unwrapped !== null) {
  3647. $fullContent = $unwrapped;
  3648. $chunkSize = 256;
  3649. $contentLength = mb_strlen($fullContent);
  3650. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3651. yield [
  3652. 'type' => 'content',
  3653. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3654. ];
  3655. }
  3656. } elseif ($pendingContent !== '') {
  3657. // 误判:补发暂缓内容,避免内容丢失
  3658. yield [
  3659. 'type' => 'content',
  3660. 'content' => $pendingContent,
  3661. ];
  3662. }
  3663. }
  3664. yield [
  3665. 'type' => 'done',
  3666. 'full_content' => $fullContent,
  3667. 'full_reasoning' => '',
  3668. 'usage' => $usage
  3669. ];
  3670. return;
  3671. } catch (\Exception $e) {
  3672. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3673. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3674. $usedLunaFallback = true;
  3675. $apiKey = $lunaApiKey;
  3676. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3677. continue;
  3678. }
  3679. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3680. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3681. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3682. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3683. throw $e;
  3684. }
  3685. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3686. 'retry' => $attempt + 1,
  3687. 'max_retries' => $maxRetries,
  3688. 'error' => $e->getMessage()
  3689. ]);
  3690. sleep($interval);
  3691. $attempt++;
  3692. }
  3693. }
  3694. }
  3695. // 与推理模型对话
  3696. public function chatWithReasoner($data) {
  3697. // 文生文计费预检(normal 档)
  3698. $uid = Site::getUid();
  3699. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  3700. $content = getProp($data, 'content');
  3701. $model = getProp($data, 'model', 'r1');
  3702. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3703. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3704. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3705. if ($model == 'r1') {
  3706. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3707. $thinkingMode = 'disabled';
  3708. } else {
  3709. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3710. $thinkingMode = 'disabled';
  3711. }
  3712. // 获取可选情感(根据音色可支持情感选)
  3713. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3714. $emotion_list = [];
  3715. foreach ($timbre_emotion as $emotion) {
  3716. $tmp = explode(',', $emotion);
  3717. $emotion_list = array_merge($emotion_list, $tmp);
  3718. }
  3719. $emotion_list = array_unique($emotion_list);
  3720. $emotion_str = implode('、', $emotion_list);
  3721. // // 获取可选情感
  3722. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3723. // $emotion_str = implode('、', $emotion_list);
  3724. // 是否启用情感
  3725. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3726. if ($enable_emotion) {
  3727. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3728. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3729. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3730. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3731. }else {
  3732. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3733. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3734. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3735. }
  3736. $messages = [
  3737. [
  3738. 'role' => 'system',
  3739. 'content' => $sys_content
  3740. ],
  3741. [
  3742. 'role' => 'user',
  3743. 'content' => $content
  3744. ]
  3745. ];
  3746. $post_data = [
  3747. 'model' => $model,
  3748. 'messages' => $messages,
  3749. // 'max_tokens' => 8192,
  3750. 'temperature' => 1,
  3751. 'frequency_penalty' => 0,
  3752. 'presence_penalty' => 0,
  3753. 'thinking' => ['type' => $thinkingMode],
  3754. 'response_format' => [
  3755. 'type' => 'text'
  3756. ],
  3757. 'stream' => false
  3758. ];
  3759. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3760. // 根据模型类型选择调用方法
  3761. $fullContent = '';
  3762. $usage = [];
  3763. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  3764. if (is_array($chatResult)) {
  3765. $fullContent = $chatResult['fullContent'];
  3766. $usage = $chatResult['usage'];
  3767. }
  3768. // 处理获取到的剧本数据
  3769. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3770. $result = [
  3771. 'origin_content' => $fullContent,
  3772. 'roles' => getProp($script_content, 'roles'),
  3773. 'words' => getProp($script_content, 'words'),
  3774. ];
  3775. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  3776. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3777. 'model' => $model,
  3778. 'source' => 'chatWithReasoner',
  3779. ], 'normal');
  3780. return $result;
  3781. }
  3782. public function resetParagraphAudio($data) {
  3783. $bid = getProp($data, 'bid');
  3784. $cid = getProp($data, 'cid');
  3785. $version_id = getProp($data, 'version_id');
  3786. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3787. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3788. 'generate_status' => '待制作',
  3789. 'updated_at' => date('Y-m-d H:i:s')
  3790. ]);
  3791. }
  3792. public function saveParagraphAudio($data) {
  3793. $bid = getProp($data, 'bid');
  3794. $cid = getProp($data, 'cid');
  3795. $version_id = getProp($data, 'version_id');
  3796. $sequence = getProp($data, 'sequence');
  3797. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3798. // 获取所有情感
  3799. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3800. $emotion_list = array_flip($emotion_list);
  3801. // 获取音色支持情感
  3802. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3803. $timbre_emotion = explode(',', $timbre_emotion);
  3804. $emotion = getProp($data, 'emotion');
  3805. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3806. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3807. $list = [
  3808. 'bid' => $bid,
  3809. 'cid' => $cid,
  3810. 'version_id' => $version_id,
  3811. 'sequence' => $sequence,
  3812. 'role' => getProp($data, 'role'),
  3813. 'gender' => getProp($data, 'gender'),
  3814. 'text' => trim(getProp($data, 'text')),
  3815. 'emotion' => $emotion,
  3816. 'emotion_type' => $emotion_type,
  3817. 'voice_type' => getProp($data, 'voice_type'),
  3818. 'voice_name' => getProp($data, 'voice_name'),
  3819. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3820. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3821. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3822. 'pitch' => getProp($data, 'pitch', 0),
  3823. // 'paragraph_audio_url' => '',
  3824. 'generate_status' => '制作中',
  3825. 'error_msg' => '',
  3826. 'updated_at' => date('Y-m-d H:i:s')
  3827. ];
  3828. $continue = false;
  3829. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3830. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3831. $list['generate_status'] = '制作成功';
  3832. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3833. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3834. $continue = true;
  3835. }
  3836. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3837. if ($id) {
  3838. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3839. }else {
  3840. $list['created_at'] = date('Y-m-d H:i:s');
  3841. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3842. $boolen = $id ? true : false;
  3843. }
  3844. // 如果更新成功则加入查询队列
  3845. if ($boolen) {
  3846. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3847. Redis::sadd($redis_key, $id);
  3848. }
  3849. if ($boolen && !$continue) {
  3850. $boolen = false;
  3851. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3852. // 根据ID通过API通知合成音频
  3853. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3854. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3855. $response = $result->getBody()->getContents();
  3856. $response_arr = json_decode($response, true);
  3857. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3858. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3859. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3860. Utils::throwError('20003:通知火山生成段落音频失败');
  3861. }
  3862. $boolen = true;
  3863. }
  3864. return $boolen;
  3865. }
  3866. public function insertAudioEffect($data) {
  3867. $audio_id = getProp($data, 'audio_id');
  3868. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3869. $bid = getProp($chapter_audio, 'bid');
  3870. $version_id = getProp($chapter_audio, 'version_id');
  3871. $cid = getProp($chapter_audio, 'cid');
  3872. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3873. $audio_effect_json = getProp($data, 'audio_effect_json');
  3874. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3875. try {
  3876. DB::beginTransaction();
  3877. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3878. if (!$count) {
  3879. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3880. }else {
  3881. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3882. }
  3883. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3884. 'audio_effect_status' => '添加中',
  3885. 'audio_effect_json' => $audio_effect_json,
  3886. 'updated_at' => date('Y-m-d H:i:s')
  3887. ]);
  3888. if (!$boolen1) {
  3889. DB::rollBack();
  3890. Utils::throwError('20003:更新生成数据失败');
  3891. }
  3892. $id = DB::table('mp_audio_tasks')->insertGetId([
  3893. 'audio_id' => $audio_id,
  3894. 'generate_status' => '执行中',
  3895. 'generate_json' => json_encode([], 256),
  3896. 'bid' => $bid,
  3897. 'book_name' => getProp($chapter_audio, 'book_name'),
  3898. 'version_id' => $version_id,
  3899. 'version_name' => getProp($chapter_audio, 'version_name'),
  3900. 'cid' => $cid,
  3901. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3902. 'task_name' => $task_name,
  3903. 'created_at' => date('Y-m-d H:i:s'),
  3904. 'updated_at' => date('Y-m-d H:i:s')
  3905. ]);
  3906. if (!$id) {
  3907. DB::rollBack();
  3908. Utils::throwError('20003:创建任务失败');
  3909. }
  3910. }catch (\Exception $e) {
  3911. DB::rollBack();
  3912. Utils::throwError('20003:'.$e->getMessage());
  3913. }
  3914. DB::commit();
  3915. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3916. // 根据ID通过API通知合成音频
  3917. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3918. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3919. $response = $result->getBody()->getContents();
  3920. $response_arr = json_decode($response, true);
  3921. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3922. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3923. Log::info('通知火山插入音效失败: '.$error_msg);
  3924. Utils::throwError('20003:通知火山插入音效失败');
  3925. }
  3926. return true;
  3927. }
  3928. public function insertBgm($data) {
  3929. $audio_id = getProp($data, 'audio_id');
  3930. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3931. $bid = getProp($chapter_audio, 'bid');
  3932. $version_id = getProp($chapter_audio, 'version_id');
  3933. $cid = getProp($chapter_audio, 'cid');
  3934. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3935. $bgm_json = getProp($data, 'bgm_json');
  3936. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3937. if (!$bgm_json) {
  3938. $bgm_json = getProp($data, 'audio_effect_json');
  3939. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3940. }
  3941. try {
  3942. DB::beginTransaction();
  3943. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3944. if (!$count) {
  3945. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3946. }else {
  3947. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3948. }
  3949. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3950. 'bgm_status' => '添加中',
  3951. 'bgm_json' => $bgm_json,
  3952. 'updated_at' => date('Y-m-d H:i:s')
  3953. ]);
  3954. if (!$boolen1) {
  3955. DB::rollBack();
  3956. Utils::throwError('20003:更新生成数据失败');
  3957. }
  3958. $id = DB::table('mp_audio_tasks')->insertGetId([
  3959. 'audio_id' => $audio_id,
  3960. 'generate_status' => '执行中',
  3961. 'generate_json' => json_encode([], 256),
  3962. 'bid' => $bid,
  3963. 'book_name' => getProp($chapter_audio, 'book_name'),
  3964. 'version_id' => $version_id,
  3965. 'version_name' => getProp($chapter_audio, 'version_name'),
  3966. 'cid' => $cid,
  3967. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3968. 'task_name' => $task_name,
  3969. 'created_at' => date('Y-m-d H:i:s'),
  3970. 'updated_at' => date('Y-m-d H:i:s')
  3971. ]);
  3972. if (!$id) {
  3973. DB::rollBack();
  3974. Utils::throwError('20003:创建任务失败');
  3975. }
  3976. }catch (\Exception $e) {
  3977. DB::rollBack();
  3978. Utils::throwError('20003:'.$e->getMessage());
  3979. }
  3980. DB::commit();
  3981. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3982. // 根据ID通过API通知合成音频
  3983. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3984. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3985. $response = $result->getBody()->getContents();
  3986. $response_arr = json_decode($response, true);
  3987. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3988. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3989. Log::info('通知火山插入bgm失败: '.$error_msg);
  3990. Utils::throwError('20003:通知火山插入bgm失败');
  3991. }
  3992. return true;
  3993. }
  3994. public function getParagraphAudios($data) {
  3995. $bid = getProp($data, 'bid');
  3996. $cid = getProp($data, 'cid');
  3997. $version_id = getProp($data, 'version_id');
  3998. $sequence = getProp($data, 'sequence');
  3999. // 获取已生成的音频
  4000. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  4001. if ($sequence) $query->where('sequence', $sequence);
  4002. $paragraph_audios = $query->orderBy('sequence')->get();
  4003. $result = [];
  4004. foreach($paragraph_audios as $item) {
  4005. $result[] = [
  4006. 'sequence' => getProp($item, 'sequence'),
  4007. 'role' => getProp($item, 'role'),
  4008. 'gender' => getProp($item, 'gender'),
  4009. 'text' => trim(getProp($item, 'text')),
  4010. 'emotion' => getProp($item, 'emotion'),
  4011. 'emotion_type' => getProp($item, 'emotion_type'),
  4012. 'voice_type' => getProp($item, 'voice_type'),
  4013. 'voice_name' => getProp($item, 'voice_name'),
  4014. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4015. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4016. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4017. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4018. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  4019. ];
  4020. }
  4021. return $result;
  4022. }
  4023. // 新增合成任务
  4024. public function addGenerateTask($data) {
  4025. $bid = getProp($data, 'bid');
  4026. $cid = getProp($data, 'cid');
  4027. $version_id = getProp($data, 'version_id');
  4028. $generate_json = getProp($data, 'generate_json');
  4029. // 获取已生成的音频
  4030. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  4031. $paragraph_list = [];
  4032. foreach($paragraph_audios as $item) {
  4033. $paragraph_list[getProp($item, 'sequence')] = [
  4034. 'role' => getProp($item, 'role'),
  4035. 'gender' => getProp($item, 'gender'),
  4036. 'text' => trim(getProp($item, 'text')),
  4037. 'emotion' => getProp($item, 'emotion'),
  4038. 'emotion_type' => getProp($item, 'emotion_type'),
  4039. 'voice_type' => getProp($item, 'voice_type'),
  4040. 'voice_name' => getProp($item, 'voice_name'),
  4041. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4042. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4043. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4044. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4045. ];
  4046. }
  4047. // 更新角色-音色信息
  4048. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  4049. $existed_role_info = json_decode($existed_role_info, true);
  4050. if (!$existed_role_info) $existed_role_info = [];
  4051. // 获取情感信息
  4052. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4053. $emotion_list = array_flip($emotion_list);
  4054. // 获取音色对应情感组
  4055. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  4056. $timbre_emotion_list = [];
  4057. foreach($timbre_emotions as $item) {
  4058. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  4059. }
  4060. // 构造生成音频的json
  4061. $words = json_decode($generate_json, true);
  4062. // 最终合成前的参数组
  4063. $mp_chapter_paragraph_audios = [];
  4064. $sequence = 1;
  4065. $complete_paragraph_sequences = [];
  4066. foreach($words as &$word) {
  4067. 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:参数格式有误');
  4068. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  4069. $role = getProp($word, 'role');
  4070. $word['gender'] = (int)$word['gender'];
  4071. // 判断音色对应情感是否支持,不支持则调整为中性
  4072. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  4073. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  4074. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  4075. if (isset($emotion_list[getProp($word, 'emotion')])) {
  4076. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  4077. }else {
  4078. $word['emotion'] = '中性';
  4079. $word['emotion_type'] = 'neutral';
  4080. }
  4081. $existed_role_info[$role] = [
  4082. 'timbre_type' => $word['voice_type'],
  4083. 'timbre_name' => $word['voice_name'],
  4084. 'emotion' => $word['emotion'],
  4085. 'emotion_type' => $word['emotion_type'],
  4086. 'speed_ratio' => $word['speed_ratio'],
  4087. 'loudness_ratio'=> $word['loudness_ratio'],
  4088. 'emotion_scale' => $word['emotion_scale'],
  4089. 'pitch' => $word['pitch']
  4090. ];
  4091. $word['paragraph_audio_url'] = '';
  4092. // 判断生成参数是否相同,相同则直接使用已生成的音频
  4093. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  4094. // 如果音频存在并且参数都未改变则使用已生成的音频
  4095. if (getProp($paragraph, 'paragraph_audio_url')) {
  4096. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  4097. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  4098. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  4099. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  4100. // {
  4101. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4102. // }
  4103. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4104. }
  4105. $tmp = $word;
  4106. // 组装章节分句音频数据
  4107. // $tmp['sequence'] = getProp($word, 'sequence');
  4108. // $tmp['text'] = getProp($word, 'text');
  4109. // $tmp['emotion'] = getProp($word, 'emotion');
  4110. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  4111. // $tmp['voice_name'] = getProp($word, 'voice_name');
  4112. // $tmp['voice_type'] = getProp($word, 'voice_type');
  4113. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  4114. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  4115. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  4116. $tmp['bid'] = $bid;
  4117. $tmp['version_id'] = $version_id;
  4118. $tmp['cid'] = $cid;
  4119. $tmp['sequence'] = $sequence;
  4120. $tmp['created_at'] = date('Y-m-d H:i:s');
  4121. $tmp['updated_at'] = date('Y-m-d H:i:s');
  4122. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  4123. $mp_chapter_paragraph_audios[] = $tmp;
  4124. $complete_paragraph_sequences[] = $sequence;
  4125. $sequence++;
  4126. }
  4127. $generate_json = json_encode($words, 256);
  4128. // 判断是否有未生成字幕的段落
  4129. $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();
  4130. if ($no_subtitle_sequences) {
  4131. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  4132. }
  4133. try {
  4134. DB::beginTransaction();
  4135. $role_info = json_encode($existed_role_info, 256);
  4136. $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')]);
  4137. if (!$boolen) {
  4138. DB::rollBack();
  4139. Utils::throwError('20003:更新角色信息失败');
  4140. }
  4141. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  4142. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  4143. if (!$count) {
  4144. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4145. }else {
  4146. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4147. }
  4148. $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')]);
  4149. if (!$boolen1) {
  4150. DB::rollBack();
  4151. Utils::throwError('20003:更新生成数据失败');
  4152. }
  4153. $id = DB::table('mp_audio_tasks')->insertGetId([
  4154. 'audio_id' => getProp($chapter_audio, 'id'),
  4155. 'generate_status' => '执行中',
  4156. 'generate_json' => $generate_json,
  4157. 'bid' => $bid,
  4158. 'book_name' => getProp($chapter_audio, 'book_name'),
  4159. 'version_id' => $version_id,
  4160. 'version_name' => getProp($chapter_audio, 'version_name'),
  4161. 'cid' => $cid,
  4162. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4163. 'task_name' => $task_name,
  4164. 'created_at' => date('Y-m-d H:i:s'),
  4165. 'updated_at' => date('Y-m-d H:i:s')
  4166. ]);
  4167. if (!$id) {
  4168. DB::rollBack();
  4169. Utils::throwError('20003:创建任务失败');
  4170. }
  4171. // 删除不在段落序号范围内的其他数据
  4172. if ($complete_paragraph_sequences) {
  4173. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  4174. }
  4175. // // 删除章节分句音频数据并重新插入
  4176. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  4177. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  4178. // if (!$boolen3) {
  4179. // DB::rollBack();
  4180. // Utils::throwError('20003:更新章节分句音频失败');
  4181. // }
  4182. } catch (\Exception $e) {
  4183. DB::rollBack();
  4184. Utils::throwError('20003:'.$e->getMessage());
  4185. }
  4186. DB::commit();
  4187. // 通知火山生成音频
  4188. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4189. // 根据ID通过API通知合成音频
  4190. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  4191. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  4192. $response = $result->getBody()->getContents();
  4193. $response_arr = json_decode($response, true);
  4194. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4195. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4196. Log::info('通知火山生成音频失败: '.$error_msg);
  4197. Utils::throwError('20003:通知火山生成音频失败');
  4198. }
  4199. return true;
  4200. }
  4201. public function timbreList($data) {
  4202. $gender = getProp($data, 'gender');
  4203. $timbre_name = getProp($data, 'voice_name');
  4204. $category_id = getProp($data, 'category_id');
  4205. $age_stage = getProp($data, 'age_stage');
  4206. $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');
  4207. if ($gender) {
  4208. $query->where('gender', $gender);
  4209. }
  4210. if ($timbre_name) {
  4211. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  4212. }
  4213. if ($category_id) {
  4214. $query->where(function ($query) use ($category_id) {
  4215. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  4216. });
  4217. }
  4218. if ($age_stage) {
  4219. $query->where('age_stage', $age_stage);
  4220. }
  4221. $list = $query->get()->map(function ($value) {
  4222. $value = (array)$value;
  4223. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  4224. return $value;
  4225. })->toArray();
  4226. return $list;
  4227. }
  4228. // 生成火山临时token
  4229. public function setStsToken() {
  4230. // ************* 配置参数 *************
  4231. $method = 'GET';
  4232. $service = 'sts';
  4233. $host = 'open.volcengineapi.com';
  4234. $region = env('VOLC_REGION');
  4235. $endpoint = 'https://open.volcengineapi.com';
  4236. // $endpoint = 'https://tos-cn-beijing.volces.com';
  4237. $access_key = env('VOLC_AK');
  4238. $secret_key = env('VOLC_SK');
  4239. // 获取缓存中的token,如果没有则请求接口
  4240. $token = Redis::get('volc_sts_token');
  4241. if (!$token) {
  4242. // 查询参数
  4243. $query_parameters = [
  4244. 'Action' => 'AssumeRole',
  4245. 'RoleSessionName' => 'user@zw',
  4246. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  4247. 'Version' => '2018-01-01'
  4248. ];
  4249. // 生成URL编码的查询字符串
  4250. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  4251. // 获取签名头信息
  4252. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  4253. // 构建完整URL
  4254. $request_url = $endpoint . '?' . $request_parameters;
  4255. $client = new Client(['verify' => false]);
  4256. $response = $client->get($request_url, ['headers' => $headers]);
  4257. $response_arr = json_decode($response->getBody()->getContents(), true);
  4258. $result = [
  4259. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  4260. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  4261. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  4262. 'Region' => env('VOLC_REGION'),
  4263. 'Endpoint' => env('VOLC_END_POINT'),
  4264. 'Bucket' => env('VOLC_BUCKET'),
  4265. ];
  4266. // 缓存token
  4267. Redis::setex('volc_sts_token', 3000, json_encode($result));
  4268. return $result;
  4269. } else {
  4270. return json_decode($token, true);
  4271. }
  4272. // $response = $response['Response'];
  4273. // $access_key = $response['Credentials']['AccessKeyId'];
  4274. // $secret_key = $response['Credentials']['AccessKeySecret'];
  4275. // $security_token = $response['Credentials']['SecurityToken'];
  4276. // $expiration = $response['Credentials']['Expiration'];
  4277. // dd($response_arr);
  4278. }
  4279. public function emotionGroups($data) {
  4280. $id = getProp($data, 'group_id');
  4281. $group_name = getProp($data, 'group_name');
  4282. $voice_type = getProp($data, 'voice_type');
  4283. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  4284. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  4285. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  4286. if ($group_name) {
  4287. $query->where('group_name', 'like', "%{$group_name}%");
  4288. }
  4289. if ($id) {
  4290. $query->where('id', $id);
  4291. }
  4292. if ($voice_type) {
  4293. $query->where('voice_type', $voice_type);
  4294. }
  4295. return $query->orderBy('id')->get()->map(function ($value) {
  4296. return (array)$value;
  4297. })->toArray();
  4298. }
  4299. private function sign($key, $msg) {
  4300. return hash_hmac('sha256', $msg, $key, true);
  4301. }
  4302. // 生成签名密钥
  4303. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  4304. $kDate = $this->sign($key, $dateStamp);
  4305. $kRegion = $this->sign($kDate, $regionName);
  4306. $kService = $this->sign($kRegion, $serviceName);
  4307. $kSigning = $this->sign($kService, 'request');
  4308. return $kSigning;
  4309. }
  4310. // 获取签名头信息
  4311. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  4312. $contenttype = 'application/x-www-form-urlencoded';
  4313. $accept = 'application/json';
  4314. // 获取当前UTC时间
  4315. $t = new DateTime('now', new DateTimeZone('UTC'));
  4316. $xdate = $t->format('Ymd\THis\Z');
  4317. $datestamp = $t->format('Ymd');
  4318. // 1. 拼接规范请求串
  4319. $canonical_uri = '/';
  4320. $canonical_querystring = $request_parameters;
  4321. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  4322. $signed_headers = 'content-type;host;x-date';
  4323. // 空请求体的SHA256哈希
  4324. $payload_hash = hash('sha256', '');
  4325. $canonical_request = implode("\n", [
  4326. $method,
  4327. $canonical_uri,
  4328. $canonical_querystring,
  4329. $canonical_headers,
  4330. $signed_headers,
  4331. $payload_hash
  4332. ]);
  4333. // 2. 拼接待签名字符串
  4334. $algorithm = 'HMAC-SHA256';
  4335. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  4336. $hashed_canonical_request = hash('sha256', $canonical_request);
  4337. $string_to_sign = implode("\n", [
  4338. $algorithm,
  4339. $xdate,
  4340. $credential_scope,
  4341. $hashed_canonical_request
  4342. ]);
  4343. // 3. 计算签名
  4344. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  4345. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  4346. // 4. 添加签名到请求头
  4347. $authorization_header = sprintf(
  4348. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4349. $algorithm,
  4350. $access_key,
  4351. $credential_scope,
  4352. $signed_headers,
  4353. $signature
  4354. );
  4355. return [
  4356. 'Accept' => $accept,
  4357. 'Content-Type' => $contenttype,
  4358. 'X-Date' => $xdate,
  4359. 'Authorization' => $authorization_header
  4360. ];
  4361. }
  4362. // 文字合成语音(火山引擎)
  4363. public function tts($data) {
  4364. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  4365. $headers = [
  4366. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  4367. 'Content-Type' => 'application/json; charset=UTF-8'
  4368. ];
  4369. $post_data = [
  4370. 'app' => [
  4371. 'appid' => env('VOLC_APPID'),
  4372. 'token' => env('VOLC_TOKEN'),
  4373. 'cluster' => 'volcano_tts'
  4374. ],
  4375. 'user' => [
  4376. 'uid' => 'mp_audio'
  4377. ],
  4378. // 'audio' => [
  4379. // 'voice_type' =>
  4380. // ],
  4381. ];
  4382. }
  4383. public function scriptList($data) {
  4384. $uid = Site::getUid();
  4385. $script_id = getProp($data, 'script_id');
  4386. $script_name = getProp($data, 'script_name');
  4387. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  4388. if ($script_id) {
  4389. $query->where('id', $script_id);
  4390. }
  4391. if ($script_name) {
  4392. $query->where('script_name', 'like', "%{$script_name}%");
  4393. }
  4394. return $query->orderBy('created_at', 'desc')->paginate(12);
  4395. }
  4396. public function scripts($data) {
  4397. $uid = Site::getUid();
  4398. $script_id = getProp($data, 'script_id');
  4399. $script_name = getProp($data, 'script_name');
  4400. $is_products = getProp($data, 'is_products');
  4401. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  4402. if ($script_id) {
  4403. $query->where('id', $script_id);
  4404. }
  4405. if ($is_products !== '') {
  4406. $query->where('is_products', $is_products);
  4407. }
  4408. if ($script_name) {
  4409. $query->where('script_name', 'like', "%{$script_name}%");
  4410. }
  4411. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  4412. return (array)$value;
  4413. })->toArray();
  4414. }
  4415. public function scriptInfo($data) {
  4416. $uid = Site::getUid();
  4417. $script_id = getProp($data, 'script_id');
  4418. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  4419. // ->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();
  4420. ->selectRaw('id as script_id, script_name')->first();
  4421. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4422. $script = (array)$script;
  4423. // 获取分集组信息
  4424. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  4425. ->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')
  4426. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  4427. $value = (array)$value;
  4428. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  4429. return (array)$value;
  4430. })->toArray();
  4431. $script['group'] = $groups;
  4432. return $script;
  4433. }
  4434. public function createScript($data) {
  4435. $script_name = getProp($data, 'script_name');
  4436. $uid = Site::getUid(); // 获取当前用户ID
  4437. $cpid = Site::getCpid(); // 获取当前公司组ID
  4438. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  4439. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  4440. $script_name .= '_'.date('YmdHis');
  4441. }
  4442. return DB::table('mp_scripts')->insertGetId([
  4443. 'script_name' => $script_name,
  4444. 'user_id' => $uid,
  4445. 'cpid' => $cpid,
  4446. 'created_at' => date('Y-m-d H:i:s'),
  4447. 'updated_at' => date('Y-m-d H:i:s')
  4448. ]);
  4449. }
  4450. public function editScript($data) {
  4451. $script_id = getProp($data, 'script_id');
  4452. $script_name = getProp($data, 'script_name');
  4453. $uid = Site::getUid(); // 获取当前用户ID
  4454. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  4455. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  4456. if ($id && (int)$id !== (int)$script_id) {
  4457. $script_name .= '_'.date('YmdHis');
  4458. }
  4459. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4460. 'script_name' => $script_name,
  4461. 'updated_at' => date('Y-m-d H:i:s')
  4462. ]);
  4463. }
  4464. public function delScript($data) {
  4465. $script_id = getProp($data, 'script_id');
  4466. $uid = Site::getUid(); // 获取当前用户ID
  4467. if (!$script_id) Utils::throwError('20003:请选择剧本');
  4468. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4469. 'is_deleted' => 1,
  4470. 'updated_at' => date('Y-m-d H:i:s')
  4471. ]);
  4472. }
  4473. public function createEpisode($data) {
  4474. $script_id = getProp($data, 'script_id');
  4475. $group_name = getProp($data, 'group_name');
  4476. $remark = getProp($data, 'remark');
  4477. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  4478. $uid = Site::getUid(); // 获取当前用户ID
  4479. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  4480. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  4481. $group_name .= '_'.date('YmdHis');
  4482. }
  4483. return DB::table('mp_script_episode_group')->insertGetId([
  4484. 'script_id' => $script_id,
  4485. 'group_name' => $group_name,
  4486. 'user_id' => $uid,
  4487. 'remark' => $remark,
  4488. 'created_at' => date('Y-m-d H:i:s'),
  4489. 'updated_at' => date('Y-m-d H:i:s')
  4490. ]);
  4491. }
  4492. public function editEpisode($data) {
  4493. $group_id = getProp($data, 'group_id');
  4494. $start_episode_number = getProp($data, 'start_episode_number');
  4495. $end_episode_number = getProp($data, 'end_episode_number');
  4496. $group_name = getProp($data, 'group_name');
  4497. $uid = Site::getUid(); // 获取当前用户ID
  4498. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  4499. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  4500. if ($id && (int)$id !== (int)$group_id) {
  4501. $group_name .= '_'.date('YmdHis');
  4502. }
  4503. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4504. 'group_name' => $group_name,
  4505. 'start_episode_number' => $start_episode_number,
  4506. 'end_episode_number' => $end_episode_number,
  4507. 'updated_at' => date('Y-m-d H:i:s')
  4508. ]);
  4509. }
  4510. public function delEpisode($data) {
  4511. $group_id = getProp($data, 'group_id');
  4512. $uid = Site::getUid(); // 获取当前用户ID
  4513. if (!$group_id) Utils::throwError('20003:请选择分集');
  4514. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4515. 'is_deleted' => 1,
  4516. 'updated_at' => date('Y-m-d H:i:s')
  4517. ]);
  4518. }
  4519. /**
  4520. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4521. *
  4522. * @param array $data 包含以下参数:
  4523. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4524. * - question: 用户问题(可选)
  4525. * - model: 使用的模型(r1 或 v3,默认 v3)
  4526. * @return \Generator 返回生成器,用于流式输出
  4527. */
  4528. public function generateEpisodes($data) {
  4529. // 文生文计费预检(special 档,每次调用扣 10)
  4530. $uid = Site::getUid();
  4531. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4532. $script_id = getProp($data, 'script_id');
  4533. $group_id = getProp($data, 'group_id');
  4534. // $file = getProp($data, 'file');
  4535. $file = '';
  4536. $content = getProp($data, 'content', '');
  4537. // $bid = getProp($data, 'bid', 0);
  4538. $bid = 0;
  4539. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4540. if (!$group) {
  4541. Utils::throwError('20003:剧本分集不存在');
  4542. }
  4543. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  4544. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  4545. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  4546. $prompt = getProp($data, 'prompt');
  4547. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  4548. $model = getProp($data, 'model');
  4549. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4550. Utils::throwError('20003:该模型不存在!');
  4551. }
  4552. // 检查是否存在重叠的剧集序号范围
  4553. $exists_groups = DB::table('mp_script_episode_group')
  4554. ->where('script_id', $script_id)
  4555. ->where('id', '<>', $group_id) // 排除当前组
  4556. ->where('is_deleted', 0)
  4557. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4558. // 检查新范围是否与现有范围重叠
  4559. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4560. // 新范围的开始在现有范围内
  4561. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4562. ->where('end_episode_number', '>=', $start_episode_sequence);
  4563. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4564. // 新范围的结束在现有范围内
  4565. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4566. ->where('end_episode_number', '>=', $end_episode_sequence);
  4567. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4568. // 新范围完全包含现有范围
  4569. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4570. ->where('end_episode_number', '<=', $end_episode_sequence);
  4571. });
  4572. })
  4573. ->select('start_episode_number', 'end_episode_number')
  4574. ->get();
  4575. if ($exists_groups->isNotEmpty()) {
  4576. $conflict_ranges = [];
  4577. foreach ($exists_groups as $group) {
  4578. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4579. }
  4580. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4581. }
  4582. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4583. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4584. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4585. if ($model === 'deepseek-chat') {
  4586. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4587. $model = 'deepseek-v4-flash';
  4588. $thinkingMode = 'disabled';
  4589. } elseif ($model === 'deepseek-reasoner') {
  4590. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4591. $model = 'deepseek-v4-flash';
  4592. $thinkingMode = 'enabled';
  4593. }
  4594. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4595. if (!$script) {
  4596. Utils::throwError('20003:剧本不存在');
  4597. }
  4598. $content = getProp($group, 'content');
  4599. if (!$file && !$content && !$bid) {
  4600. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4601. }
  4602. // 提取文件内容
  4603. if ($file) {
  4604. $content = $this->extractFileContent($file);
  4605. if (!$content) {
  4606. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4607. }
  4608. } elseif ($bid) {
  4609. $content = $this->getContentByBid($bid);
  4610. if (!$content) {
  4611. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4612. }
  4613. } elseif ($content) {
  4614. $content = filterContent($content);
  4615. } elseif ($prompt) {
  4616. $content = filterContent($prompt);
  4617. } else {
  4618. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4619. }
  4620. // 构建消息
  4621. $messages = [
  4622. $this->sys_message,
  4623. [
  4624. 'role' => 'user',
  4625. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4626. ]
  4627. ];
  4628. $post_data = [
  4629. 'model' => $model,
  4630. 'messages' => $messages,
  4631. // 'max_tokens' => 8192,
  4632. 'temperature' => 0.7,
  4633. 'frequency_penalty' => 0,
  4634. 'presence_penalty' => 0,
  4635. 'thinking' => ['type' => $thinkingMode],
  4636. 'response_format' => ['type' => 'text'],
  4637. 'stream' => true
  4638. ];
  4639. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4640. // 根据模型类型选择调用方法
  4641. $fullContent = '';
  4642. $fullReasoningContent = '';
  4643. $usage = [];
  4644. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4645. // 处理流式输出
  4646. foreach ($streamGenerator as $chunk) {
  4647. if (isset($chunk['type'])) {
  4648. if ($chunk['type'] === 'done') {
  4649. // 最终结果
  4650. $fullContent = $chunk['full_content'];
  4651. $fullReasoningContent = $chunk['full_reasoning'];
  4652. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4653. } else {
  4654. // 逐块yield数据
  4655. yield $chunk;
  4656. }
  4657. }
  4658. }
  4659. dLog('deepseek')->info('完整内容: '.$fullContent);
  4660. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4661. // 处理完整内容并返回最终结果
  4662. $script_arr = [];
  4663. if ($fullContent) {
  4664. $script_arr = extractScriptContent($fullContent);
  4665. }
  4666. logDB('deepseek', 'info', '解析内容', $script_arr);
  4667. if (!$script_arr['episodes']) {
  4668. Utils::throwError('20003:未生成剧本相关信息');
  4669. // yield [
  4670. // 'type' => 'done',
  4671. // 'script' => $script_arr,
  4672. // 'msg' => '未生成剧本相关信息',
  4673. // 'answer' => $fullContent,
  4674. // 'reasoning' => $fullReasoningContent,
  4675. // 'usage' => $usage
  4676. // ];
  4677. // return ;
  4678. }
  4679. try {
  4680. DB::beginTransaction();
  4681. // // 返回前保存剧本内容
  4682. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4683. // 'content' => $content,
  4684. // 'updated_at' => date('Y-m-d H:i:s')
  4685. // ]);
  4686. // if (!$boolen) {
  4687. // Utils::throwError('20003:保存剧本内容失败');
  4688. // }
  4689. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4690. // 'start_episode_number' => $start_episode_sequence,
  4691. // 'end_episode_number' => $end_episode_sequence,
  4692. // 'updated_at' => date('Y-m-d H:i:s')
  4693. // ]);
  4694. // if (!$boolen1) {
  4695. // Utils::throwError('20003:保存分集失败');
  4696. // }
  4697. $episode_content = '';
  4698. $episodes = [];
  4699. foreach ($script_arr['episodes'] as $item) {
  4700. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4701. // $episodes[] = [
  4702. // 'script_id' => $script_id,
  4703. // 'episode_number' => $item['episode_number'],
  4704. // 'episode_name' => $item['episode_name'],
  4705. // 'episode_content' => $item['episode_content'],
  4706. // 'created_at' => date('Y-m-d H:i:s'),
  4707. // 'updated_at' => date('Y-m-d H:i:s'),
  4708. // ];
  4709. }
  4710. if ($episode_content) {
  4711. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4712. 'episode_content' => $episode_content,
  4713. 'updated_at' => date('Y-m-d H:i:s')
  4714. ]);
  4715. if (!$boolen2) {
  4716. Utils::throwError('20003:保存分集内容失败');
  4717. }
  4718. }else {
  4719. Utils::throwError('20003:分集剧本解析失败');
  4720. }
  4721. // 文生文成功计费(special 档):与落库同事务
  4722. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4723. 'model' => $model,
  4724. 'script_id' => $script_id,
  4725. 'group_id' => $group_id,
  4726. 'source' => 'generateEpisodes',
  4727. ]);
  4728. }catch (\Exception $e) {
  4729. DB::rollBack();
  4730. Utils::throwError('20003:'.$e->getMessage());
  4731. }
  4732. DB::commit();
  4733. yield [
  4734. 'type' => 'done',
  4735. 'script' => $script_arr,
  4736. 'episode_content' => $episode_content,
  4737. 'answer' => $fullContent,
  4738. 'reasoning' => $fullReasoningContent,
  4739. 'usage' => $usage
  4740. ];
  4741. }
  4742. public function chatWithFileStream($data) {
  4743. // 剧本解析资产表计费预检(special 档)
  4744. $uid = Site::getUid();
  4745. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4746. $script_id = getProp($data, 'script_id');
  4747. $group_id = getProp($data, 'group_id');
  4748. $file = getProp($data, 'file');
  4749. $content = getProp($data, 'content', '');
  4750. $bid = getProp($data, 'bid', 0);
  4751. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4752. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4753. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4754. $prompt = getProp($data, 'prompt');
  4755. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4756. if (!empty($prompt)) {
  4757. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4758. }
  4759. $question = getProp($data, 'question', $baseQuestion);
  4760. $model = getProp($data, 'model');
  4761. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4762. Utils::throwError('20003:该模型不存在!');
  4763. }
  4764. // 检查是否存在重叠的剧集序号范围
  4765. $exists_groups = DB::table('mp_script_episode_group')
  4766. ->where('script_id', $script_id)
  4767. ->where('id', '<>', $group_id)
  4768. ->where('is_deleted', 0)
  4769. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4770. // 检查新范围是否与现有范围重叠
  4771. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4772. // 新范围的开始在现有范围内
  4773. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4774. ->where('end_episode_number', '>=', $start_episode_sequence);
  4775. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4776. // 新范围的结束在现有范围内
  4777. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4778. ->where('end_episode_number', '>=', $end_episode_sequence);
  4779. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4780. // 新范围完全包含现有范围
  4781. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4782. ->where('end_episode_number', '<=', $end_episode_sequence);
  4783. });
  4784. })
  4785. ->select('start_episode_number', 'end_episode_number')
  4786. ->get();
  4787. if ($exists_groups->isNotEmpty()) {
  4788. $conflict_ranges = [];
  4789. foreach ($exists_groups as $group) {
  4790. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4791. }
  4792. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4793. }
  4794. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4795. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4796. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4797. if ($model === 'deepseek-chat') {
  4798. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4799. $model = 'deepseek-v4-flash';
  4800. $thinkingMode = 'disabled';
  4801. } elseif ($model === 'deepseek-reasoner') {
  4802. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4803. $model = 'deepseek-v4-flash';
  4804. $thinkingMode = 'enabled';
  4805. }
  4806. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4807. if (!$script) {
  4808. Utils::throwError('20003:剧本不存在');
  4809. }
  4810. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4811. if (!$group) {
  4812. Utils::throwError('20003:剧本分集不存在');
  4813. }
  4814. if (!$file && !$content && !$bid) {
  4815. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4816. }
  4817. // 提取文件内容
  4818. if ($file) {
  4819. $content = $this->extractFileContent($file);
  4820. if (!$content) {
  4821. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4822. }
  4823. } elseif ($bid) {
  4824. $content = $this->getContentByBid($bid);
  4825. if (!$content) {
  4826. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4827. }
  4828. } elseif ($content) {
  4829. $content = filterContent($content);
  4830. } elseif ($prompt) {
  4831. $content = filterContent($prompt);
  4832. } else {
  4833. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4834. }
  4835. // 构建消息
  4836. $messages = [
  4837. [
  4838. 'role' => 'system',
  4839. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4840. 强制要求:\n
  4841. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4842. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4843. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4844. 普通要求:\n
  4845. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4846. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4847. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4848. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4849. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4850. 示例如下:\n
  4851. ###剧本名:西昆仑
  4852. ###故事梗概
  4853. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4854. ###剧本亮点
  4855. 亮点1:绝境奇药,生死一线
  4856. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4857. 亮点2:结拜兄妹,化解尴尬
  4858. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4859. 亮点3:纤发夺命,情愫暗涌
  4860. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4861. ###人物关系
  4862. 阿雪与梁萧之间存在兄妹之情。
  4863. ###核心矛盾
  4864. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4865. ###主体列表
  4866. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4867. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4868. 阴阳球:天地异宝,能化生精气,救人于危难。
  4869. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4870. ###美术风格
  4871. 基础画风风格词:厚涂古风
  4872. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4873. ###场景列表
  4874. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4875. [
  4876. 'role' => 'user',
  4877. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4878. ]
  4879. ];
  4880. $post_data = [
  4881. 'model' => $model,
  4882. 'messages' => $messages,
  4883. // 'max_tokens' => 8192,
  4884. 'temperature' => 0.7,
  4885. 'frequency_penalty' => 0,
  4886. 'presence_penalty' => 0,
  4887. 'thinking' => ['type' => $thinkingMode],
  4888. 'response_format' => ['type' => 'text'],
  4889. 'stream' => true
  4890. ];
  4891. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4892. // 根据模型类型选择调用方法
  4893. $fullContent = '';
  4894. $fullReasoningContent = '';
  4895. $usage = [];
  4896. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4897. // 处理流式输出
  4898. foreach ($streamGenerator as $chunk) {
  4899. if (isset($chunk['type'])) {
  4900. if ($chunk['type'] === 'done') {
  4901. // 最终结果
  4902. $fullContent = $chunk['full_content'];
  4903. $fullReasoningContent = $chunk['full_reasoning'];
  4904. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4905. } else {
  4906. // 逐块yield数据
  4907. yield $chunk;
  4908. }
  4909. }
  4910. }
  4911. dLog('deepseek')->info('完整内容: '.$fullContent);
  4912. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4913. // 处理完整内容并返回最终结果
  4914. $script_arr = [];
  4915. if ($fullContent) {
  4916. $script_arr = extractScriptContent($fullContent);
  4917. }
  4918. logDB('deepseek', 'info', '解析内容', $script_arr);
  4919. if (!$script_arr['roles']) {
  4920. Utils::throwError('20003:未生成剧本相关信息');
  4921. // yield [
  4922. // 'type' => 'done',
  4923. // 'script' => $script_arr,
  4924. // 'msg' => '未生成剧本相关信息',
  4925. // 'answer' => $fullContent,
  4926. // 'reasoning' => $fullReasoningContent,
  4927. // 'usage' => $usage
  4928. // ];
  4929. }
  4930. try {
  4931. DB::beginTransaction();
  4932. // // 返回前保存剧本内容
  4933. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4934. // 'content' => $content,
  4935. // 'status' => '解析完成',
  4936. // 'updated_at' => date('Y-m-d H:i:s')
  4937. // ]);
  4938. // if (!$boolen) {
  4939. // Utils::throwError('20003:保存剧本内容失败');
  4940. // }
  4941. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4942. 'start_episode_number' => $start_episode_sequence,
  4943. 'end_episode_number' => $end_episode_sequence,
  4944. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4945. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4946. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4947. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4948. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4949. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4950. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4951. 'status' => '解析完成',
  4952. 'content' => $content,
  4953. 'updated_at' => date('Y-m-d H:i:s')
  4954. ]);
  4955. if (!$boolen1) {
  4956. Utils::throwError('20003:保存分集失败');
  4957. }
  4958. // 剧本解析资产表成功计费(special 档):与落库同事务
  4959. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4960. 'model' => $model,
  4961. 'script_id' => $script_id,
  4962. 'group_id' => $group_id,
  4963. 'source' => 'chatWithFileStream',
  4964. ], 'special');
  4965. // $episodes = [];
  4966. // foreach ($script_arr['episodes'] as $item) {
  4967. // $episodes[] = [
  4968. // 'script_id' => $script_id,
  4969. // 'episode_number' => $item['episode_number'],
  4970. // 'episode_name' => $item['episode_name'],
  4971. // 'episode_content' => $item['episode_content'],
  4972. // 'created_at' => date('Y-m-d H:i:s'),
  4973. // 'updated_at' => date('Y-m-d H:i:s'),
  4974. // ];
  4975. // }
  4976. // if ($episodes) {
  4977. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4978. // if (!$boolen2) {
  4979. // Utils::throwError('20003:保存分集内容失败');
  4980. // }
  4981. // }else {
  4982. // Utils::throwError('20003:分集剧本解析失败');
  4983. // }
  4984. }catch (\Exception $e) {
  4985. DB::rollBack();
  4986. Utils::throwError('20003:'.$e->getMessage());
  4987. }
  4988. DB::commit();
  4989. yield [
  4990. 'type' => 'done',
  4991. 'script' => $script_arr,
  4992. 'answer' => $fullContent,
  4993. 'reasoning' => $fullReasoningContent,
  4994. 'usage' => $usage
  4995. ];
  4996. }
  4997. /**
  4998. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4999. *
  5000. * @param array $data 包含以下参数:
  5001. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5002. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  5003. * - model: 使用的模型(r1 或 v3,默认 v3)
  5004. * @return array
  5005. */
  5006. public function chatWithFile($data) {
  5007. // 剧本解析资产表计费预检(special 档)
  5008. $uid = Site::getUid();
  5009. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  5010. $script_id = getProp($data, 'script_id');
  5011. $file = getProp($data, 'file');
  5012. $content = getProp($data, 'content', '');
  5013. $bid = getProp($data, 'bid', 0);
  5014. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5015. $total_episode_num = getProp($data, 'total_episode_num', 30);
  5016. $prompt = getProp($data, 'prompt');
  5017. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  5018. if (!empty($prompt)) {
  5019. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  5020. }
  5021. $question = getProp($data, 'question', $baseQuestion);
  5022. // 处理文本模型
  5023. $model = getProp($data, 'model');
  5024. if (!$model) {
  5025. // 用户没有输入,使用默认值
  5026. $model = 'doubao-seed-2-0-mini-260215';
  5027. }
  5028. // 验证模型是否在可用模型表中
  5029. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5030. $model = 'doubao-seed-2-0-mini-260215';
  5031. }
  5032. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5033. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5034. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5035. if ($model === 'deepseek-chat') {
  5036. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5037. $model = 'deepseek-v4-flash';
  5038. $thinkingMode = 'disabled';
  5039. } elseif ($model === 'deepseek-reasoner') {
  5040. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5041. $model = 'deepseek-v4-flash';
  5042. $thinkingMode = 'enabled';
  5043. }
  5044. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  5045. if (!$script) {
  5046. Utils::throwError('20003:剧本不存在');
  5047. }
  5048. if (!$file && !$content && !$bid) {
  5049. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5050. }
  5051. // 提取文件内容
  5052. if ($file) {
  5053. $content = $this->extractFileContent($file);
  5054. if (!$content) {
  5055. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5056. }
  5057. } elseif ($bid) {
  5058. $content = $this->getContentByBid($bid);
  5059. if (!$content) {
  5060. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5061. }
  5062. } elseif ($content) {
  5063. $content = filterContent($content);
  5064. } elseif ($prompt) {
  5065. $content = filterContent($prompt);
  5066. } else {
  5067. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5068. }
  5069. // 构建消息
  5070. $messages = [
  5071. $this->sys_message,
  5072. [
  5073. 'role' => 'user',
  5074. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  5075. ]
  5076. ];
  5077. $post_data = [
  5078. 'model' => $model,
  5079. 'messages' => $messages,
  5080. // 'max_tokens' => 8192,
  5081. 'temperature' => 0.7,
  5082. 'frequency_penalty' => 0,
  5083. 'presence_penalty' => 0,
  5084. 'thinking' => ['type' => $thinkingMode],
  5085. 'response_format' => ['type' => 'text'],
  5086. 'stream' => false
  5087. ];
  5088. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5089. // 根据模型类型选择调用方法
  5090. $fullContent = '';
  5091. $usage = [];
  5092. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  5093. if (is_array($chatResult)) {
  5094. $fullContent = $chatResult['fullContent'];
  5095. $usage = $chatResult['usage'];
  5096. }
  5097. $script_arr = [];
  5098. // 处理结果
  5099. if ($fullContent) {
  5100. $script_arr = extractScriptContent($fullContent);
  5101. }
  5102. // 返回前保存剧本内容
  5103. DB::table('mp_scripts')->where('id', $script_id)->update([
  5104. 'content' => $content,
  5105. 'updated_at' => date('Y-m-d H:i:s')
  5106. ]);
  5107. // 剧本解析资产表成功计费(special 档):同时记录积分与 token 明细
  5108. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5109. 'model' => $model,
  5110. 'script_id' => $script_id,
  5111. 'source' => 'chatWithFile',
  5112. ], 'special');
  5113. return [
  5114. 'script' => $script_arr,
  5115. 'answer' => $fullContent,
  5116. 'usage' => $usage
  5117. ];
  5118. }
  5119. public function getEpisodeContent($data) {
  5120. $group_id = getProp($data, 'group_id');
  5121. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  5122. }
  5123. public function saveEpisodeContent($data) {
  5124. $script_id = getProp($data, 'script_id');
  5125. $group_id = getProp($data, 'group_id');
  5126. $start_episode_sequence = getProp($data, 'start_episode_number');
  5127. $end_episode_sequence = getProp($data, 'end_episode_number');
  5128. // 检查是否存在重叠的剧集序号范围
  5129. $exists_groups = DB::table('mp_script_episode_group')
  5130. ->where('script_id', $script_id)
  5131. ->where('id', '<>', $group_id) // 排除当前组
  5132. ->where('is_deleted', 0)
  5133. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  5134. // 检查新范围是否与现有范围重叠
  5135. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5136. // 新范围的开始在现有范围内
  5137. $q->where('start_episode_number', '<=', $start_episode_sequence)
  5138. ->where('end_episode_number', '>=', $start_episode_sequence);
  5139. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5140. // 新范围的结束在现有范围内
  5141. $q->where('start_episode_number', '<=', $end_episode_sequence)
  5142. ->where('end_episode_number', '>=', $end_episode_sequence);
  5143. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5144. // 新范围完全包含现有范围
  5145. $q->where('start_episode_number', '>=', $start_episode_sequence)
  5146. ->where('end_episode_number', '<=', $end_episode_sequence);
  5147. });
  5148. })
  5149. ->select('start_episode_number', 'end_episode_number')
  5150. ->get();
  5151. if ($exists_groups->isNotEmpty()) {
  5152. $conflict_ranges = [];
  5153. foreach ($exists_groups as $group) {
  5154. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  5155. }
  5156. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  5157. }
  5158. $episode_content = getProp($data, 'episode_content');
  5159. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  5160. 'content' => $episode_content,
  5161. 'start_episode_number' => $start_episode_sequence,
  5162. 'end_episode_number' => $end_episode_sequence,
  5163. 'updated_at' => date('Y-m-d H:i:s')
  5164. ]);
  5165. $script_arr =getProp($data, 'script', []);
  5166. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  5167. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5168. $script_id = getProp($data, 'script_id');
  5169. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  5170. try {
  5171. DB::beginTransaction();
  5172. $update_data = [
  5173. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5174. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5175. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5176. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5177. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5178. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5179. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5180. 'status' => 3,
  5181. 'start_episode_sequence' => $start_episode_sequence,
  5182. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  5183. 'episode_num' => count($script_arr['episodes']),
  5184. 'updated_at' => date('Y-m-d H:i:s')
  5185. ];
  5186. // 保存剧本内容
  5187. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  5188. if (!$boolen) {
  5189. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  5190. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  5191. Utils::throwError('20003:剧本内容保存失败');
  5192. }
  5193. // 保存分集内容
  5194. // 删除历史分集内容
  5195. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  5196. $episodes = [];
  5197. $sequence = 1;
  5198. foreach ($script_arr['episodes'] as $episode) {
  5199. $segment_number = 1;
  5200. foreach($episode['segments'] as $segment) {
  5201. $episodes[] = [
  5202. 'script_id' => $script_id,
  5203. 'episode_number' => $episode['episode_number'],
  5204. 'title' => $episode['title'],
  5205. // 'content' => $episode['content'],
  5206. 'content' => '',
  5207. 'segment_number' => $segment_number,
  5208. 'segment_content' => $segment['segment_content'],
  5209. 'sequence' => $sequence,
  5210. 'created_at' => date('Y-m-d H:i:s'),
  5211. 'updated_at' => date('Y-m-d H:i:s')
  5212. ];
  5213. $sequence++;
  5214. $segment_number++;
  5215. }
  5216. }
  5217. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5218. if (!$boolen2) {
  5219. dLog('deepseek')->info('分集内容保存失败', $episodes);
  5220. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  5221. Utils::throwError('20003:分集内容保存失败');
  5222. }
  5223. } catch (\Exception $e) {
  5224. DB::rollBack();
  5225. Utils::throwError('20003:'.$e->getMessage());
  5226. }
  5227. DB::commit();
  5228. return true;
  5229. }
  5230. public function getBookContent($data) {
  5231. $bid = getProp($data, 'bid');
  5232. $start_sequence = getProp($data, 'start_sequence');
  5233. $end_sequence = getProp($data, 'end_sequence');
  5234. $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])
  5235. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  5236. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  5237. return $return_content;
  5238. }
  5239. public function exportScript($data) {
  5240. $filename = getProp($data, 'filename');
  5241. $script_id = getProp($data, 'script_id');
  5242. $group_id = getProp($data, 'group_id');
  5243. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  5244. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  5245. if (!$script) Utils::throwError('20003:该剧本不存在!');
  5246. $script = (array)$script;
  5247. // 获取分集组信息
  5248. if ($group_id) {
  5249. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5250. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5251. ->get()->map(function($value) {
  5252. return (array)$value;
  5253. })->toArray();
  5254. }else {
  5255. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5256. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5257. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  5258. return (array)$value;
  5259. })->toArray();
  5260. }
  5261. if (!$groups) Utils::throwError('20003:分集不存在');
  5262. $script['group'] = $groups;
  5263. $export_type = getProp($data, 'export_type', 'txt');
  5264. // 生成文件名
  5265. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  5266. // 根据导出类型生成不同格式的文件
  5267. switch ($export_type) {
  5268. case 'txt':
  5269. return $this->exportScriptAsTxt($script, $filename);
  5270. case 'pdf':
  5271. return $this->exportScriptAsPdf($script, $filename);
  5272. default:
  5273. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  5274. }
  5275. }
  5276. /**
  5277. * 导出剧本为TXT格式
  5278. */
  5279. private function exportScriptAsTxt($script, $filename) {
  5280. // 构建TXT内容
  5281. $content = $this->buildScriptContent($script);
  5282. // 设置响应头,直接下载
  5283. header('Content-Type: text/plain; charset=utf-8');
  5284. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  5285. header('Content-Length: ' . strlen($content));
  5286. // 输出内容并结束
  5287. echo $content;
  5288. exit();
  5289. }
  5290. /**
  5291. * 导出剧本为PDF格式
  5292. */
  5293. private function exportScriptAsPdf($script, $filename) {
  5294. // 使用HTML转PDF的方式来更好地支持中文
  5295. $htmlContent = $this->buildScriptHtmlForPdf($script);
  5296. // 创建PDF实例
  5297. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  5298. // 设置文档信息
  5299. $pdf->SetCreator('剧本导出系统');
  5300. $pdf->SetAuthor('系统');
  5301. $pdf->SetTitle($script['script_name']);
  5302. $pdf->SetSubject('剧本导出');
  5303. // 设置边距
  5304. $pdf->SetMargins(15, 15, 15);
  5305. $pdf->SetAutoPageBreak(TRUE, 15);
  5306. // 添加页面
  5307. $pdf->AddPage();
  5308. // 注册并使用 simsun.ttf 字体
  5309. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  5310. // 使用HTML内容生成PDF
  5311. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  5312. // 直接输出PDF文件供下载
  5313. header('Content-Type: application/pdf');
  5314. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  5315. // 直接输出PDF内容
  5316. $pdf->Output($filename . '.pdf', 'D');
  5317. exit();
  5318. }
  5319. /**
  5320. * 构建用于PDF的HTML内容
  5321. */
  5322. private function buildScriptHtmlForPdf($script) {
  5323. $html = '<style>
  5324. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  5325. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  5326. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  5327. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  5328. .info { margin-bottom: 8px; }
  5329. .group { margin-bottom: 30px; page-break-inside: avoid; }
  5330. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  5331. .segment { margin-bottom: 10px; margin-left: 20px; }
  5332. .episode-content { white-space: pre-wrap; }
  5333. </style>';
  5334. // 标题
  5335. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  5336. // 处理分组数据
  5337. if (!empty($script['group']) && is_array($script['group'])) {
  5338. $groups = (array)$script['group'];
  5339. foreach ($groups as $group) {
  5340. $html .= '<div class="group">';
  5341. // 分组标题
  5342. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  5343. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  5344. // 故事梗概
  5345. if (!empty($group['intro'])) {
  5346. $html .= '<h3>故事梗概</h3>';
  5347. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  5348. }
  5349. // 剧本亮点
  5350. if (!empty($group['highlights'])) {
  5351. $html .= '<h3>剧本亮点</h3>';
  5352. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  5353. }
  5354. // 人物关系
  5355. if (!empty($group['role_relationship'])) {
  5356. $html .= '<h3>人物关系</h3>';
  5357. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  5358. }
  5359. // 核心矛盾
  5360. if (!empty($group['core_contradiction'])) {
  5361. $html .= '<h3>核心矛盾</h3>';
  5362. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  5363. }
  5364. // 主体列表
  5365. if (!empty($group['roles']) && is_array($group['roles'])) {
  5366. $html .= '<h3>主体列表</h3>';
  5367. $html .= '<ul>';
  5368. foreach ($group['roles'] as $role) {
  5369. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  5370. }
  5371. $html .= '</ul>';
  5372. }
  5373. // 美术风格
  5374. if (!empty($group['art_style'])) {
  5375. $html .= '<h3>美术风格</h3>';
  5376. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  5377. }
  5378. // 场景列表
  5379. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5380. $html .= '<h3>场景列表</h3>';
  5381. $html .= '<ul>';
  5382. foreach ($group['scenes'] as $scene) {
  5383. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  5384. }
  5385. $html .= '</ul>';
  5386. }
  5387. // 分集剧本
  5388. if (!empty($group['episode_content'])) {
  5389. $html .= '<h3>分集剧本</h3>';
  5390. // 去除零宽字符和其他不可见字符
  5391. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  5392. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  5393. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  5394. }
  5395. $html .= '</div>';
  5396. }
  5397. }
  5398. return $html;
  5399. }
  5400. /**
  5401. * 构建PDF内容
  5402. */
  5403. private function buildPdfContent($pdf, $script) {
  5404. // 标题
  5405. $pdf->SetFont('dejavusans', 'B', 18);
  5406. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  5407. $pdf->Ln(5);
  5408. // 基本信息
  5409. $pdf->SetFont('dejavusans', '', 12);
  5410. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  5411. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  5412. $pdf->Ln(5);
  5413. // 剧本简介
  5414. if (!empty($script['intro'])) {
  5415. $pdf->SetFont('dejavusans', 'B', 14);
  5416. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  5417. $pdf->SetFont('dejavusans', '', 12);
  5418. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  5419. $pdf->Ln(3);
  5420. }
  5421. // 亮点
  5422. if (!empty($script['highlights'])) {
  5423. $pdf->SetFont('dejavusans', 'B', 14);
  5424. $pdf->Cell(0, 10, '亮点', 0, 1);
  5425. $pdf->SetFont('dejavusans', '', 12);
  5426. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  5427. $pdf->Ln(3);
  5428. }
  5429. // 核心矛盾
  5430. if (!empty($script['core_contradiction'])) {
  5431. $pdf->SetFont('dejavusans', 'B', 14);
  5432. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  5433. $pdf->SetFont('dejavusans', '', 12);
  5434. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  5435. $pdf->Ln(3);
  5436. }
  5437. // 艺术风格
  5438. if (!empty($script['art_style'])) {
  5439. $pdf->SetFont('dejavusans', 'B', 14);
  5440. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  5441. $pdf->SetFont('dejavusans', '', 12);
  5442. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  5443. $pdf->Ln(3);
  5444. }
  5445. // 备注
  5446. if (!empty($script['remark'])) {
  5447. $pdf->SetFont('dejavusans', 'B', 14);
  5448. $pdf->Cell(0, 10, '备注', 0, 1);
  5449. $pdf->SetFont('dejavusans', '', 12);
  5450. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  5451. $pdf->Ln(3);
  5452. }
  5453. // 角色列表
  5454. if (!empty($script['roles']) && is_array($script['roles'])) {
  5455. $pdf->SetFont('dejavusans', 'B', 14);
  5456. $pdf->Cell(0, 10, '角色列表', 0, 1);
  5457. $pdf->SetFont('dejavusans', '', 12);
  5458. foreach ($script['roles'] as $index => $role) {
  5459. if (is_array($role) || is_object($role)) {
  5460. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  5461. } else {
  5462. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  5463. }
  5464. }
  5465. $pdf->Ln(3);
  5466. }
  5467. // 角色关系
  5468. if (!empty($script['role_relationship'])) {
  5469. $pdf->SetFont('dejavusans', 'B', 14);
  5470. $pdf->Cell(0, 10, '角色关系', 0, 1);
  5471. $pdf->SetFont('dejavusans', '', 12);
  5472. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  5473. $pdf->Ln(3);
  5474. }
  5475. // 场景列表
  5476. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  5477. $pdf->SetFont('dejavusans', 'B', 14);
  5478. $pdf->Cell(0, 10, '场景列表', 0, 1);
  5479. $pdf->SetFont('dejavusans', '', 12);
  5480. foreach ($script['scenes'] as $index => $scene) {
  5481. if (is_array($scene) || is_object($scene)) {
  5482. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  5483. } else {
  5484. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  5485. }
  5486. }
  5487. $pdf->Ln(5);
  5488. }
  5489. // 分集内容
  5490. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  5491. $pdf->SetFont('dejavusans', 'B', 16);
  5492. $pdf->Cell(0, 12, '分集内容', 0, 1);
  5493. $pdf->Ln(3);
  5494. foreach ($script['episodes'] as $episode) {
  5495. // 检查是否需要新页面
  5496. if ($pdf->GetY() > 250) {
  5497. $pdf->AddPage();
  5498. }
  5499. $pdf->SetFont('dejavusans', 'B', 14);
  5500. $episodeTitle = '第' . $episode['episode_number'] . '集';
  5501. if (!empty($episode['title'])) {
  5502. $episodeTitle .= ':' . $episode['title'];
  5503. }
  5504. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  5505. // 处理分段内容
  5506. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  5507. $pdf->SetFont('dejavusans', '', 12);
  5508. foreach ($episode['segments'] as $segment) {
  5509. if (!empty($segment['segment_content'])) {
  5510. // 如果有分段编号,显示分段标题
  5511. if (!empty($segment['segment_number'])) {
  5512. $pdf->SetFont('dejavusans', 'B', 12);
  5513. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  5514. $pdf->SetFont('dejavusans', '', 12);
  5515. }
  5516. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  5517. $pdf->Ln(2);
  5518. }
  5519. }
  5520. }
  5521. $pdf->Ln(5);
  5522. }
  5523. }
  5524. }
  5525. /**
  5526. * 构建剧本文本内容
  5527. */
  5528. private function buildScriptContent($script) {
  5529. $content = '';
  5530. $groups = $script['group'];
  5531. $groups = (array)$groups;
  5532. foreach ($groups as $group) {
  5533. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  5534. // 剧本基本信息
  5535. if (!empty($group['intro'])) {
  5536. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5537. }
  5538. if (!empty($group['highlights'])) {
  5539. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5540. }
  5541. if (!empty($group['role_relationship'])) {
  5542. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5543. }
  5544. if (!empty($group['core_contradiction'])) {
  5545. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5546. }
  5547. if (!empty($group['roles']) && is_array($group['roles'])) {
  5548. $content .= "###主体列表\n";
  5549. foreach ($group['roles'] as $role) {
  5550. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5551. }
  5552. $content .= "\n\n";
  5553. }
  5554. if (!empty($group['art_style'])) {
  5555. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5556. }
  5557. // 场景信息
  5558. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5559. $content .= "###场景列表\n";
  5560. foreach ($group['scenes'] as $scene) {
  5561. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5562. }
  5563. $content .= "\n\n";
  5564. }
  5565. // 分集内容
  5566. if (!empty($group['episode_content'])) {
  5567. $content .= "###分集剧本\n";
  5568. $content .= $group['episode_content'];
  5569. // foreach ($script['episodes'] as $episode) {
  5570. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5571. // // if (!empty($episode['episode_name'])) {
  5572. // // $content .= ":" . $episode['episode_name'];
  5573. // // }
  5574. // // $content .= "\n";
  5575. // $content .= $episode['episode_content'] . "\n\n";
  5576. // }
  5577. }
  5578. }
  5579. return $content;
  5580. }
  5581. /**
  5582. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5583. *
  5584. * @param array $data 包含以下参数:
  5585. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5586. * - question: 用户问题(可选)
  5587. * - model: 使用的模型(r1 或 v3,默认 v3)
  5588. * @return \Generator 返回生成器,用于流式输出
  5589. */
  5590. public function addChat($data) {
  5591. $uid = Site::getUid();
  5592. $anime_id = getProp($data, 'anime_id');
  5593. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5594. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5595. if (!$anime) Utils::throwError('20003:对话不存在');
  5596. $file = getProp($data, 'file');
  5597. $content = getProp($data, 'content', '');
  5598. $bid = getProp($data, 'bid', 0);
  5599. $script_id = getProp($data, 'script_id', 0);
  5600. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5601. $prompt = getProp($data, 'prompt');
  5602. $user_anime_name = getProp($anime, 'anime_name');
  5603. // 处理文本模型
  5604. $model = getProp($data, 'model');
  5605. if (!$model) {
  5606. // 用户没有输入,从anime表获取
  5607. $model = getProp($anime, 'model');
  5608. if (!$model) {
  5609. // anime表也没有,使用默认值
  5610. $model = 'doubao-seed-2-0-mini-260215';
  5611. }
  5612. }
  5613. // 验证模型是否在可用模型表中
  5614. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5615. $model = 'doubao-seed-2-0-mini-260215';
  5616. }
  5617. $is_multi = getProp($anime, 'is_multi');
  5618. $is_single = (int)$is_multi !== 1;
  5619. // 积分余额预检(仅单剧集模式收费)
  5620. if ($is_single) {
  5621. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5622. }
  5623. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5624. if ($prompt) {
  5625. $question .= "本次修改要求如下:\n{$prompt}";
  5626. }
  5627. // if (!$file && !$content && !$bid) {
  5628. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5629. // }
  5630. // 提取文件内容
  5631. if ($file) {
  5632. $content = $this->extractFileContent($file);
  5633. if (!$content) {
  5634. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5635. }
  5636. } elseif ($script_id) {
  5637. $content = $this->getContentByScriptId($script_id);
  5638. if (!$content) {
  5639. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5640. }
  5641. } elseif ($bid) {
  5642. $content = $this->getContentByBid($bid);
  5643. if (!$content) {
  5644. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5645. }
  5646. } elseif ($content) {
  5647. $content = filterContent($content);
  5648. } else {
  5649. $content = getProp($anime, 'content');
  5650. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5651. $need_generate_content = true;
  5652. }
  5653. }
  5654. // 美术风格
  5655. $input_art_style = getProp($data, 'art_style');
  5656. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5657. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5658. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5659. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5660. 中年女:邻居阿姨
  5661. 老年男:幽默大爷
  5662. 老年女:婆婆
  5663. 萌娃:奶气萌娃";
  5664. // 判断是否需要生成原文内容
  5665. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5666. // 如果需要生成原文内容,添加额外的要求
  5667. $content_generation_requirement = $need_generate_content
  5668. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5669. : "";
  5670. // 美术风格
  5671. if (!$mappedArtStyle) {
  5672. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5673. }else {
  5674. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5675. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5676. }else {
  5677. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5678. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5679. }
  5680. }
  5681. $systemPrompt = $is_single
  5682. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5683. 强制要求:
  5684. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5685. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5686. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5687. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5688. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5689. 普通要求:
  5690. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5691. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5692. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5693. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5694. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5695. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5696. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5697. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5698. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5699. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5700. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5701. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5702. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5703. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5704. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5705. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5706. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5707. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5708. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5709. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5710. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5711. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5712. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5713. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5714. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5715. 5.{$mappedArtStyle_prompt}\n\n
  5716. 示例如下:\n
  5717. ###剧本名:西昆仑
  5718. ###故事梗概
  5719. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5720. ###剧本亮点
  5721. 亮点1:绝境奇药,生死一线
  5722. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5723. 亮点2:结拜兄妹,化解尴尬
  5724. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5725. 亮点3:纤发夺命,情愫暗涌
  5726. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5727. ###人物关系
  5728. 阿雪与梁萧之间存在兄妹之情。
  5729. ###核心矛盾
  5730. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5731. ###主体列表
  5732. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5733. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5734. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5735. 姿态:站立。}{{甜心小美}}
  5736. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5737. 全景,正面拍摄,青年女性,亚洲人。
  5738. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5739. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5740. 姿态:站立。}{{阳光青年}}
  5741. ###美术风格
  5742. 基础画风风格词:厚涂古风
  5743. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5744. ###场景列表
  5745. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5746. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5747. 无人物。}
  5748. ###分镜剧本
  5749. ##第1幕:徐家老旧厨房 白天 室内
  5750. 分镜1
  5751. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5752. 场景:徐家老旧厨房
  5753. 构图设计:全景,低角度仰视
  5754. 运镜调度:手持拍摄
  5755. 配音角色:旁白
  5756. 出镜角色:许芸-校服装、徐母
  5757. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5758. 画面类型:普通画面
  5759. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5760. 分镜2
  5761. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5762. 场景:徐家老旧厨房
  5763. 构图设计:近景,徐母面部特写
  5764. 运镜调度:固定镜头
  5765. 配音角色:徐母
  5766. 出镜角色:徐母
  5767. 台词内容:问我夜不归宿死哪儿去了。
  5768. 画面类型:对口型
  5769. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5770. ##第2幕:徐家简陋客厅 黄昏 室内
  5771. 分镜3
  5772. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5773. 场景:徐家简陋客厅
  5774. 构图设计:全景,景深虚化
  5775. 运镜调度:固定镜头
  5776. 配音角色:旁白
  5777. 出镜角色:无
  5778. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5779. 画面类型:普通画面
  5780. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5781. 分镜4
  5782. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5783. 场景:徐家简陋客厅
  5784. 构图设计:特写,火车票
  5785. 运镜调度:固定镜头
  5786. 配音角色:旁白
  5787. 出镜角色:无
  5788. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5789. 画面类型:普通画面
  5790. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5791. "
  5792. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5793. 强制要求:\n
  5794. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5795. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5796. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5797. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5798. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5799. 普通要求:\n
  5800. 1.剧本名(必须生成)必须与文档内容高度相关
  5801. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5802. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5803. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5804. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5805. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5806. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5807. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5808. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5809. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5810. 4.{$mappedArtStyle_prompt}\n\n
  5811. 示例如下:\n
  5812. ###剧本名:西昆仑
  5813. ###故事梗概
  5814. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5815. ###剧本亮点
  5816. 亮点1:绝境奇药,生死一线
  5817. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5818. 亮点2:结拜兄妹,化解尴尬
  5819. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5820. 亮点3:纤发夺命,情愫暗涌
  5821. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5822. ###人物关系
  5823. 阿雪与梁萧之间存在兄妹之情。
  5824. ###核心矛盾
  5825. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5826. ###主体列表
  5827. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5828. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5829. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5830. 姿态:站立。}{{甜心小美}}
  5831. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5832. 全景,正面拍摄,青年女性,亚洲人。
  5833. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5834. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5835. 姿态:站立。}{{阳光青年}}
  5836. ###美术风格
  5837. 基础画风风格词:厚涂古风
  5838. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5839. ###场景列表
  5840. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5841. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5842. 无人物。}";
  5843. // 构建消息
  5844. $messages = [
  5845. [
  5846. 'role' => 'system',
  5847. 'content' => $systemPrompt
  5848. ],
  5849. [
  5850. 'role' => 'user',
  5851. 'content' => "以下是文档内容:
  5852. {$content}
  5853. 用户问题:
  5854. {$question}"
  5855. ]
  5856. ];
  5857. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5858. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5859. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5860. if ($model === 'deepseek-chat') {
  5861. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5862. $model = 'deepseek-v4-flash';
  5863. $thinkingMode = 'disabled';
  5864. } elseif ($model === 'deepseek-reasoner') {
  5865. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5866. $model = 'deepseek-v4-flash';
  5867. $thinkingMode = 'enabled';
  5868. }
  5869. $post_data = [
  5870. 'model' => $model,
  5871. 'messages' => $messages,
  5872. // 'max_tokens' => 8192,
  5873. 'temperature' => 0.7,
  5874. 'frequency_penalty' => 0,
  5875. 'presence_penalty' => 0,
  5876. 'response_format' => ['type' => 'text'],
  5877. 'thinking' => ['type'=>$thinkingMode],
  5878. 'stream' => true // 启用流式输出
  5879. ];
  5880. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5881. // 根据模型类型选择调用方法
  5882. $fullContent = '';
  5883. $fullReasoningContent = '';
  5884. $usage = [];
  5885. try {
  5886. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5887. // 验证返回值类型
  5888. if (!is_iterable($streamGenerator)) {
  5889. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5890. dLog('deepseek')->error('addChat流式生成器无效', [
  5891. 'generator_type' => $errorType,
  5892. 'model' => $model,
  5893. 'anime_id' => $anime_id
  5894. ]);
  5895. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5896. 'type' => $errorType,
  5897. 'model' => $model
  5898. ]);
  5899. yield [
  5900. 'type' => 'error',
  5901. 'script' => [],
  5902. 'episode' => [],
  5903. 'answer' => '',
  5904. 'reasoning' => '',
  5905. 'usage' => [],
  5906. 'error' => '接口返回数据异常,请重新请求'
  5907. ];
  5908. return;
  5909. }
  5910. // 处理流式输出
  5911. foreach ($streamGenerator as $chunk) {
  5912. if (isset($chunk['type'])) {
  5913. if ($chunk['type'] === 'done') {
  5914. // 最终结果
  5915. $fullContent = $chunk['full_content'];
  5916. $fullReasoningContent = $chunk['full_reasoning'];
  5917. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5918. } else {
  5919. // 逐块yield数据
  5920. yield $chunk;
  5921. }
  5922. }
  5923. }
  5924. } catch (\Exception $e) {
  5925. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5926. 'model' => $model,
  5927. 'anime_id' => $anime_id,
  5928. 'trace' => $e->getTraceAsString()
  5929. ]);
  5930. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5931. 'error' => $e->getMessage(),
  5932. 'model' => $model
  5933. ]);
  5934. yield [
  5935. 'type' => 'error',
  5936. 'script' => [],
  5937. 'episode' => [],
  5938. 'answer' => '',
  5939. 'reasoning' => '',
  5940. 'usage' => [],
  5941. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5942. ];
  5943. return;
  5944. }
  5945. dLog('deepseek')->info('完整内容: '.$fullContent);
  5946. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5947. // 处理完整内容并返回最终结果
  5948. $script_arr = [];
  5949. if ($fullContent) {
  5950. $script_arr = handleScriptContent($fullContent);
  5951. dLog('deepseek')->info('解析内容', $script_arr);
  5952. logDB('deepseek', 'info', '解析内容', $script_arr);
  5953. }
  5954. if (empty($script_arr['roles'])) {
  5955. // 未生成剧本相关内容,保存对话记录并返回提示
  5956. dLog('deepseek')->info('未生成剧本相关的内容');
  5957. try {
  5958. DB::beginTransaction();
  5959. $now = date('Y-m-d H:i:s');
  5960. // 保存对话记录
  5961. $records = [
  5962. [
  5963. 'uid' => $uid,
  5964. 'anime_id' => $anime_id,
  5965. 'sequence' => 0,
  5966. 'role' => 'user',
  5967. 'content' => $prompt,
  5968. 'created_at' => $now,
  5969. 'updated_at' => $now
  5970. ],
  5971. [
  5972. 'uid' => $uid,
  5973. 'anime_id' => $anime_id,
  5974. 'sequence' => 0,
  5975. 'role' => 'assistant',
  5976. // 'content' => $fullContent,
  5977. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5978. 'created_at' => $now,
  5979. 'updated_at' => $now
  5980. ]
  5981. ];
  5982. DB::table('mp_anime_records')->insert($records);
  5983. DB::commit();
  5984. } catch (\Exception $e) {
  5985. DB::rollBack();
  5986. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5987. }
  5988. yield [
  5989. 'type' => 'done',
  5990. 'script' => [],
  5991. 'episode' => [],
  5992. 'answer' => $fullContent,
  5993. 'reasoning' => $fullReasoningContent,
  5994. 'usage' => $usage,
  5995. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5996. ];
  5997. return;
  5998. }
  5999. // 如果需要生成原文内容,从script_arr中提取
  6000. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6001. $content = $script_arr['content'];
  6002. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6003. if (!$content) {
  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. }
  6016. // 替换美术风格
  6017. if ($mappedArtStyle !== '') {
  6018. $script_arr['art_style'] = $mappedArtStyle;
  6019. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6020. }
  6021. // 新建动漫
  6022. if ($user_anime_name == '新剧本策划') {
  6023. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6024. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6025. // if (!$anime_name) {
  6026. // // 未识别到剧本名,保存对话记录并返回提示
  6027. // dLog('deepseek')->info('未能识别到剧本名称');
  6028. // try {
  6029. // DB::beginTransaction();
  6030. // $now = date('Y-m-d H:i:s');
  6031. // // 保存对话记录
  6032. // $records = [
  6033. // [
  6034. // 'uid' => $uid,
  6035. // 'anime_id' => $anime_id,
  6036. // 'sequence' => 0,
  6037. // 'role' => 'user',
  6038. // 'content' => $prompt,
  6039. // 'created_at' => $now,
  6040. // 'updated_at' => $now
  6041. // ],
  6042. // [
  6043. // 'uid' => $uid,
  6044. // 'anime_id' => $anime_id,
  6045. // 'sequence' => 0,
  6046. // 'role' => 'assistant',
  6047. // 'content' => '未能生成剧本名称,请重试',
  6048. // 'created_at' => $now,
  6049. // 'updated_at' => $now
  6050. // ]
  6051. // ];
  6052. // DB::table('mp_anime_records')->insert($records);
  6053. // DB::commit();
  6054. // } catch (\Exception $e) {
  6055. // DB::rollBack();
  6056. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6057. // }
  6058. // yield [
  6059. // 'type' => 'done',
  6060. // 'script' => [],
  6061. // 'episode' => [],
  6062. // 'answer' => $fullContent,
  6063. // 'reasoning' => $fullReasoningContent,
  6064. // 'usage' => $usage,
  6065. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6066. // ];
  6067. // return;
  6068. // }
  6069. // 确认对话名称唯一性
  6070. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6071. $anime_name = $anime_name . '_' . date('YmdHis');
  6072. }
  6073. }else {
  6074. $anime_name = $user_anime_name;
  6075. }
  6076. $table_data = [
  6077. 'user_id' => $uid,
  6078. 'anime_name' => $anime_name,
  6079. 'model' => $model,
  6080. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6081. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6082. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6083. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6084. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6085. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6086. 'art_style_type' => $input_art_style,
  6087. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6088. 'status' => '解析完成',
  6089. 'content' => $content,
  6090. 'is_multi' => $is_multi,
  6091. 'ace_mode' => $ace_mode,
  6092. 'generate_status' => '待执行',
  6093. 'updated_at' => date('Y-m-d H:i:s')
  6094. ];
  6095. if ($table_data['content']) {
  6096. $chapters = splitContent($table_data['content']);
  6097. $chapter_count = count($chapters);
  6098. if ($chapter_count > 0) {
  6099. $table_data['start_episode_sequence'] = 1;
  6100. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6101. }
  6102. }
  6103. // 如果有剧本ID则进行绑定
  6104. if ($script_id) {
  6105. $table_data['script_id'] = $script_id;
  6106. }
  6107. $single_episode = [];
  6108. try {
  6109. DB::beginTransaction();
  6110. $now = date('Y-m-d H:i:s');
  6111. // 更新动漫大纲
  6112. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6113. if (!$boolen) {
  6114. dLog('deepseek')->info('动漫保存失败', $table_data);
  6115. Utils::throwError('20003:动漫保存失败');
  6116. }
  6117. // 保存对话记录
  6118. $records = [
  6119. [
  6120. 'uid' => $uid,
  6121. 'anime_id' => $anime_id,
  6122. 'sequence' => 0,
  6123. 'role' => 'user',
  6124. 'content' => $prompt,
  6125. 'created_at' => date('Y-m-d H:i:s'),
  6126. 'updated_at' => date('Y-m-d H:i:s')
  6127. ],
  6128. [
  6129. 'uid' => $uid,
  6130. 'anime_id' => $anime_id,
  6131. 'sequence' => 0,
  6132. 'role' => 'assistant',
  6133. 'content' => $fullContent,
  6134. 'created_at' => date('Y-m-d H:i:s'),
  6135. 'updated_at' => date('Y-m-d H:i:s')
  6136. ]
  6137. ];
  6138. // 保存对话记录
  6139. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6140. if (!$boolen3) {
  6141. Utils::throwError('20003:对话记录保存失败');
  6142. }
  6143. if ($is_single) {
  6144. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6145. if (empty($episode_arr['acts'])) {
  6146. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6147. }
  6148. $saveResult = $this->saveEpisodeVersionData(
  6149. $anime_id,
  6150. 1,
  6151. $episode_arr,
  6152. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6153. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6154. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6155. null,
  6156. null,
  6157. false,
  6158. $content,
  6159. $now
  6160. );
  6161. $single_episode = $saveResult['episode'];
  6162. $episode_id = $saveResult['episode_id'];
  6163. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6164. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6165. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6166. 'props' => json_encode($saveResult['merged_props'], 256),
  6167. 'updated_at' => $now
  6168. ]);
  6169. if ($boolen5 === false) {
  6170. Utils::throwError('20003:单剧集主表资源同步失败');
  6171. }
  6172. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6173. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6174. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6175. $episode_record_content = '确认分镜大纲';
  6176. if ($content !== '') {
  6177. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6178. }
  6179. $episode_records = [
  6180. [
  6181. 'uid' => $uid,
  6182. 'anime_id' => $anime_id,
  6183. 'role' => 'user',
  6184. 'content' => $episode_record_content,
  6185. 'sequence' => 1,
  6186. 'episode_id' => $episode_id,
  6187. 'created_at' => $now,
  6188. 'updated_at' => $now
  6189. ],
  6190. [
  6191. 'uid' => $uid,
  6192. 'anime_id' => $anime_id,
  6193. 'role' => 'assistant',
  6194. 'content' => $fullContent,
  6195. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6196. 'sequence' => 1,
  6197. 'episode_id' => $episode_id,
  6198. 'created_at' => $now,
  6199. 'updated_at' => $now
  6200. ]
  6201. ];
  6202. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6203. if (!$boolen4) {
  6204. Utils::throwError('20003:单剧集分镜记录保存失败');
  6205. }
  6206. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6207. if ($is_single && !empty($single_episode)) {
  6208. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6209. 'anime_id' => $anime_id,
  6210. 'episode_id' => $episode_id ?? 0,
  6211. 'model' => $model,
  6212. 'source' => 'addChat',
  6213. ]);
  6214. }
  6215. }
  6216. }catch (\Exception $e) {
  6217. DB::rollBack();
  6218. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6219. yield [
  6220. 'type' => 'done',
  6221. 'answer' => $fullContent,
  6222. 'reasoning' => $fullReasoningContent,
  6223. 'usage' => $usage,
  6224. 'error' => $e->getMessage(),
  6225. ];
  6226. return;
  6227. }
  6228. DB::commit();
  6229. dLog('deepseek')->info('保存完毕');
  6230. if ($is_single && !empty($single_episode)) {
  6231. // $this->batchSetGlobalRoleImg([
  6232. // 'anime_id' => $anime_id,
  6233. // ]);
  6234. // $this->batchSetGlobalSceneImg([
  6235. // 'anime_id' => $anime_id,
  6236. // ]);
  6237. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6238. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6239. }
  6240. $table_data['anime_id'] = $anime_id;
  6241. $table_data['roles'] = json_decode($table_data['roles'], true);
  6242. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6243. // $table_data['episodes'] = $script_arr['episodes'];
  6244. unset($table_data['created_at']);
  6245. unset($table_data['updated_at']);
  6246. unset($table_data['status']);
  6247. dLog('deepseek')->info('开始返回');
  6248. yield [
  6249. 'type' => 'done',
  6250. 'script' => $table_data,
  6251. 'episode' => $single_episode,
  6252. 'answer' => $fullContent,
  6253. 'reasoning' => $fullReasoningContent,
  6254. 'usage' => $usage
  6255. ];
  6256. }
  6257. public function reGenerateAnime($data) {
  6258. $uid = Site::getUid();
  6259. $file = getProp($data, 'file');
  6260. $content = getProp($data, 'content', '');
  6261. $bid = getProp($data, 'bid', 0);
  6262. $script_id = getProp($data, 'script_id', 0);
  6263. $anime_id = getProp($data, 'anime_id');
  6264. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6265. if (!$anime) {
  6266. Utils::throwError('20003:该对话不存在');
  6267. }
  6268. $user_anime_name = getProp($anime, 'anime_name');
  6269. $prompt = getProp($data, 'prompt');
  6270. // 处理文本模型
  6271. $model = getProp($data, 'model');
  6272. if (!$model) {
  6273. // 用户没有输入,从anime表获取
  6274. $model = getProp($anime, 'model');
  6275. if (!$model) {
  6276. // anime表也没有,使用默认值
  6277. $model = 'doubao-seed-2-0-mini-260215';
  6278. }
  6279. }
  6280. // 验证模型是否在可用模型表中
  6281. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6282. $model = 'doubao-seed-2-0-mini-260215';
  6283. }
  6284. $is_multi = getProp($anime, 'is_multi', 1);
  6285. $is_single = (int)$is_multi !== 1;
  6286. // 积分余额预检(仅单剧集模式收费)
  6287. if ($is_single) {
  6288. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6289. }
  6290. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6291. if ($is_single) {
  6292. $episode_exists = DB::table('mp_anime_episodes')
  6293. ->where('anime_id', $anime_id)
  6294. ->where('sequence', 1)
  6295. ->exists();
  6296. if ($episode_exists) {
  6297. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6298. }
  6299. }
  6300. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  6301. if ($prompt) {
  6302. $question .= "本次修改要求如下:\n{$prompt}";
  6303. }
  6304. // 提取文件内容
  6305. if ($file) {
  6306. $content = $this->extractFileContent($file);
  6307. if (!$content) {
  6308. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6309. }
  6310. } elseif ($script_id) {
  6311. $content = $this->getContentByScriptId($script_id);
  6312. if (!$content) {
  6313. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6314. }
  6315. } elseif ($bid) {
  6316. $content = $this->getContentByBid($bid);
  6317. if (!$content) {
  6318. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6319. }
  6320. } elseif ($content) {
  6321. $content = filterContent($content);
  6322. }else {
  6323. $content = filterContent(getProp($anime, 'content'));
  6324. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6325. $need_generate_content = true;
  6326. }
  6327. }
  6328. // 判断是否需要生成原文内容
  6329. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6330. // 如果需要生成原文内容,添加额外的要求
  6331. $content_generation_requirement = $need_generate_content
  6332. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6333. : "";
  6334. // 美术风格
  6335. $input_art_style = getProp($anime, 'art_style');
  6336. if (!$input_art_style) {
  6337. $input_art_style = getProp($data, 'art_style');
  6338. }
  6339. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6340. // 美术风格
  6341. if (!$mappedArtStyle) {
  6342. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6343. }else {
  6344. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6345. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6346. }else {
  6347. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6348. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6349. }
  6350. }
  6351. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6352. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6353. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6354. 中年女:邻居阿姨
  6355. 老年男:幽默大爷
  6356. 老年女:婆婆
  6357. 萌娃:奶气萌娃";
  6358. $system_message = ['role'=>'system', 'content'=>$is_single
  6359. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6360. 强制要求:
  6361. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6362. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6363. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6364. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6365. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6366. 普通要求:
  6367. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6368. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6369. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6370. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6371. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6372. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6373. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6374. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6375. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6376. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6377. 3.$mappedArtStyle_prompt\n\n
  6378. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6379. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6380. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6381. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6382. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  6383. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6384. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6385. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6386. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6387. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6388. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6389. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6390. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6391. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6392. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  6393. 示例如下:\n
  6394. ###剧本名:西昆仑
  6395. ###故事梗概
  6396. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6397. ###剧本亮点
  6398. 亮点1:绝境奇药,生死一线
  6399. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6400. 亮点2:结拜兄妹,化解尴尬
  6401. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6402. 亮点3:纤发夺命,情愫暗涌
  6403. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6404. ###人物关系
  6405. 阿雪与梁萧之间存在兄妹之情。
  6406. ###核心矛盾
  6407. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6408. ###主体列表
  6409. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6410. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6411. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6412. 姿态:站立。}{{甜心小美}}
  6413. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6414. 全景,正面拍摄,青年女性,亚洲人。
  6415. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6416. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6417. 姿态:站立。}{{阳光青年}}
  6418. ###美术风格
  6419. 基础画风风格词:厚涂古风
  6420. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6421. ###场景列表
  6422. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6423. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6424. 无人物。}
  6425. ###分镜剧本
  6426. ##第1幕:徐家老旧厨房 白天 室内
  6427. 分镜1
  6428. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6429. 场景:徐家老旧厨房
  6430. 构图设计:全景,低角度仰视
  6431. 运镜调度:手持拍摄
  6432. 配音角色:旁白
  6433. 出镜角色:许芸-校服装、徐母
  6434. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6435. 画面类型:普通画面
  6436. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6437. 分镜2
  6438. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6439. 场景:徐家老旧厨房
  6440. 构图设计:近景,徐母面部特写
  6441. 运镜调度:固定镜头
  6442. 配音角色:徐母
  6443. 出镜角色:徐母
  6444. 台词内容:问我夜不归宿死哪儿去了。
  6445. 画面类型:对口型
  6446. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6447. ##第2幕:徐家简陋客厅 黄昏 室内
  6448. 分镜3
  6449. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6450. 场景:徐家简陋客厅
  6451. 构图设计:全景,景深虚化
  6452. 运镜调度:固定镜头
  6453. 配音角色:旁白
  6454. 出镜角色:无
  6455. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6456. 画面类型:普通画面
  6457. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6458. 分镜4
  6459. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6460. 场景:徐家简陋客厅
  6461. 构图设计:特写,火车票
  6462. 运镜调度:固定镜头
  6463. 配音角色:旁白
  6464. 出镜角色:无
  6465. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6466. 画面类型:普通画面
  6467. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  6468. "
  6469. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6470. 强制要求:\n
  6471. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6472. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6473. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6474. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6475. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6476. 普通要求:\n
  6477. 1.剧本名(必须生成)必须与文档内容高度相关
  6478. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6479. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6480. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6481. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6482. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6483. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6484. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6485. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6486. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6487. 4.$mappedArtStyle_prompt\n\n
  6488. 示例如下:\n
  6489. ###剧本名:西昆仑
  6490. ###故事梗概
  6491. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6492. ###剧本亮点
  6493. 亮点1:绝境奇药,生死一线
  6494. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6495. 亮点2:结拜兄妹,化解尴尬
  6496. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6497. 亮点3:纤发夺命,情愫暗涌
  6498. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6499. ###人物关系
  6500. 阿雪与梁萧之间存在兄妹之情。
  6501. ###核心矛盾
  6502. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6503. ###主体列表
  6504. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6505. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6506. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6507. 姿态:站立。}{{甜心小美}}
  6508. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6509. 全景,正面拍摄,青年女性,亚洲人。
  6510. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6511. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6512. 姿态:站立。}{{阳光青年}}
  6513. ###美术风格
  6514. 基础画风风格词:厚涂古风
  6515. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6516. ###场景列表
  6517. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6518. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6519. 无人物。}"];
  6520. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6521. $episode_count = $this->extractEpisodeNumber($prompt);
  6522. if ((int)getProp($anime, 'is_multi') !== 1) {
  6523. yield [
  6524. 'type' => 'done',
  6525. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6526. 'reasoning' => '',
  6527. 'usage' => []
  6528. ];
  6529. return;
  6530. }
  6531. if ($episode_count) {
  6532. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6533. $system_message = [
  6534. 'role' => 'system',
  6535. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6536. 强制要求:\n
  6537. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6538. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6539. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6540. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6541. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6542. 普通要求:\n
  6543. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6544. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6545. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6546. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6547. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6548. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6549. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6550. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6551. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6552. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6553. 示例如下:\n
  6554. ###剧本名:西昆仑
  6555. ###故事梗概
  6556. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6557. ###剧本亮点
  6558. 亮点1:绝境奇药,生死一线
  6559. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6560. 亮点2:结拜兄妹,化解尴尬
  6561. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6562. 亮点3:纤发夺命,情愫暗涌
  6563. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6564. ###人物关系
  6565. 阿雪与梁萧之间存在兄妹之情。
  6566. ###核心矛盾
  6567. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6568. ###主体列表
  6569. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6570. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6571. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6572. 姿态:站立。}{{甜心小美}}
  6573. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6574. 全景,正面拍摄,青年女性,亚洲人。
  6575. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6576. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6577. 姿态:站立。}{{阳光青年}}
  6578. ###美术风格
  6579. 基础画风风格词:厚涂古风
  6580. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6581. ###场景列表
  6582. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6583. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6584. 无人物。}
  6585. ###分集详细内容
  6586. ##第1章 重生
  6587. 我重生了。
  6588. 源于一个男人偏执的暗恋。
  6589. ##第2章 相救
  6590. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6591. 我眼睛扫向站在锅炉后的卞大伟。"
  6592. ];
  6593. // 构建消息
  6594. $messages = [
  6595. $system_message,
  6596. [
  6597. 'role' => 'user',
  6598. 'content' => "以下是文档内容:
  6599. {$content}
  6600. 用户问题:
  6601. {$question}"
  6602. ]
  6603. ];
  6604. }else {
  6605. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6606. // 构建消息
  6607. $messages = [
  6608. $system_message,
  6609. [
  6610. 'role' => 'user',
  6611. 'content' => "以下是文档内容:
  6612. {$content}
  6613. 用户问题:
  6614. {$question}"
  6615. ]
  6616. ];
  6617. }else {
  6618. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6619. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6620. return (array)$value;
  6621. })->toArray();
  6622. array_unshift($messages, $system_message);
  6623. $messages[] = [
  6624. 'role' => 'user',
  6625. 'content' => $prompt
  6626. ];
  6627. }
  6628. }
  6629. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6630. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6631. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6632. if ($model === 'deepseek-chat') {
  6633. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6634. $model = 'deepseek-v4-flash';
  6635. $thinkingMode = 'disabled';
  6636. } elseif ($model === 'deepseek-reasoner') {
  6637. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6638. $model = 'deepseek-v4-flash';
  6639. $thinkingMode = 'enabled';
  6640. }
  6641. $post_data = [
  6642. 'model' => $model,
  6643. 'messages' => $messages,
  6644. // 'max_tokens' => 8192,
  6645. 'temperature' => 0.7,
  6646. 'frequency_penalty' => 0,
  6647. 'presence_penalty' => 0,
  6648. 'response_format' => ['type' => 'text'],
  6649. 'thinking' => ['type' => $thinkingMode],
  6650. 'stream' => true // 启用流式输出
  6651. ];
  6652. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6653. // 根据模型类型选择调用方法
  6654. $fullContent = '';
  6655. $fullReasoningContent = '';
  6656. $usage = [];
  6657. // dd($post_data);
  6658. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6659. try {
  6660. $streamGenerator = $this->dispatchStreamByModel($post_data);
  6661. // 验证返回值类型
  6662. if (!is_iterable($streamGenerator)) {
  6663. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6664. dLog('deepseek')->error('方法名流式生成器无效', [
  6665. 'generator_type' => $errorType,
  6666. 'model' => $model,
  6667. // 添加其他上下文信息
  6668. ]);
  6669. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6670. 'type' => $errorType,
  6671. 'model' => $model
  6672. ]);
  6673. yield [
  6674. 'type' => 'error',
  6675. // 根据方法返回相应的空数据结构
  6676. 'answer' => '',
  6677. 'reasoning' => '',
  6678. 'usage' => [],
  6679. 'error' => '接口返回数据异常,请重新请求'
  6680. ];
  6681. return;
  6682. }
  6683. // 处理流式输出
  6684. foreach ($streamGenerator as $chunk) {
  6685. if (isset($chunk['type'])) {
  6686. if ($chunk['type'] === 'done') {
  6687. $fullContent = $chunk['full_content'];
  6688. $fullReasoningContent = $chunk['full_reasoning'];
  6689. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6690. } else {
  6691. yield $chunk;
  6692. }
  6693. }
  6694. }
  6695. } catch (\Exception $e) {
  6696. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6697. 'model' => $model,
  6698. 'trace' => $e->getTraceAsString()
  6699. ]);
  6700. logDB('deepseek', 'error', '方法名流式处理失败', [
  6701. 'error' => $e->getMessage(),
  6702. 'model' => $model
  6703. ]);
  6704. yield [
  6705. 'type' => 'error',
  6706. // 根据方法返回相应的空数据结构
  6707. 'answer' => '',
  6708. 'reasoning' => '',
  6709. 'usage' => [],
  6710. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6711. ];
  6712. return;
  6713. }
  6714. dLog('deepseek')->info('完整内容: '.$fullContent);
  6715. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6716. // 处理完整内容并返回最终结果
  6717. $script_arr = [];
  6718. if ($fullContent) {
  6719. $script_arr = handleScriptContent($fullContent);
  6720. dLog('deepseek')->info('解析内容', $script_arr);
  6721. logDB('deepseek', 'info', '解析内容', $script_arr);
  6722. }
  6723. if (empty($script_arr['roles'])) {
  6724. // 未生成剧本相关内容,保存对话记录并返回提示
  6725. dLog('deepseek')->info('未生成剧本相关的内容');
  6726. try {
  6727. $now = date('Y-m-d H:i:s');
  6728. // 保存对话记录
  6729. $records = [
  6730. [
  6731. 'uid' => $uid,
  6732. 'anime_id' => $anime_id,
  6733. 'sequence' => 0,
  6734. 'role' => 'user',
  6735. 'content' => $prompt,
  6736. 'created_at' => $now,
  6737. 'updated_at' => $now
  6738. ],
  6739. [
  6740. 'uid' => $uid,
  6741. 'anime_id' => $anime_id,
  6742. 'sequence' => 0,
  6743. 'role' => 'assistant',
  6744. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6745. 'created_at' => $now,
  6746. 'updated_at' => $now
  6747. ]
  6748. ];
  6749. DB::table('mp_anime_records')->insert($records);
  6750. } catch (\Exception $e) {
  6751. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6752. }
  6753. yield [
  6754. 'type' => 'done',
  6755. 'script' => [],
  6756. 'episode' => [],
  6757. 'answer' => $fullContent,
  6758. 'reasoning' => $fullReasoningContent,
  6759. 'usage' => $usage,
  6760. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6761. ];
  6762. return;
  6763. }
  6764. // 替换美术风格
  6765. if ($mappedArtStyle !== '') {
  6766. $script_arr['art_style'] = $mappedArtStyle;
  6767. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6768. }
  6769. if ($user_anime_name != '新剧本策划') {
  6770. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6771. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6772. // 确认对话名称唯一性
  6773. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6774. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6775. }
  6776. }else {
  6777. $anime_name = $user_anime_name;
  6778. }
  6779. $table_data = [
  6780. 'user_id' => $uid,
  6781. 'model' => $model,
  6782. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6783. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6784. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6785. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6786. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6787. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6788. 'art_style_type' => $input_art_style,
  6789. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6790. 'status' => '解析完成',
  6791. 'generate_status' => '待执行',
  6792. 'updated_at' => date('Y-m-d H:i:s')
  6793. ];
  6794. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6795. // 如果是修改集数,则将content内容更新(会改变原文)
  6796. if (isset($episode_count) && $episode_count > 0) {
  6797. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6798. $table_data['start_episode_sequence'] = 1;
  6799. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6800. }else {
  6801. // 如果需要生成原文内容,从script_arr中提取
  6802. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6803. $table_data['content'] = $script_arr['content'];
  6804. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6805. if (!$table_data['content']) {
  6806. yield [
  6807. 'type' => 'done',
  6808. 'script' => [],
  6809. 'episode' => [],
  6810. 'answer' => $fullContent,
  6811. 'reasoning' => $fullReasoningContent,
  6812. 'usage' => $usage,
  6813. 'error' => '未生成剧本内容,请调整提示词再试'
  6814. ];
  6815. return;
  6816. }
  6817. }
  6818. if (isset($table_data['content']) && $table_data['content']) {
  6819. $chapters = splitContent($table_data['content']);
  6820. $chapter_count = count($chapters);
  6821. if ($chapter_count > 0) {
  6822. $table_data['start_episode_sequence'] = 1;
  6823. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6824. }
  6825. }
  6826. }
  6827. $single_episode = [];
  6828. try {
  6829. DB::beginTransaction();
  6830. $now = date('Y-m-d H:i:s');
  6831. // 更新动漫大纲
  6832. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6833. if (!$boolen) {
  6834. dLog('deepseek')->info('对话修改失败', $table_data);
  6835. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6836. Utils::throwError('20003:对话修改失败');
  6837. }
  6838. // 保存对话记录
  6839. $records = [
  6840. [
  6841. 'uid' => $uid,
  6842. 'anime_id' => $anime_id,
  6843. 'sequence' => 0,
  6844. 'role' => 'user',
  6845. 'content' => $prompt,
  6846. 'created_at' => $now,
  6847. 'updated_at' => $now
  6848. ],
  6849. [
  6850. 'uid' => $uid,
  6851. 'anime_id' => $anime_id,
  6852. 'sequence' => 0,
  6853. 'role' => 'assistant',
  6854. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6855. 'content' => $fullContent,
  6856. 'created_at' => $now,
  6857. 'updated_at' => $now
  6858. ]
  6859. ];
  6860. // 保存对话记录
  6861. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6862. if (!$boolen3) {
  6863. Utils::throwError('20003:对话记录保存失败');
  6864. }
  6865. // 单剧集模式:生成并保存剧集信息
  6866. if ($is_single) {
  6867. $anime_name = getProp($anime, 'anime_name', '未命名');
  6868. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6869. if (empty($episode_arr['acts'])) {
  6870. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6871. }
  6872. $saveResult = $this->saveEpisodeVersionData(
  6873. $anime_id,
  6874. 1,
  6875. $episode_arr,
  6876. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6877. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6878. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6879. null,
  6880. null,
  6881. false,
  6882. $content,
  6883. $now
  6884. );
  6885. $single_episode = $saveResult['episode'];
  6886. $episode_id = $saveResult['episode_id'];
  6887. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6888. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6889. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6890. 'props' => json_encode($saveResult['merged_props'], 256),
  6891. 'updated_at' => $now
  6892. ]);
  6893. if ($boolen5 === false) {
  6894. Utils::throwError('20003:单剧集主表资源同步失败');
  6895. }
  6896. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6897. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6898. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6899. $episode_record_content = '确认分镜大纲';
  6900. if ($content !== '') {
  6901. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6902. }
  6903. $episode_records = [
  6904. [
  6905. 'uid' => $uid,
  6906. 'anime_id' => $anime_id,
  6907. 'role' => 'user',
  6908. 'content' => $episode_record_content,
  6909. 'sequence' => 1,
  6910. 'episode_id' => $episode_id,
  6911. 'created_at' => $now,
  6912. 'updated_at' => $now
  6913. ],
  6914. [
  6915. 'uid' => $uid,
  6916. 'anime_id' => $anime_id,
  6917. 'role' => 'assistant',
  6918. 'content' => $fullContent,
  6919. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6920. 'sequence' => 1,
  6921. 'episode_id' => $episode_id,
  6922. 'created_at' => $now,
  6923. 'updated_at' => $now
  6924. ]
  6925. ];
  6926. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6927. if (!$boolen4) {
  6928. Utils::throwError('20003:单剧集分镜记录保存失败');
  6929. }
  6930. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6931. if ($is_single && !empty($single_episode)) {
  6932. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6933. 'anime_id' => $anime_id,
  6934. 'episode_id' => $episode_id ?? 0,
  6935. 'model' => $model,
  6936. 'source' => 'reGenerateAnime',
  6937. ]);
  6938. }
  6939. }
  6940. }catch (\Exception $e) {
  6941. DB::rollBack();
  6942. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6943. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6944. yield [
  6945. 'type' => 'done',
  6946. 'answer' => $fullContent,
  6947. 'reasoning' => $fullReasoningContent,
  6948. 'usage' => $usage,
  6949. 'error' => $e->getMessage(),
  6950. ];
  6951. return;
  6952. }
  6953. DB::commit();
  6954. dLog('deepseek')->info('保存完毕');
  6955. if ($is_single && !empty($single_episode)) {
  6956. // $this->batchSetGlobalRoleImg([
  6957. // 'anime_id' => $anime_id,
  6958. // ]);
  6959. // $this->batchSetGlobalSceneImg([
  6960. // 'anime_id' => $anime_id,
  6961. // ]);
  6962. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6963. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6964. }
  6965. $table_data['anime_id'] = $anime_id;
  6966. $table_data['roles'] = json_decode($table_data['roles'], true);
  6967. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6968. unset($table_data['updated_at']);
  6969. unset($table_data['status']);
  6970. yield [
  6971. 'type' => 'done',
  6972. 'script' => $table_data,
  6973. 'episode' => $single_episode,
  6974. 'answer' => $fullContent,
  6975. 'reasoning' => $fullReasoningContent,
  6976. 'usage' => $usage
  6977. ];
  6978. }
  6979. public function chat($data) {
  6980. $uid = Site::getUid();
  6981. // 积分余额预检(不足直接报错)
  6982. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6983. $anime_id = getProp($data, 'anime_id');
  6984. $file = getProp($data, 'file');
  6985. $content = getProp($data, 'content', '');
  6986. $bid = getProp($data, 'bid', 0);
  6987. $script_id = getProp($data, 'script_id', 0);
  6988. $episode_number = getProp($data, 'episode_number', 1);
  6989. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6990. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6991. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6992. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6993. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6994. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6995. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6996. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6997. $roles = is_array($roles) ? $roles : [];
  6998. $scenes = is_array($scenes) ? $scenes : [];
  6999. // 获取最后一集序号
  7000. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  7001. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7002. // 转换主体列表和场景列表的格式
  7003. // 获取参考主体或场景
  7004. if ((int)$episode_number === 1) {
  7005. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7006. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7007. }else {
  7008. $prev_episode_number = $episode_number - 1;
  7009. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7010. }
  7011. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7012. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7013. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7014. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7015. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  7016. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  7017. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  7018. 中年女:邻居阿姨
  7019. 老年男:幽默大爷
  7020. 老年女:婆婆
  7021. 萌娃:奶气萌娃";
  7022. if ($roles_content) {
  7023. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7024. 主体范围:\n {$roles_content}\n
  7025. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7026. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7027. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7028. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7029. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7030. }else {
  7031. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7032. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7033. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7034. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7035. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7036. }
  7037. if ($scenes_content) {
  7038. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7039. 场景范围:\n {$scenes_content}\n
  7040. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7041. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7042. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7043. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7044. }else {
  7045. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7046. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7047. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7048. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7049. }
  7050. // 提取文件内容
  7051. if ($file) {
  7052. $uploaded_content = $this->extractFileContent($file);
  7053. if (!$uploaded_content) {
  7054. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7055. }
  7056. } elseif ($script_id) {
  7057. $uploaded_content = $this->getContentByScriptId($script_id);
  7058. if (!$uploaded_content) {
  7059. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7060. }
  7061. } elseif ($bid) {
  7062. $uploaded_content = $this->getContentByBid($bid);
  7063. if (!$uploaded_content) {
  7064. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7065. }
  7066. } elseif ($content) {
  7067. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7068. }
  7069. // elseif ($prompt) {
  7070. // $uploaded_content = filterContent($prompt);
  7071. // }
  7072. else {
  7073. $uploaded_content = '';
  7074. }
  7075. $input_art_style = getProp($anime, 'art_style');
  7076. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7077. // 美术风格
  7078. if (!$mappedArtStyle) {
  7079. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7080. }else {
  7081. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7082. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7083. }else {
  7084. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7085. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7086. }
  7087. }
  7088. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7089. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7090. // 强制要求:
  7091. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7092. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7093. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7094. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7095. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  7096. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  7097. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7098. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7099. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7100. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7101. // - 分镜要和场景列表、人物主体保持一致\n
  7102. // 普通要求:
  7103. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7104. // {$role_demo}
  7105. // {$scene_demo}
  7106. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7107. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7108. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7109. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  7110. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7111. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7112. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7113. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7114. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7115. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7116. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7117. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7118. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7119. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7120. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7121. // 5.$mappedArtStyle_prompt\n\n
  7122. // 示例格式:\n
  7123. // 第1集:隐形的守护者
  7124. // ###故事梗概
  7125. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7126. // ###美术风格
  7127. // 基础画风风格词:韩漫二次元
  7128. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7129. // ###主体列表
  7130. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7131. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7132. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7133. // ###场景列表
  7134. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7135. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7136. // 无人物。}
  7137. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7138. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7139. // 无人物。}
  7140. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7141. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7142. // 无人物。}
  7143. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7144. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7145. // 无人物。}
  7146. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7147. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7148. // 无人物。}
  7149. // ###分镜剧本
  7150. // ##第1幕:徐家老旧厨房 白天 室内
  7151. // 分镜1
  7152. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7153. // 场景:徐家老旧厨房
  7154. // 构图设计:全景,低角度仰视
  7155. // 运镜调度:手持拍摄
  7156. // 配音角色:旁白
  7157. // 出镜角色:许芸-校服装、徐母
  7158. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7159. // 画面类型:普通画面
  7160. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7161. // 分镜2
  7162. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7163. // 场景:徐家老旧厨房
  7164. // 构图设计:近景,徐母面部特写
  7165. // 运镜调度:固定镜头
  7166. // 配音角色:徐母
  7167. // 出镜角色:徐母
  7168. // 台词内容:问我夜不归宿死哪儿去了。
  7169. // 画面类型:对口型
  7170. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7171. // ##第2幕:徐家简陋客厅 黄昏 室内
  7172. // 分镜3
  7173. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7174. // 场景:徐家简陋客厅
  7175. // 构图设计:全景,景深虚化
  7176. // 运镜调度:固定镜头
  7177. // 配音角色:旁白
  7178. // 出镜角色:无
  7179. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7180. // 画面类型:普通画面
  7181. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7182. // 分镜4
  7183. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7184. // 场景:徐家简陋客厅
  7185. // 构图设计:特写,火车票
  7186. // 运镜调度:固定镜头
  7187. // 配音角色:旁白
  7188. // 出镜角色:无
  7189. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7190. // 画面类型:普通画面
  7191. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7192. // \n\n";
  7193. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7194. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7195. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  7196. 普通要求:
  7197. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7198. {$role_demo}
  7199. {$scene_demo}
  7200. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7201. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7202. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7203. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7204. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7205. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7206. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7207. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7208. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7209. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7210. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7211. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7212. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7213. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7214. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7215. 5.$mappedArtStyle_prompt
  7216. 6.《情绪-视听语言映射表》:
  7217. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7218. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7219. -----|---------|------------|----------------
  7220. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7221. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7222. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7223. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7224. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7225. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7226. -----|---------|------------|----------------
  7227. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7228. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7229. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7230. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7231. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7232. --------|---------|--------------|-------------
  7233. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7234. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7235. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7236. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7237. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7238. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7239. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7240. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7241. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7242. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7243. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7244. -----|---------|------------|------------
  7245. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7246. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7247. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7248. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7249. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7250. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7251. --------|---------|--------------|----------
  7252. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7253. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7254. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7255. 6.6 声音设计与潜意识影响 (Soundscape)
  7256. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7257. -----|---------|------------|------------------
  7258. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7259. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7260. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7261. 理论基石:
  7262. - The Five C's of Cinematography by Joseph V. Mascelli
  7263. - Film Art: An Introduction by David Bordwell
  7264. - Sight, Sound, Motion by Herbert Zettl
  7265. - Notes on the Cinematograph by Robert Bresson
  7266. \n\n
  7267. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  7268. 示例格式:\n
  7269. 第1集:隐形的守护者
  7270. ###故事梗概
  7271. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7272. ###美术风格
  7273. 基础画风风格词:韩漫二次元
  7274. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7275. ###主体列表
  7276. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7277. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7278. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7279. ###场景列表
  7280. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7281. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7282. 无人物。}
  7283. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7284. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7285. 无人物。}
  7286. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7287. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7288. 无人物。}
  7289. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7290. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7291. 无人物。}
  7292. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7293. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7294. 无人物。}
  7295. ###分镜剧本
  7296. ##第1幕:徐家老旧厨房 白天 室内
  7297. 分镜1
  7298. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7299. 场景:徐家老旧厨房
  7300. 构图设计:全景,低角度仰视
  7301. 运镜调度:手持拍摄
  7302. 配音角色:旁白
  7303. 出镜角色:许芸-校服装、徐母
  7304. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7305. 画面类型:普通画面
  7306. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7307. 分镜2
  7308. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7309. 场景:徐家老旧厨房
  7310. 构图设计:近景,徐母面部特写
  7311. 运镜调度:固定镜头
  7312. 配音角色:徐母
  7313. 出镜角色:徐母
  7314. 台词内容:问我夜不归宿死哪儿去了。
  7315. 画面类型:对口型
  7316. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7317. ##第2幕:徐家简陋客厅 黄昏 室内
  7318. 分镜3
  7319. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7320. 场景:徐家简陋客厅
  7321. 构图设计:全景,景深虚化
  7322. 运镜调度:固定镜头
  7323. 配音角色:旁白
  7324. 出镜角色:无
  7325. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7326. 画面类型:普通画面
  7327. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7328. 分镜4
  7329. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7330. 场景:徐家简陋客厅
  7331. 构图设计:特写,火车票
  7332. 运镜调度:固定镜头
  7333. 配音角色:旁白
  7334. 出镜角色:无
  7335. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7336. 画面类型:普通画面
  7337. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7338. \n\n";
  7339. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7340. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  7341. $is_regenerate_version = true;
  7342. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7343. $prompt = $origin_prompt;
  7344. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7345. // 获取章节内容
  7346. $full_content = getProp($anime, 'content');
  7347. if ($uploaded_content) {
  7348. $full_content = $uploaded_content;
  7349. }
  7350. // 根据章节内容拆分章节
  7351. $chapters = splitContent($full_content);
  7352. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7353. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7354. $messages = [];
  7355. if ($prompt == '确认分镜大纲') {
  7356. // 暂时保留
  7357. $content = $chapter_content;
  7358. if ($is_single) $content = $full_content; // 单剧集使用全文
  7359. if (!$content) {
  7360. Utils::throwError('20003:章节内容无法获取,请确认');
  7361. }
  7362. $question = $is_single
  7363. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7364. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7365. // 构建消息
  7366. $messages[] =
  7367. [
  7368. 'role' => 'user',
  7369. 'content' => $question
  7370. ];
  7371. }else if ($prompt == '继续策划下一集') {
  7372. if ($is_single) {
  7373. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7374. }
  7375. $content = $chapter_content;
  7376. if (!$content) {
  7377. Utils::throwError('20003:章节内容无法获取,请确认');
  7378. }
  7379. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7380. // 获取上一集最后记录
  7381. $prev_sequence = $episode_number - 1;
  7382. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7383. // 构建消息
  7384. $messages[] =
  7385. [
  7386. 'role' => 'user',
  7387. 'content' => $question
  7388. ];
  7389. }else {
  7390. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7391. if (!$content) {
  7392. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7393. }
  7394. if (!$content) {
  7395. Utils::throwError('20003:章节内容无法获取,请确认');
  7396. }
  7397. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7398. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7399. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7400. if ($origin_prompt) {
  7401. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  7402. }
  7403. $messages[] =
  7404. [
  7405. 'role' => 'user',
  7406. 'content' => $question
  7407. ];
  7408. }
  7409. // 处理文本模型
  7410. $model = getProp($data, 'model');
  7411. if (!$model) {
  7412. // 用户没有输入,从anime表获取
  7413. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7414. $model = getProp($anime, 'model');
  7415. if (!$model) {
  7416. // anime表也没有,使用默认值
  7417. $model = 'doubao-seed-2-0-mini-260215';
  7418. }
  7419. }
  7420. // 验证模型是否在可用模型表中
  7421. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7422. $model = 'doubao-seed-2-0-mini-260215';
  7423. }
  7424. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7425. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7426. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7427. if ($model === 'deepseek-chat') {
  7428. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7429. $model = 'deepseek-v4-flash';
  7430. $thinkingMode = 'disabled';
  7431. } elseif ($model === 'deepseek-reasoner') {
  7432. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7433. $model = 'deepseek-v4-flash';
  7434. $thinkingMode = 'enabled';
  7435. }
  7436. $post_data = [
  7437. 'model' => $model,
  7438. 'messages' => $messages,
  7439. // 'max_tokens' => 8192,
  7440. 'temperature' => 0.2,
  7441. 'frequency_penalty' => 0,
  7442. 'presence_penalty' => 0,
  7443. 'response_format' => ['type' => 'text'],
  7444. 'thinking' => ['type' => $thinkingMode],
  7445. 'stream' => true // 启用流式输出
  7446. ];
  7447. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7448. // 根据模型类型选择调用方法
  7449. $fullContent = '';
  7450. $fullReasoningContent = '';
  7451. $usage = [];
  7452. try {
  7453. $streamGenerator = $this->dispatchStreamByModel($post_data);
  7454. // 验证返回值类型
  7455. if (!is_iterable($streamGenerator)) {
  7456. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7457. dLog('deepseek')->error('chat流式生成器无效', [
  7458. 'generator_type' => $errorType,
  7459. 'model' => $model,
  7460. 'anime_id' => $anime_id,
  7461. 'episode_number' => $episode_number
  7462. ]);
  7463. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7464. 'type' => $errorType,
  7465. 'model' => $model
  7466. ]);
  7467. yield [
  7468. 'type' => 'error',
  7469. 'episode' => [],
  7470. 'answer' => '',
  7471. 'reasoning' => '',
  7472. 'usage' => [],
  7473. 'error' => '接口返回数据异常,请重新请求'
  7474. ];
  7475. return;
  7476. }
  7477. // 处理流式输出
  7478. foreach ($streamGenerator as $chunk) {
  7479. if (isset($chunk['type'])) {
  7480. if ($chunk['type'] === 'done') {
  7481. // 最终结果
  7482. $fullContent = $chunk['full_content'];
  7483. $fullReasoningContent = $chunk['full_reasoning'];
  7484. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7485. } else {
  7486. // 逐块yield数据
  7487. yield $chunk;
  7488. }
  7489. }
  7490. }
  7491. } catch (\Exception $e) {
  7492. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7493. 'model' => $model,
  7494. 'anime_id' => $anime_id,
  7495. 'episode_number' => $episode_number,
  7496. 'trace' => $e->getTraceAsString()
  7497. ]);
  7498. logDB('deepseek', 'error', 'chat流式处理失败', [
  7499. 'error' => $e->getMessage(),
  7500. 'model' => $model
  7501. ]);
  7502. yield [
  7503. 'type' => 'error',
  7504. 'episode' => [],
  7505. 'answer' => '',
  7506. 'reasoning' => '',
  7507. 'usage' => [],
  7508. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7509. ];
  7510. return;
  7511. }
  7512. dLog('deepseek')->info('完整内容: '.$fullContent);
  7513. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7514. // 处理完整内容并返回最终结果
  7515. $episode_arr = handleEpisodeContent($fullContent);
  7516. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7517. if (empty($episode_arr['acts'])) {
  7518. // 未生成剧本相关内容,保存对话记录并返回提示
  7519. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7520. try {
  7521. $now = date('Y-m-d H:i:s');
  7522. // 保存对话记录
  7523. $records = [
  7524. [
  7525. 'uid' => $uid,
  7526. 'anime_id' => $anime_id,
  7527. 'sequence' => $episode_number,
  7528. 'role' => 'user',
  7529. 'content' => $prompt,
  7530. 'created_at' => $now,
  7531. 'updated_at' => $now
  7532. ],
  7533. [
  7534. 'uid' => $uid,
  7535. 'anime_id' => $anime_id,
  7536. 'sequence' => $episode_number,
  7537. 'role' => 'assistant',
  7538. 'content' => $fullContent,
  7539. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7540. 'created_at' => $now,
  7541. 'updated_at' => $now
  7542. ]
  7543. ];
  7544. DB::table('mp_anime_records')->insert($records);
  7545. } catch (\Exception $e) {
  7546. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7547. }
  7548. yield [
  7549. 'type' => 'done',
  7550. 'episode' => [],
  7551. 'answer' => $fullContent,
  7552. 'reasoning' => $fullReasoningContent,
  7553. 'usage' => $usage,
  7554. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7555. ];
  7556. return;
  7557. }
  7558. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7559. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7560. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7561. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7562. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7563. $existing_props = is_array($existing_props) ? $existing_props : [];
  7564. $now = date('Y-m-d H:i:s');
  7565. try {
  7566. DB::beginTransaction();
  7567. $saveResult = $this->saveEpisodeVersionData(
  7568. $anime_id,
  7569. $episode_number,
  7570. $episode_arr,
  7571. $existing_roles,
  7572. $existing_scenes,
  7573. $existing_props,
  7574. $current_episode,
  7575. $base_episode,
  7576. $is_regenerate_version,
  7577. $content,
  7578. $now
  7579. );
  7580. $episode = $saveResult['episode'];
  7581. $episode_id = $saveResult['episode_id'];
  7582. $merged_roles = $saveResult['merged_roles'];
  7583. $merged_scenes = $saveResult['merged_scenes'];
  7584. $merged_props = $saveResult['merged_props'];
  7585. $record_content = $origin_prompt;
  7586. if ($uploaded_content !== '') {
  7587. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7588. }
  7589. $records = [
  7590. [
  7591. 'uid' => $uid,
  7592. 'anime_id' => $anime_id,
  7593. 'role' => 'user',
  7594. 'content' => $record_content,
  7595. 'sequence' => $episode_number,
  7596. 'episode_id' => $episode_id,
  7597. 'created_at' => $now,
  7598. 'updated_at' => $now
  7599. ],
  7600. [
  7601. 'uid' => $uid,
  7602. 'anime_id' => $anime_id,
  7603. 'role' => 'assistant',
  7604. 'content' => $fullContent,
  7605. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7606. 'sequence' => $episode_number,
  7607. 'episode_id' => $episode_id,
  7608. 'created_at' => $now,
  7609. 'updated_at' => $now
  7610. ]
  7611. ];
  7612. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7613. if (!$boolen4) {
  7614. Utils::throwError('20003:对话记录保存失败');
  7615. }
  7616. // 保存模型和内容到anime表
  7617. $update_anime_data = [
  7618. 'model' => $model,
  7619. 'updated_at' => $now
  7620. ];
  7621. if ($uploaded_content) {
  7622. $update_anime_data['content'] = $uploaded_content;
  7623. }
  7624. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7625. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7626. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7627. 'anime_id' => $anime_id,
  7628. 'episode_number' => $episode_number,
  7629. 'model' => $model,
  7630. 'source' => 'chat',
  7631. ]);
  7632. }catch (\Exception $e) {
  7633. DB::rollBack();
  7634. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7635. yield [
  7636. 'type' => 'done',
  7637. 'answer' => $fullContent,
  7638. 'reasoning' => $fullReasoningContent,
  7639. 'usage' => $usage,
  7640. 'error' => $e->getMessage(),
  7641. ];
  7642. return;
  7643. }
  7644. DB::commit();
  7645. if ($is_global_generate_pics) {
  7646. // // 批量生成全局角色图片
  7647. // $this->batchSetGlobalRoleImg([
  7648. // 'anime_id' => $anime_id,
  7649. // ], true);
  7650. // // 批量生成全局场景图片
  7651. // $this->batchSetGlobalSceneImg([
  7652. // 'anime_id' => $anime_id,
  7653. // ], true);
  7654. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7655. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7656. }
  7657. $episode['episode_id'] = $episode_id;
  7658. $episode['roles'] = $merged_roles;
  7659. $episode['scenes'] = $merged_scenes;
  7660. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7661. yield [
  7662. 'type' => 'done',
  7663. 'episode' => $episode,
  7664. 'answer' => $fullContent,
  7665. 'reasoning' => $fullReasoningContent,
  7666. 'usage' => $usage
  7667. ];
  7668. }
  7669. public function addChatForAce($data) {
  7670. $uid = Site::getUid();
  7671. $anime_id = getProp($data, 'anime_id');
  7672. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7673. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7674. if (!$anime) Utils::throwError('20003:对话不存在');
  7675. $file = getProp($data, 'file');
  7676. $content = getProp($data, 'content', '');
  7677. $bid = getProp($data, 'bid', 0);
  7678. $script_id = getProp($data, 'script_id', 0);
  7679. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7680. $prompt = getProp($data, 'prompt');
  7681. $is_multi = getProp($anime, 'is_multi');
  7682. $is_single = (int)$is_multi !== 1;
  7683. // 积分余额预检(仅单剧集模式收费)
  7684. if ($is_single) {
  7685. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7686. }
  7687. $extra_products = getProp($data, 'products', []);
  7688. if (!$extra_products) {
  7689. $extra_products = getProp($anime, 'extra_products');
  7690. if ($extra_products) {
  7691. $extra_products = json_decode($extra_products, true);
  7692. }else {
  7693. $extra_products = [];
  7694. }
  7695. }else {
  7696. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7697. }
  7698. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7699. $anime_script_id = getProp($anime, 'script_id');
  7700. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7701. $cpid = Site::getCpid();
  7702. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7703. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7704. ->where('mapping.script_id', $anime_script_id)
  7705. ->where('product.cpid', $cpid)
  7706. ->where('product.is_deleted', 0);
  7707. $mappings = $script_products_mappings->select(
  7708. 'mapping.product_id',
  7709. 'mapping.episode_number',
  7710. 'product.product_name',
  7711. 'product.type',
  7712. 'product.product',
  7713. 'product.pic_prompt',
  7714. 'product.url',
  7715. 'product.pic_task_id',
  7716. 'product.pic_task_status',
  7717. 'product.three_view_image_url'
  7718. )
  7719. ->get();
  7720. // 按 product_id 分组,合并 episode_number
  7721. $productMap = [];
  7722. foreach ($mappings as $item) {
  7723. $product_id = $item->product_id;
  7724. $product_name = $item->product_name;
  7725. // 处理product_name两边的符号
  7726. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7727. if (!isset($productMap[$product_id])) {
  7728. $productMap[$product_id] = [
  7729. 'product_id' => $product_id,
  7730. 'product_name' => $product_name,
  7731. 'type' => (int)$item->type,
  7732. 'product' => (int)$item->product,
  7733. 'pic_prompt' => $item->pic_prompt,
  7734. 'url' => $item->url,
  7735. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7736. 'pic_task_id' => $item->pic_task_id,
  7737. 'pic_task_status' => $item->pic_task_status,
  7738. 'episode_numbers' => [],
  7739. ];
  7740. }
  7741. // 添加 episode_number(去重)
  7742. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7743. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7744. }
  7745. }
  7746. // 将查询到的剧本资产合并到extra_products中
  7747. // 先构建extra_products的索引(以product_id为key,用于去重)
  7748. $extraProductsMap = [];
  7749. foreach ($extra_products as $item) {
  7750. $key = getProp($item, 'product_id');
  7751. if ($key) {
  7752. $extraProductsMap[$key] = $item;
  7753. }
  7754. }
  7755. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7756. foreach ($productMap as $product) {
  7757. $product_id = $product['product_id'];
  7758. // 如果不存在则添加(不带episode_number信息)
  7759. if (!isset($extraProductsMap[$product_id])) {
  7760. $extraProductsMap[$product_id] = [
  7761. 'product_id' => $product['product_id'],
  7762. 'product_name' => $product['product_name'],
  7763. 'type' => $product['type'],
  7764. 'product' => $product['product'],
  7765. 'pic_prompt' => $product['pic_prompt'],
  7766. 'url' => $product['url'],
  7767. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  7768. 'pic_task_id' => $product['pic_task_id'],
  7769. 'pic_task_status' => $product['pic_task_status'],
  7770. ];
  7771. }
  7772. }
  7773. // 重新赋值给extra_products
  7774. $extra_products = array_values($extraProductsMap);
  7775. }
  7776. $user_anime_name = getProp($anime, 'anime_name');
  7777. // 处理提示词
  7778. if ($prompt && $extra_products) {
  7779. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7780. foreach($extra_products as $item) {
  7781. $product_name = getProp($item, 'product_name');
  7782. if ($product_name) {
  7783. // 替换 {product_name} 为 product_name
  7784. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7785. }
  7786. }
  7787. }
  7788. // 处理文本模型
  7789. $model = getProp($data, 'model');
  7790. if (!$model) {
  7791. // 用户没有输入,从anime表获取
  7792. $model = getProp($anime, 'model');
  7793. if (!$model) {
  7794. // anime表也没有,使用默认值
  7795. $model = 'deepseek-v4-pro';
  7796. }
  7797. }
  7798. // 验证模型是否在可用模型表中
  7799. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7800. $model = 'deepseek-v4-pro';
  7801. }
  7802. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7803. if ($prompt) {
  7804. $question .= "本次修改要求如下:\n{$prompt}";
  7805. }
  7806. // if (!$file && !$content && !$bid) {
  7807. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7808. // }
  7809. // 提取文件内容
  7810. if ($file) {
  7811. $content = $this->extractFileContent($file);
  7812. if (!$content) {
  7813. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7814. }
  7815. } elseif ($script_id) {
  7816. $content = $this->getContentByScriptId($script_id);
  7817. if (!$content) {
  7818. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7819. }
  7820. } elseif ($bid) {
  7821. $content = $this->getContentByBid($bid);
  7822. if (!$content) {
  7823. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7824. }
  7825. } elseif ($content) {
  7826. $content = filterContent($content);
  7827. } else {
  7828. $content = getProp($anime, 'content');
  7829. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7830. $need_generate_content = true;
  7831. }
  7832. }
  7833. // 美术风格
  7834. $input_art_style = getProp($data, 'art_style');
  7835. if (!$input_art_style) {
  7836. $mappedArtStyle = getProp($anime, 'art_style');
  7837. }else {
  7838. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7839. }
  7840. // 判断是否需要生成原文内容
  7841. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7842. // 如果需要生成原文内容,添加额外的要求
  7843. $content_generation_requirement = $need_generate_content
  7844. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7845. : "";
  7846. // 美术风格
  7847. if (!$mappedArtStyle) {
  7848. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7849. }else {
  7850. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7851. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7852. }else {
  7853. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7854. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7855. }
  7856. }
  7857. // 构建主体、场景和道具提示词
  7858. $extra_role_prompt = "\n";
  7859. $extra_scene_prompt = "\n";
  7860. $extra_prop_prompt = "\n";
  7861. $extra_roles = [];
  7862. $extra_scenes = [];
  7863. $extra_props = [];
  7864. $ref_products = []; // 参考资产
  7865. if ($extra_products) {
  7866. foreach($extra_products as $item) {
  7867. $product = getProp($item, 'product');
  7868. $product_name = getProp($item, 'product_name');
  7869. if ($product_name == '旁白') continue;
  7870. $ref_products[$product_name] = $item;
  7871. $pic_prompt = getProp($item, 'pic_prompt');
  7872. if ((int)$product === 1) {
  7873. // 拼接角色信息
  7874. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7875. $extra_roles[$product_name] = [
  7876. 'role' => $product_name,
  7877. 'pic_prompt' => $pic_prompt,
  7878. 'url' => getProp($item, 'url', ''),
  7879. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7880. ];
  7881. } elseif ((int)$product === 2) {
  7882. // 拼接场景信息
  7883. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7884. $extra_scenes[$product_name] = [
  7885. 'scene' => $product_name,
  7886. 'pic_prompt' => $pic_prompt,
  7887. 'url' => getProp($item, 'url', ''),
  7888. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7889. ];
  7890. } elseif ((int)$product === 3) {
  7891. // 拼接道具信息
  7892. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7893. $extra_props[$product_name] = [
  7894. 'prop' => $product_name,
  7895. 'pic_prompt' => $pic_prompt,
  7896. 'url' => getProp($item, 'url', ''),
  7897. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7898. ];
  7899. }
  7900. }
  7901. // 优化提示词,融入剧本
  7902. if (!empty(trim($extra_role_prompt))) {
  7903. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7904. }
  7905. if (!empty(trim($extra_scene_prompt))) {
  7906. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7907. }
  7908. if (!empty(trim($extra_prop_prompt))) {
  7909. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7910. }
  7911. }
  7912. if ($anime_script_id && $is_single) {
  7913. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7914. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7915. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7916. }else {
  7917. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7918. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7919. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7920. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7921. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7922. {$extra_role_prompt}";
  7923. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7924. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7925. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7926. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7927. {$extra_scene_prompt}";
  7928. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7929. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7930. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7931. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7932. {$extra_prop_prompt}";
  7933. }
  7934. $systemPrompt = $is_single
  7935. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7936. 强制要求:
  7937. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7938. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7939. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7940. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7941. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7942. 普通要求:
  7943. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7944. $role_demo
  7945. $scene_demo
  7946. $prop_demo
  7947. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7948. 5.1片段分割逻辑(优先级从高到低):
  7949. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7950. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7951. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7952. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7953. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7954. - 片段数量格式为: 片段数量:8
  7955. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7956. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7957. 5.3分镜结构:每个分镜包含以下字段:
  7958. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  7959. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7960. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7961. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7962. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7963. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7964. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7965. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7966. - 运镜:场景+画面描述+运镜
  7967. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7968. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7969. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7970. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7971. 6.《情绪-视听语言映射表》:
  7972. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7973. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7974. -----|---------|------------|----------------
  7975. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7976. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7977. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7978. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7979. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7980. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7981. -----|---------|------------|----------------
  7982. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7983. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7984. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7985. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7986. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7987. --------|---------|--------------|-------------
  7988. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7989. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7990. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7991. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7992. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7993. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7994. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7995. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7996. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7997. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7998. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7999. -----|---------|------------|------------
  8000. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8001. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8002. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8003. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8004. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8005. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8006. --------|---------|--------------|----------
  8007. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8008. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8009. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8010. 6.6 声音设计与潜意识影响 (Soundscape)
  8011. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8012. -----|---------|------------|------------------
  8013. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8014. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8015. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8016. 理论基石:
  8017. - The Five C's of Cinematography by Joseph V. Mascelli
  8018. - Film Art: An Introduction by David Bordwell
  8019. - Sight, Sound, Motion by Herbert Zettl
  8020. - Notes on the Cinematograph by Robert Bresson
  8021. \n\n
  8022. 7.{$mappedArtStyle_prompt}\n\n
  8023. 示例如下:\n
  8024. ###剧本名:西昆仑
  8025. ###故事梗概
  8026. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8027. ###剧本亮点
  8028. 亮点1:绝境奇药,生死一线
  8029. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8030. 亮点2:结拜兄妹,化解尴尬
  8031. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8032. 亮点3:纤发夺命,情愫暗涌
  8033. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8034. ###人物关系
  8035. 阿雪与梁萧之间存在兄妹之情。
  8036. ###核心矛盾
  8037. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8038. ###主体列表
  8039. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8040. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8041. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8042. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8043. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8044. 全景,正面拍摄,青年女性,亚洲人。
  8045. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8046. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8047. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8048. ###美术风格
  8049. 基础画风风格词:厚涂古风
  8050. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8051. ###场景列表
  8052. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8053. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8054. 无人物。}
  8055. ###分段剧本
  8056. 片段数量:8
  8057. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8058. ##片段1
  8059. 时长:12s
  8060. 分镜1
  8061. 出场角色:刀疤脸
  8062. 场景:边境小镇街道
  8063. 出场道具:酒杯-高脚杯
  8064. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8065. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8066. 配音台词:
  8067. 背景音效:
  8068. 分镜2
  8069. 出场角色:刀疤脸
  8070. 场景:悦来酒馆
  8071. 出场道具:酒杯-高脚杯
  8072. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8073. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8074. 配音台词:
  8075. 背景音效:
  8076. 分镜3
  8077. 出场角色:刀疤脸
  8078. 场景:悦来酒馆
  8079. 出场道具:酒杯-高脚杯
  8080. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8081. 运镜:从中景推向令牌特写。
  8082. 配音台词:
  8083. 背景音效:
  8084. 分镜4
  8085. 出场角色:刀疤脸
  8086. 场景:悦来酒馆
  8087. 出场道具:酒杯-高脚杯
  8088. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8089. 运镜:极速推向酒水溅起的瞬间。
  8090. 配音台词:
  8091. 背景音效:
  8092. 分镜5
  8093. 出场角色:刀疤脸
  8094. 场景:悦来酒馆
  8095. 出场道具:酒杯-高脚杯
  8096. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8097. 运镜:固定机位,利用倾斜构图制造压迫感。
  8098. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8099. 背景音效:
  8100. \n\n"
  8101. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8102. 强制要求:\n
  8103. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8104. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8105. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8106. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8107. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8108. 普通要求:\n
  8109. 1.剧本名(必须生成)必须与文档内容高度相关
  8110. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8111. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8112. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8113. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8114. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8115. {$extra_role_prompt}
  8116. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8117. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8118. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8119. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8120. {$extra_scene_prompt}
  8121. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8122. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8123. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8124. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8125. {$extra_prop_prompt}
  8126. 5.{$mappedArtStyle_prompt}\n\n
  8127. 示例如下:\n
  8128. ###剧本名:西昆仑
  8129. ###故事梗概
  8130. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8131. ###剧本亮点
  8132. 亮点1:绝境奇药,生死一线
  8133. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8134. 亮点2:结拜兄妹,化解尴尬
  8135. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8136. 亮点3:纤发夺命,情愫暗涌
  8137. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8138. ###人物关系
  8139. 阿雪与梁萧之间存在兄妹之情。
  8140. ###核心矛盾
  8141. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8142. ###主体列表
  8143. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8144. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8145. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8146. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8147. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8148. 全景,正面拍摄,青年女性,亚洲人。
  8149. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8150. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8151. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8152. ###美术风格
  8153. 基础画风风格词:厚涂古风
  8154. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8155. ###场景列表
  8156. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8157. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8158. 无人物。}
  8159. ###道具列表
  8160. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  8161. // 构建消息
  8162. $messages = [
  8163. [
  8164. 'role' => 'system',
  8165. 'content' => $systemPrompt
  8166. ],
  8167. [
  8168. 'role' => 'user',
  8169. 'content' => "以下是文档内容:
  8170. {$content}
  8171. 用户问题:
  8172. {$question}"
  8173. ]
  8174. ];
  8175. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8176. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认思考模式
  8177. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8178. if ($model === 'deepseek-chat') {
  8179. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8180. $model = 'deepseek-v4-flash';
  8181. $thinkingMode = 'disabled';
  8182. } elseif ($model === 'deepseek-reasoner') {
  8183. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8184. $model = 'deepseek-v4-flash';
  8185. $thinkingMode = 'enabled';
  8186. }
  8187. $post_data = [
  8188. 'model' => $model,
  8189. 'messages' => $messages,
  8190. // 'max_tokens' => 8192,
  8191. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8192. 'frequency_penalty' => 0,
  8193. 'presence_penalty' => 0,
  8194. 'response_format' => ['type' => 'text'],
  8195. 'thinking' => ['type'=>$thinkingMode],
  8196. 'stream' => true // 启用流式输出
  8197. ];
  8198. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8199. // 根据模型类型选择调用方法
  8200. $fullContent = '';
  8201. $fullReasoningContent = '';
  8202. $usage = [];
  8203. try {
  8204. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8205. // 验证返回值类型
  8206. if (!is_iterable($streamGenerator)) {
  8207. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8208. dLog('deepseek')->error('addChat流式生成器无效', [
  8209. 'generator_type' => $errorType,
  8210. 'model' => $model,
  8211. 'anime_id' => $anime_id
  8212. ]);
  8213. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  8214. 'type' => $errorType,
  8215. 'model' => $model
  8216. ]);
  8217. yield [
  8218. 'type' => 'error',
  8219. 'script' => [],
  8220. 'episode' => [],
  8221. 'answer' => '',
  8222. 'reasoning' => '',
  8223. 'usage' => [],
  8224. 'error' => '接口返回数据异常,请重新请求'
  8225. ];
  8226. return;
  8227. }
  8228. // 处理流式输出
  8229. foreach ($streamGenerator as $chunk) {
  8230. if (isset($chunk['type'])) {
  8231. if ($chunk['type'] === 'done') {
  8232. // 最终结果
  8233. $fullContent = $chunk['full_content'];
  8234. $fullReasoningContent = $chunk['full_reasoning'];
  8235. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8236. } else {
  8237. // 逐块yield数据
  8238. yield $chunk;
  8239. }
  8240. }
  8241. }
  8242. } catch (\Exception $e) {
  8243. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  8244. 'model' => $model,
  8245. 'anime_id' => $anime_id,
  8246. 'trace' => $e->getTraceAsString()
  8247. ]);
  8248. logDB('deepseek', 'error', 'addChat流式处理失败', [
  8249. 'error' => $e->getMessage(),
  8250. 'model' => $model
  8251. ]);
  8252. yield [
  8253. 'type' => 'error',
  8254. 'script' => [],
  8255. 'episode' => [],
  8256. 'answer' => '',
  8257. 'reasoning' => '',
  8258. 'usage' => [],
  8259. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8260. ];
  8261. return;
  8262. }
  8263. dLog('deepseek')->info('完整内容: '.$fullContent);
  8264. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8265. // 处理完整内容并返回最终结果
  8266. $script_arr = [];
  8267. if ($fullContent) {
  8268. $script_arr = handleScriptContentForAce($fullContent);
  8269. dLog('deepseek')->info('解析内容', $script_arr);
  8270. logDB('deepseek', 'info', '解析内容', $script_arr);
  8271. }
  8272. if (empty($script_arr['roles'])) {
  8273. // 未生成剧本相关内容,保存对话记录并返回提示
  8274. dLog('deepseek')->info('未生成剧本相关的内容');
  8275. try {
  8276. DB::beginTransaction();
  8277. $now = date('Y-m-d H:i:s');
  8278. // 保存对话记录
  8279. $records = [
  8280. [
  8281. 'uid' => $uid,
  8282. 'anime_id' => $anime_id,
  8283. 'sequence' => 0,
  8284. 'role' => 'user',
  8285. 'content' => $prompt,
  8286. 'created_at' => $now,
  8287. 'updated_at' => $now
  8288. ],
  8289. [
  8290. 'uid' => $uid,
  8291. 'anime_id' => $anime_id,
  8292. 'sequence' => 0,
  8293. 'role' => 'assistant',
  8294. // 'content' => $fullContent,
  8295. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  8296. 'created_at' => $now,
  8297. 'updated_at' => $now
  8298. ]
  8299. ];
  8300. DB::table('mp_anime_records')->insert($records);
  8301. DB::commit();
  8302. } catch (\Exception $e) {
  8303. DB::rollBack();
  8304. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8305. }
  8306. yield [
  8307. 'type' => 'done',
  8308. 'script' => [],
  8309. 'episode' => [],
  8310. 'answer' => $fullContent,
  8311. 'reasoning' => $fullReasoningContent,
  8312. 'usage' => $usage,
  8313. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8314. ];
  8315. return;
  8316. }
  8317. // 如果需要生成原文内容,从script_arr中提取
  8318. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8319. $content = $script_arr['content'];
  8320. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  8321. if (!$content) {
  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. }
  8334. // 替换美术风格
  8335. if ($mappedArtStyle !== '') {
  8336. $script_arr['art_style'] = $mappedArtStyle;
  8337. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8338. }
  8339. // 新建动漫
  8340. if ($user_anime_name == '新剧本策划') {
  8341. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8342. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8343. // if (!$anime_name) {
  8344. // // 未识别到剧本名,保存对话记录并返回提示
  8345. // dLog('deepseek')->info('未能识别到剧本名称');
  8346. // try {
  8347. // DB::beginTransaction();
  8348. // $now = date('Y-m-d H:i:s');
  8349. // // 保存对话记录
  8350. // $records = [
  8351. // [
  8352. // 'uid' => $uid,
  8353. // 'anime_id' => $anime_id,
  8354. // 'sequence' => 0,
  8355. // 'role' => 'user',
  8356. // 'content' => $prompt,
  8357. // 'created_at' => $now,
  8358. // 'updated_at' => $now
  8359. // ],
  8360. // [
  8361. // 'uid' => $uid,
  8362. // 'anime_id' => $anime_id,
  8363. // 'sequence' => 0,
  8364. // 'role' => 'assistant',
  8365. // 'content' => '未能生成剧本名称,请重试',
  8366. // 'created_at' => $now,
  8367. // 'updated_at' => $now
  8368. // ]
  8369. // ];
  8370. // DB::table('mp_anime_records')->insert($records);
  8371. // DB::commit();
  8372. // } catch (\Exception $e) {
  8373. // DB::rollBack();
  8374. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8375. // }
  8376. // yield [
  8377. // 'type' => 'done',
  8378. // 'script' => [],
  8379. // 'episode' => [],
  8380. // 'answer' => $fullContent,
  8381. // 'reasoning' => $fullReasoningContent,
  8382. // 'usage' => $usage,
  8383. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  8384. // ];
  8385. // return;
  8386. // }
  8387. // 确认对话名称唯一性
  8388. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8389. $anime_name = $anime_name . '_' . date('YmdHis');
  8390. }
  8391. }else {
  8392. $anime_name = $user_anime_name;
  8393. }
  8394. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  8395. if ($is_single) {
  8396. $max_retries = 3;
  8397. $retry_count = 0;
  8398. $validation_failed = false;
  8399. $validation_error_msg = '';
  8400. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8401. // 首次校验
  8402. if ($anime_script_id) {
  8403. if (empty($episode_arr['acts'])) {
  8404. $validation_failed = true;
  8405. $validation_error_msg = '未生成分镜剧本相关的内容';
  8406. } else {
  8407. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8408. $generated_roles = array_filter($generated_roles, function($role) {
  8409. return $role !== '旁白';
  8410. });
  8411. if (empty($generated_roles)) {
  8412. $validation_failed = true;
  8413. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8414. }
  8415. if (!$validation_failed && !empty($extra_roles)) {
  8416. $expected_roles = array_keys($extra_roles);
  8417. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8418. if (!empty($invalid_roles)) {
  8419. $validation_failed = true;
  8420. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8421. }
  8422. }
  8423. if (!$validation_failed && !empty($extra_scenes)) {
  8424. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8425. $expected_scenes = array_keys($extra_scenes);
  8426. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8427. if (!empty($invalid_scenes)) {
  8428. $validation_failed = true;
  8429. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8430. }
  8431. }
  8432. if (!$validation_failed && !empty($extra_props)) {
  8433. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8434. $expected_props = array_keys($extra_props);
  8435. $invalid_props = array_diff($generated_props, $expected_props);
  8436. if (!empty($invalid_props)) {
  8437. $validation_failed = true;
  8438. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8439. }
  8440. }
  8441. }
  8442. } else {
  8443. if (empty($episode_arr['acts'])) {
  8444. $validation_failed = true;
  8445. $validation_error_msg = '未生成分镜剧本相关的内容';
  8446. } else {
  8447. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8448. $generated_roles = array_filter($generated_roles, function($role) {
  8449. return $role !== '旁白';
  8450. });
  8451. if (empty($generated_roles)) {
  8452. $validation_failed = true;
  8453. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8454. }
  8455. }
  8456. }
  8457. // 重试循环
  8458. while ($validation_failed && $retry_count < $max_retries) {
  8459. $retry_count++;
  8460. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8461. 'reason' => $validation_error_msg,
  8462. 'anime_id' => $anime_id,
  8463. 'episode_number' => 1
  8464. ]);
  8465. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8466. 'reason' => $validation_error_msg,
  8467. 'anime_id' => $anime_id
  8468. ]);
  8469. yield [
  8470. 'type' => 'retry',
  8471. 'retry_count' => $retry_count,
  8472. 'reason' => $validation_error_msg
  8473. ];
  8474. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8475. if ($anime_script_id) {
  8476. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8477. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8478. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8479. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  8480. } else {
  8481. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8482. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  8483. }
  8484. $messages[] = [
  8485. 'role' => 'assistant',
  8486. 'content' => $fullContent
  8487. ];
  8488. $messages[] = [
  8489. 'role' => 'user',
  8490. 'content' => $retry_prompt
  8491. ];
  8492. $post_data['messages'] = $messages;
  8493. try {
  8494. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8495. $fullContent = '';
  8496. $fullReasoningContent = '';
  8497. foreach ($streamGenerator as $chunk) {
  8498. if (isset($chunk['type'])) {
  8499. if ($chunk['type'] === 'done') {
  8500. $fullContent = $chunk['full_content'];
  8501. $fullReasoningContent = $chunk['full_reasoning'];
  8502. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8503. } else {
  8504. yield $chunk;
  8505. }
  8506. }
  8507. }
  8508. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8509. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  8510. if ($fullContent === '') {
  8511. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  8512. yield [
  8513. 'type' => 'done',
  8514. 'script' => [],
  8515. 'episode' => [],
  8516. 'answer' => '',
  8517. 'reasoning' => $fullReasoningContent,
  8518. 'usage' => $usage,
  8519. 'error' => '生成接口未返回有效内容,请稍后重试'
  8520. ];
  8521. return;
  8522. }
  8523. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8524. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8525. $script_arr = handleScriptContentForAce($fullContent);
  8526. if ($mappedArtStyle !== '') {
  8527. $script_arr['art_style'] = $mappedArtStyle;
  8528. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8529. }
  8530. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8531. $validation_failed = false;
  8532. $validation_error_msg = '';
  8533. if ($anime_script_id) {
  8534. if (empty($episode_arr['acts'])) {
  8535. $validation_failed = true;
  8536. $validation_error_msg = '未生成分镜剧本相关的内容';
  8537. } else {
  8538. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8539. $generated_roles = array_filter($generated_roles, function($role) {
  8540. return $role !== '旁白';
  8541. });
  8542. if (empty($generated_roles)) {
  8543. $validation_failed = true;
  8544. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8545. }
  8546. if (!$validation_failed && !empty($extra_roles)) {
  8547. $expected_roles = array_keys($extra_roles);
  8548. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8549. if (!empty($invalid_roles)) {
  8550. $validation_failed = true;
  8551. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8552. }
  8553. }
  8554. if (!$validation_failed && !empty($extra_scenes)) {
  8555. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8556. $expected_scenes = array_keys($extra_scenes);
  8557. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8558. if (!empty($invalid_scenes)) {
  8559. $validation_failed = true;
  8560. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8561. }
  8562. }
  8563. if (!$validation_failed && !empty($extra_props)) {
  8564. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8565. $expected_props = array_keys($extra_props);
  8566. $invalid_props = array_diff($generated_props, $expected_props);
  8567. if (!empty($invalid_props)) {
  8568. $validation_failed = true;
  8569. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8570. }
  8571. }
  8572. }
  8573. } else {
  8574. if (empty($episode_arr['acts'])) {
  8575. $validation_failed = true;
  8576. $validation_error_msg = '未生成分镜剧本相关的内容';
  8577. } else {
  8578. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8579. $generated_roles = array_filter($generated_roles, function($role) {
  8580. return $role !== '旁白';
  8581. });
  8582. if (empty($generated_roles)) {
  8583. $validation_failed = true;
  8584. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8585. }
  8586. }
  8587. }
  8588. } catch (\Exception $e) {
  8589. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8590. 'trace' => $e->getTraceAsString()
  8591. ]);
  8592. break;
  8593. }
  8594. }
  8595. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  8596. if ($validation_failed && $retry_count >= $max_retries) {
  8597. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8598. 'retry_count' => $retry_count,
  8599. 'last_error' => $validation_error_msg
  8600. ]);
  8601. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8602. 'error' => $validation_error_msg,
  8603. 'anime_id' => $anime_id
  8604. ]);
  8605. $validation_failed = false;
  8606. $validation_error_msg = '';
  8607. }
  8608. // 如果重试后仍然失败
  8609. if ($validation_failed) {
  8610. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8611. 'retry_count' => $retry_count,
  8612. 'last_error' => $validation_error_msg
  8613. ]);
  8614. try {
  8615. $now = date('Y-m-d H:i:s');
  8616. $records = [
  8617. [
  8618. 'uid' => $uid,
  8619. 'anime_id' => $anime_id,
  8620. 'sequence' => 1,
  8621. 'role' => 'user',
  8622. 'content' => $prompt,
  8623. 'created_at' => $now,
  8624. 'updated_at' => $now
  8625. ],
  8626. [
  8627. 'uid' => $uid,
  8628. 'anime_id' => $anime_id,
  8629. 'sequence' => 1,
  8630. 'role' => 'assistant',
  8631. 'content' => $fullContent,
  8632. 'created_at' => $now,
  8633. 'updated_at' => $now
  8634. ]
  8635. ];
  8636. DB::table('mp_anime_records')->insert($records);
  8637. } catch (\Exception $e) {
  8638. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8639. }
  8640. yield [
  8641. 'type' => 'done',
  8642. 'script' => [],
  8643. 'episode' => [],
  8644. 'answer' => $fullContent,
  8645. 'reasoning' => $fullReasoningContent,
  8646. 'usage' => $usage,
  8647. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8648. ];
  8649. return;
  8650. }
  8651. // 验证成功,记录日志
  8652. if ($retry_count > 0) {
  8653. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8654. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8655. }
  8656. }
  8657. $table_data = [
  8658. 'user_id' => $uid,
  8659. 'anime_name' => $anime_name,
  8660. 'model' => $model,
  8661. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8662. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8663. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8664. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8665. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8666. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8667. 'art_style_type' => $input_art_style,
  8668. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8669. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8670. 'status' => '解析完成',
  8671. 'content' => $content,
  8672. 'is_multi' => $is_multi,
  8673. 'ace_mode' => $ace_mode,
  8674. 'generate_status' => '待执行',
  8675. 'updated_at' => date('Y-m-d H:i:s')
  8676. ];
  8677. if ($table_data['content']) {
  8678. $chapters = splitContent($table_data['content']);
  8679. $chapter_count = count($chapters);
  8680. if ($chapter_count > 0) {
  8681. $table_data['start_episode_sequence'] = 1;
  8682. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8683. }
  8684. }
  8685. if ($extra_products) {
  8686. $table_data['extra_products'] = json_encode($extra_products, 256);
  8687. }
  8688. // 如果有剧本ID则进行绑定
  8689. if ($script_id) {
  8690. $table_data['script_id'] = $script_id;
  8691. }
  8692. $single_episode = [];
  8693. try {
  8694. DB::beginTransaction();
  8695. $now = date('Y-m-d H:i:s');
  8696. // 更新动漫大纲
  8697. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8698. if (!$boolen) {
  8699. dLog('deepseek')->info('动漫保存失败', $table_data);
  8700. Utils::throwError('20003:动漫保存失败');
  8701. }
  8702. // 保存对话记录
  8703. $records = [
  8704. [
  8705. 'uid' => $uid,
  8706. 'anime_id' => $anime_id,
  8707. 'sequence' => 0,
  8708. 'role' => 'user',
  8709. 'content' => $prompt,
  8710. 'created_at' => date('Y-m-d H:i:s'),
  8711. 'updated_at' => date('Y-m-d H:i:s')
  8712. ],
  8713. [
  8714. 'uid' => $uid,
  8715. 'anime_id' => $anime_id,
  8716. 'sequence' => 0,
  8717. 'role' => 'assistant',
  8718. 'content' => $fullContent,
  8719. 'created_at' => date('Y-m-d H:i:s'),
  8720. 'updated_at' => date('Y-m-d H:i:s')
  8721. ]
  8722. ];
  8723. // 保存对话记录
  8724. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8725. if (!$boolen3) {
  8726. Utils::throwError('20003:对话记录保存失败');
  8727. }
  8728. if ($is_single) {
  8729. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8730. if (empty($episode_arr['acts'])) {
  8731. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8732. }
  8733. $saveResult = $this->saveEpisodeVersionData(
  8734. $anime_id,
  8735. 1,
  8736. $episode_arr,
  8737. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8738. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8739. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8740. null,
  8741. null,
  8742. false,
  8743. $content,
  8744. $now,
  8745. $ref_products
  8746. );
  8747. $single_episode = $saveResult['episode'];
  8748. $episode_id = $saveResult['episode_id'];
  8749. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8750. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8751. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8752. 'props' => json_encode($saveResult['merged_props'], 256),
  8753. 'updated_at' => $now
  8754. ]);
  8755. if ($boolen5 === false) {
  8756. Utils::throwError('20003:单剧集主表资源同步失败');
  8757. }
  8758. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8759. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8760. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8761. $episode_record_content = '确认分镜大纲';
  8762. if ($content !== '') {
  8763. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8764. }
  8765. $episode_records = [
  8766. [
  8767. 'uid' => $uid,
  8768. 'anime_id' => $anime_id,
  8769. 'role' => 'user',
  8770. 'content' => $episode_record_content,
  8771. 'sequence' => 1,
  8772. 'episode_id' => $episode_id,
  8773. 'created_at' => $now,
  8774. 'updated_at' => $now
  8775. ],
  8776. [
  8777. 'uid' => $uid,
  8778. 'anime_id' => $anime_id,
  8779. 'role' => 'assistant',
  8780. 'content' => $fullContent,
  8781. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8782. 'sequence' => 1,
  8783. 'episode_id' => $episode_id,
  8784. 'created_at' => $now,
  8785. 'updated_at' => $now
  8786. ]
  8787. ];
  8788. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8789. if (!$boolen4) {
  8790. Utils::throwError('20003:单剧集分镜记录保存失败');
  8791. }
  8792. }
  8793. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8794. if ($is_single && !empty($single_episode)) {
  8795. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8796. 'anime_id' => $anime_id,
  8797. 'episode_id' => $episode_id ?? 0,
  8798. 'model' => $model,
  8799. 'source' => 'addChatForAce',
  8800. ]);
  8801. }
  8802. }catch (\Exception $e) {
  8803. DB::rollBack();
  8804. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8805. yield [
  8806. 'type' => 'done',
  8807. 'answer' => $fullContent,
  8808. 'reasoning' => $fullReasoningContent,
  8809. 'usage' => $usage,
  8810. 'error' => $e->getMessage(),
  8811. ];
  8812. return;
  8813. }
  8814. DB::commit();
  8815. dLog('deepseek')->info('保存完毕');
  8816. if ($is_single && !empty($single_episode)) {
  8817. // $this->batchSetGlobalRoleImg([
  8818. // 'anime_id' => $anime_id,
  8819. // ]);
  8820. // $this->batchSetGlobalSceneImg([
  8821. // 'anime_id' => $anime_id,
  8822. // ]);
  8823. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8824. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8825. }
  8826. $table_data['anime_id'] = $anime_id;
  8827. $table_data['roles'] = json_decode($table_data['roles'], true);
  8828. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8829. // $table_data['episodes'] = $script_arr['episodes'];
  8830. unset($table_data['created_at']);
  8831. unset($table_data['updated_at']);
  8832. unset($table_data['status']);
  8833. dLog('deepseek')->info('开始返回');
  8834. yield [
  8835. 'type' => 'done',
  8836. 'script' => $table_data,
  8837. 'episode' => $single_episode,
  8838. 'answer' => $fullContent,
  8839. 'reasoning' => $fullReasoningContent,
  8840. 'usage' => $usage
  8841. ];
  8842. }
  8843. public function reGenerateAnimeForAce($data) {
  8844. $uid = Site::getUid();
  8845. $file = getProp($data, 'file');
  8846. $content = getProp($data, 'content', '');
  8847. $bid = getProp($data, 'bid', 0);
  8848. $script_id = getProp($data, 'script_id', 0);
  8849. $anime_id = getProp($data, 'anime_id');
  8850. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8851. if (!$anime) {
  8852. Utils::throwError('20003:该对话不存在');
  8853. }
  8854. $is_multi = getProp($anime, 'is_multi', 1);
  8855. $is_single = (int)$is_multi !== 1;
  8856. // 积分余额预检(仅单剧集模式收费)
  8857. if ($is_single) {
  8858. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8859. }
  8860. $extra_products = getProp($data, 'products', []);
  8861. if (!$extra_products) {
  8862. $extra_products = getProp($anime, 'extra_products');
  8863. if ($extra_products) {
  8864. $extra_products = json_decode($extra_products, true);
  8865. }else {
  8866. $extra_products = [];
  8867. }
  8868. }else {
  8869. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8870. }
  8871. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8872. $anime_script_id = getProp($anime, 'script_id');
  8873. if ($anime_script_id && $is_single) {
  8874. $cpid = Site::getCpid();
  8875. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8876. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8877. ->where('mapping.script_id', $anime_script_id)
  8878. ->where('product.cpid', $cpid)
  8879. ->where('product.is_deleted', 0);
  8880. $mappings = $script_products_mappings->select(
  8881. 'mapping.product_id',
  8882. 'mapping.episode_number',
  8883. 'product.product_name',
  8884. 'product.type',
  8885. 'product.product',
  8886. 'product.pic_prompt',
  8887. 'product.url',
  8888. 'product.pic_task_id',
  8889. 'product.pic_task_status',
  8890. 'product.three_view_image_url'
  8891. )
  8892. ->get();
  8893. // 按 product_id 分组,合并 episode_number
  8894. $productMap = [];
  8895. foreach ($mappings as $item) {
  8896. $product_id = $item->product_id;
  8897. $product_name = $item->product_name;
  8898. // 处理product_name两边的符号
  8899. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8900. if (!isset($productMap[$product_id])) {
  8901. $productMap[$product_id] = [
  8902. 'product_id' => $product_id,
  8903. 'product_name' => $product_name,
  8904. 'type' => (int)$item->type,
  8905. 'product' => (int)$item->product,
  8906. 'pic_prompt' => $item->pic_prompt,
  8907. 'url' => $item->url,
  8908. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8909. 'pic_task_id' => $item->pic_task_id,
  8910. 'pic_task_status' => $item->pic_task_status,
  8911. 'episode_numbers' => [],
  8912. ];
  8913. }
  8914. // 添加 episode_number(去重)
  8915. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8916. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8917. }
  8918. }
  8919. // 将查询到的剧本资产合并到extra_products中
  8920. // 先构建extra_products的索引(以product_id为key,用于去重)
  8921. $extraProductsMap = [];
  8922. foreach ($extra_products as $item) {
  8923. $key = getProp($item, 'product_id');
  8924. if ($key) {
  8925. $extraProductsMap[$key] = $item;
  8926. }
  8927. }
  8928. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8929. foreach ($productMap as $product) {
  8930. $product_id = $product['product_id'];
  8931. // 如果不存在则添加(不带episode_number信息)
  8932. if (!isset($extraProductsMap[$product_id])) {
  8933. $extraProductsMap[$product_id] = [
  8934. 'product_id' => $product['product_id'],
  8935. 'product_name' => $product['product_name'],
  8936. 'type' => $product['type'],
  8937. 'product' => $product['product'],
  8938. 'pic_prompt' => $product['pic_prompt'],
  8939. 'url' => $product['url'],
  8940. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  8941. 'pic_task_id' => $product['pic_task_id'],
  8942. 'pic_task_status' => $product['pic_task_status'],
  8943. ];
  8944. }
  8945. }
  8946. // 重新赋值给extra_products
  8947. $extra_products = array_values($extraProductsMap);
  8948. }
  8949. $user_anime_name = getProp($anime, 'anime_name');
  8950. $prompt = getProp($data, 'prompt');
  8951. // 处理提示词
  8952. if ($prompt && $extra_products) {
  8953. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8954. foreach($extra_products as $item) {
  8955. $product_name = getProp($item, 'product_name');
  8956. if ($product_name) {
  8957. // 替换 {product_name} 为 product_name
  8958. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8959. }
  8960. }
  8961. }
  8962. // 处理文本模型
  8963. $model = getProp($data, 'model');
  8964. if (!$model) {
  8965. // 用户没有输入,从anime表获取
  8966. $model = getProp($anime, 'model');
  8967. if (!$model) {
  8968. // anime表也没有,使用默认值
  8969. $model = 'deepseek-v4-pro';
  8970. }
  8971. }
  8972. // 验证模型是否在可用模型表中
  8973. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8974. $model = 'deepseek-v4-pro';
  8975. }
  8976. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8977. if ($is_single) {
  8978. $episode_exists = DB::table('mp_anime_episodes')
  8979. ->where('anime_id', $anime_id)
  8980. ->where('sequence', 1)
  8981. ->exists();
  8982. if ($episode_exists) {
  8983. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8984. }
  8985. }
  8986. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8987. if ($prompt) {
  8988. $question .= "本次修改要求如下:\n{$prompt}";
  8989. }
  8990. // 提取文件内容
  8991. if ($file) {
  8992. $content = $this->extractFileContent($file);
  8993. if (!$content) {
  8994. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8995. }
  8996. } elseif ($script_id) {
  8997. $content = $this->getContentByScriptId($script_id);
  8998. if (!$content) {
  8999. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9000. }
  9001. } elseif ($bid) {
  9002. $content = $this->getContentByBid($bid);
  9003. if (!$content) {
  9004. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9005. }
  9006. } elseif ($content) {
  9007. $content = filterContent($content);
  9008. }else {
  9009. $content = filterContent(getProp($anime, 'content'));
  9010. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  9011. $need_generate_content = true;
  9012. }
  9013. }
  9014. // 判断是否需要生成原文内容
  9015. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  9016. // 如果需要生成原文内容,添加额外的要求
  9017. $content_generation_requirement = $need_generate_content
  9018. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  9019. : "";
  9020. // 美术风格
  9021. $input_art_style = getProp($data, 'art_style');
  9022. if (!$input_art_style) {
  9023. $mappedArtStyle = getProp($anime, 'art_style');
  9024. }else {
  9025. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9026. }
  9027. if (!$mappedArtStyle) {
  9028. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9029. }else {
  9030. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9031. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9032. }else {
  9033. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9034. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9035. }
  9036. }
  9037. // 构建主体、场景和道具提示词
  9038. $extra_role_prompt = "\n";
  9039. $extra_scene_prompt = "\n";
  9040. $extra_prop_prompt = "\n";
  9041. $extra_roles = [];
  9042. $extra_scenes = [];
  9043. $extra_props = [];
  9044. $ref_products = []; // 参考资产
  9045. if ($extra_products) {
  9046. foreach($extra_products as $item) {
  9047. $product = getProp($item, 'product');
  9048. $product_name = getProp($item, 'product_name');
  9049. if ($product_name == '旁白') continue;
  9050. $ref_products[$product_name] = $item;
  9051. $pic_prompt = getProp($item, 'pic_prompt');
  9052. if ((int)$product === 1) {
  9053. // 拼接角色信息
  9054. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9055. $extra_roles[$product_name] = [
  9056. 'role' => $product_name,
  9057. 'pic_prompt' => $pic_prompt,
  9058. 'url' => getProp($item, 'url', ''),
  9059. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9060. ];
  9061. } elseif ((int)$product === 2) {
  9062. // 拼接场景信息
  9063. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9064. $extra_scenes[$product_name] = [
  9065. 'scene' => $product_name,
  9066. 'pic_prompt' => $pic_prompt,
  9067. 'url' => getProp($item, 'url', ''),
  9068. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9069. ];
  9070. } elseif ((int)$product === 3) {
  9071. // 拼接道具信息
  9072. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9073. $extra_props[$product_name] = [
  9074. 'prop' => $product_name,
  9075. 'pic_prompt' => $pic_prompt,
  9076. 'url' => getProp($item, 'url', ''),
  9077. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9078. ];
  9079. }
  9080. }
  9081. // 优化提示词,融入剧本
  9082. if (!empty(trim($extra_role_prompt))) {
  9083. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9084. }
  9085. if (!empty(trim($extra_scene_prompt))) {
  9086. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9087. }
  9088. if (!empty(trim($extra_prop_prompt))) {
  9089. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9090. }
  9091. }
  9092. if ($anime_script_id && $is_single) {
  9093. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  9094. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  9095. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  9096. }else {
  9097. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9098. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9099. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9100. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9101. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9102. {$extra_role_prompt}";
  9103. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9104. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  9105. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9106. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9107. {$extra_scene_prompt}";
  9108. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9109. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  9110. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9111. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  9112. {$extra_prop_prompt}";
  9113. }
  9114. $system_message = ['role'=>'system', 'content'=>$is_single
  9115. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  9116. 强制要求:
  9117. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9118. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9119. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9120. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9121. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9122. 普通要求:
  9123. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  9124. $role_demo
  9125. $scene_demo
  9126. $prop_demo
  9127. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9128. 5.1片段分割逻辑(优先级从高到低):
  9129. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9130. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9131. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9132. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9133. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9134. - 片段数量格式为: 片段数量:8
  9135. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9136. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9137. 5.3分镜结构:每个分镜包含以下字段:
  9138. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9139. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9140. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9141. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9142. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9143. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9144. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9145. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9146. - 运镜:场景+画面描述+运镜
  9147. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9148. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9149. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9150. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  9151. 6.《情绪-视听语言映射表》:
  9152. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9153. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9154. -----|---------|------------|----------------
  9155. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9156. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9157. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9158. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9159. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9160. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9161. -----|---------|------------|----------------
  9162. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9163. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9164. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9165. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9166. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9167. --------|---------|--------------|-------------
  9168. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9169. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9170. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9171. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9172. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9173. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9174. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9175. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9176. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9177. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9178. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9179. -----|---------|------------|------------
  9180. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9181. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9182. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9183. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9184. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9185. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9186. --------|---------|--------------|----------
  9187. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9188. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9189. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9190. 6.6 声音设计与潜意识影响 (Soundscape)
  9191. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9192. -----|---------|------------|------------------
  9193. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9194. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9195. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9196. 理论基石:
  9197. - The Five C's of Cinematography by Joseph V. Mascelli
  9198. - Film Art: An Introduction by David Bordwell
  9199. - Sight, Sound, Motion by Herbert Zettl
  9200. - Notes on the Cinematograph by Robert Bresson
  9201. \n\n
  9202. 7.{$mappedArtStyle_prompt}\n\n
  9203. 示例如下:\n
  9204. ###剧本名:西昆仑
  9205. ###故事梗概
  9206. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9207. ###剧本亮点
  9208. 亮点1:绝境奇药,生死一线
  9209. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9210. 亮点2:结拜兄妹,化解尴尬
  9211. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9212. 亮点3:纤发夺命,情愫暗涌
  9213. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9214. ###人物关系
  9215. 阿雪与梁萧之间存在兄妹之情。
  9216. ###核心矛盾
  9217. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9218. ###主体列表
  9219. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9220. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9221. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9222. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9223. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9224. 全景,正面拍摄,青年女性,亚洲人。
  9225. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9226. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9227. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9228. ###美术风格
  9229. 基础画风风格词:厚涂古风
  9230. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9231. ###场景列表
  9232. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9233. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9234. 无人物。}
  9235. ###分段剧本
  9236. 片段数量:8
  9237. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9238. ##片段1
  9239. 时长:12s
  9240. 分镜1
  9241. 出场角色:刀疤脸
  9242. 场景:边境小镇街道
  9243. 出场道具:酒杯-高脚杯
  9244. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9245. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9246. 配音台词:
  9247. 背景音效:
  9248. 分镜2
  9249. 出场角色:刀疤脸
  9250. 场景:悦来酒馆
  9251. 出场道具:酒杯-高脚杯
  9252. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9253. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9254. 配音台词:
  9255. 背景音效:
  9256. 分镜3
  9257. 出场角色:刀疤脸
  9258. 场景:悦来酒馆
  9259. 出场道具:酒杯-高脚杯
  9260. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9261. 运镜:从中景推向令牌特写。
  9262. 配音台词:
  9263. 背景音效:
  9264. 分镜4
  9265. 出场角色:刀疤脸
  9266. 场景:悦来酒馆
  9267. 出场道具:酒杯-高脚杯
  9268. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9269. 运镜:极速推向酒水溅起的瞬间。
  9270. 配音台词:
  9271. 背景音效:
  9272. 分镜5
  9273. 出场角色:刀疤脸
  9274. 场景:悦来酒馆
  9275. 出场道具:酒杯-高脚杯
  9276. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9277. 运镜:固定机位,利用倾斜构图制造压迫感。
  9278. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9279. 背景音效:
  9280. \n\n"
  9281. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9282. 强制要求:\n
  9283. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9284. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9285. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9286. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9287. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9288. 普通要求:\n
  9289. 1.剧本名(必须生成)必须与文档内容高度相关
  9290. $role_demo
  9291. $scene_demo
  9292. $prop_demo
  9293. 5.{$mappedArtStyle_prompt}\n\n
  9294. 示例如下:\n
  9295. ###剧本名:西昆仑
  9296. ###故事梗概
  9297. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9298. ###剧本亮点
  9299. 亮点1:绝境奇药,生死一线
  9300. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9301. 亮点2:结拜兄妹,化解尴尬
  9302. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9303. 亮点3:纤发夺命,情愫暗涌
  9304. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9305. ###人物关系
  9306. 阿雪与梁萧之间存在兄妹之情。
  9307. ###核心矛盾
  9308. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9309. ###主体列表
  9310. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9311. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9312. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9313. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9314. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9315. 全景,正面拍摄,青年女性,亚洲人。
  9316. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9317. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9318. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9319. ###美术风格
  9320. 基础画风风格词:厚涂古风
  9321. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9322. ###场景列表
  9323. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9324. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9325. 无人物。}
  9326. ###道具列表
  9327. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  9328. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  9329. $episode_count = $this->extractEpisodeNumber($prompt);
  9330. if ((int)getProp($anime, 'is_multi') !== 1) {
  9331. yield [
  9332. 'type' => 'done',
  9333. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  9334. 'reasoning' => '',
  9335. 'usage' => []
  9336. ];
  9337. return;
  9338. }
  9339. if ($episode_count) {
  9340. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  9341. $system_message = [
  9342. 'role' => 'system',
  9343. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9344. 强制要求:\n
  9345. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9346. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9347. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9348. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9349. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9350. 普通要求:\n
  9351. 1.<故事梗概>控制在200-300字左右
  9352. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9353. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9354. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9355. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9356. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9357. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9358. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9359. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9360. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9361. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  9362. 示例如下:\n
  9363. ###剧本名:西昆仑
  9364. ###故事梗概
  9365. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9366. ###剧本亮点
  9367. 亮点1:绝境奇药,生死一线
  9368. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9369. 亮点2:结拜兄妹,化解尴尬
  9370. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9371. 亮点3:纤发夺命,情愫暗涌
  9372. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9373. ###人物关系
  9374. 阿雪与梁萧之间存在兄妹之情。
  9375. ###核心矛盾
  9376. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9377. ###主体列表
  9378. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9379. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9380. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9381. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9382. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9383. 全景,正面拍摄,青年女性,亚洲人。
  9384. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9385. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9386. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9387. ###美术风格
  9388. 基础画风风格词:厚涂古风
  9389. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9390. ###场景列表
  9391. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9392. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9393. 无人物。}
  9394. ###分集详细内容
  9395. ##第1章 重生
  9396. 我重生了。
  9397. 源于一个男人偏执的暗恋。
  9398. ##第2章 相救
  9399. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  9400. 我眼睛扫向站在锅炉后的卞大伟。"
  9401. ];
  9402. // 构建消息
  9403. $messages = [
  9404. $system_message,
  9405. [
  9406. 'role' => 'user',
  9407. 'content' => "以下是文档内容:
  9408. {$content}
  9409. 用户问题:
  9410. {$question}"
  9411. ]
  9412. ];
  9413. }else {
  9414. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  9415. // 构建消息
  9416. $messages = [
  9417. $system_message,
  9418. [
  9419. 'role' => 'user',
  9420. 'content' => "以下是文档内容:
  9421. {$content}
  9422. 用户问题:
  9423. {$question}"
  9424. ]
  9425. ];
  9426. }else {
  9427. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  9428. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  9429. return (array)$value;
  9430. })->toArray();
  9431. array_unshift($messages, $system_message);
  9432. $messages[] = [
  9433. 'role' => 'user',
  9434. 'content' => $prompt
  9435. ];
  9436. }
  9437. }
  9438. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9439. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  9440. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9441. if ($model === 'deepseek-chat') {
  9442. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9443. $model = 'deepseek-v4-flash';
  9444. $thinkingMode = 'disabled';
  9445. } elseif ($model === 'deepseek-reasoner') {
  9446. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9447. $model = 'deepseek-v4-flash';
  9448. $thinkingMode = 'enabled';
  9449. }
  9450. $post_data = [
  9451. 'model' => $model,
  9452. 'messages' => $messages,
  9453. // 'max_tokens' => 8192,
  9454. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9455. 'frequency_penalty' => 0,
  9456. 'presence_penalty' => 0,
  9457. 'response_format' => ['type' => 'text'],
  9458. 'thinking' => ['type' => $thinkingMode],
  9459. 'stream' => true // 启用流式输出
  9460. ];
  9461. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9462. // 根据模型类型选择调用方法
  9463. $fullContent = '';
  9464. $fullReasoningContent = '';
  9465. $usage = [];
  9466. // dd($post_data);
  9467. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  9468. try {
  9469. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9470. // 验证返回值类型
  9471. if (!is_iterable($streamGenerator)) {
  9472. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9473. dLog('deepseek')->error('方法名流式生成器无效', [
  9474. 'generator_type' => $errorType,
  9475. 'model' => $model,
  9476. // 添加其他上下文信息
  9477. ]);
  9478. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  9479. 'type' => $errorType,
  9480. 'model' => $model
  9481. ]);
  9482. yield [
  9483. 'type' => 'error',
  9484. // 根据方法返回相应的空数据结构
  9485. 'answer' => '',
  9486. 'reasoning' => '',
  9487. 'usage' => [],
  9488. 'error' => '接口返回数据异常,请重新请求'
  9489. ];
  9490. return;
  9491. }
  9492. // 处理流式输出
  9493. foreach ($streamGenerator as $chunk) {
  9494. if (isset($chunk['type'])) {
  9495. if ($chunk['type'] === 'done') {
  9496. $fullContent = $chunk['full_content'];
  9497. $fullReasoningContent = $chunk['full_reasoning'];
  9498. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9499. } else {
  9500. yield $chunk;
  9501. }
  9502. }
  9503. }
  9504. } catch (\Exception $e) {
  9505. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  9506. 'model' => $model,
  9507. 'trace' => $e->getTraceAsString()
  9508. ]);
  9509. logDB('deepseek', 'error', '方法名流式处理失败', [
  9510. 'error' => $e->getMessage(),
  9511. 'model' => $model
  9512. ]);
  9513. yield [
  9514. 'type' => 'error',
  9515. // 根据方法返回相应的空数据结构
  9516. 'answer' => '',
  9517. 'reasoning' => '',
  9518. 'usage' => [],
  9519. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9520. ];
  9521. return;
  9522. }
  9523. dLog('deepseek')->info('完整内容: '.$fullContent);
  9524. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9525. // 处理完整内容并返回最终结果
  9526. $script_arr = [];
  9527. if ($fullContent) {
  9528. $script_arr = handleScriptContentForAce($fullContent);
  9529. dLog('deepseek')->info('解析内容', $script_arr);
  9530. logDB('deepseek', 'info', '解析内容', $script_arr);
  9531. }
  9532. if (empty($script_arr['roles'])) {
  9533. // 未生成剧本相关内容,保存对话记录并返回提示
  9534. dLog('deepseek')->info('未生成剧本相关的内容');
  9535. try {
  9536. $now = date('Y-m-d H:i:s');
  9537. // 保存对话记录
  9538. $records = [
  9539. [
  9540. 'uid' => $uid,
  9541. 'anime_id' => $anime_id,
  9542. 'sequence' => 0,
  9543. 'role' => 'user',
  9544. 'content' => $prompt,
  9545. 'created_at' => $now,
  9546. 'updated_at' => $now
  9547. ],
  9548. [
  9549. 'uid' => $uid,
  9550. 'anime_id' => $anime_id,
  9551. 'sequence' => 0,
  9552. 'role' => 'assistant',
  9553. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  9554. 'created_at' => $now,
  9555. 'updated_at' => $now
  9556. ]
  9557. ];
  9558. DB::table('mp_anime_records')->insert($records);
  9559. } catch (\Exception $e) {
  9560. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9561. }
  9562. yield [
  9563. 'type' => 'done',
  9564. 'script' => [],
  9565. 'episode' => [],
  9566. 'answer' => $fullContent,
  9567. 'reasoning' => $fullReasoningContent,
  9568. 'usage' => $usage,
  9569. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  9570. ];
  9571. return;
  9572. }
  9573. // 替换美术风格
  9574. if ($mappedArtStyle !== '') {
  9575. $script_arr['art_style'] = $mappedArtStyle;
  9576. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9577. }
  9578. if ($user_anime_name != '新剧本策划') {
  9579. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  9580. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  9581. // 确认对话名称唯一性
  9582. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  9583. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  9584. }
  9585. }else {
  9586. $anime_name = $user_anime_name;
  9587. }
  9588. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  9589. if ($is_single) {
  9590. $max_retries = 3;
  9591. $retry_count = 0;
  9592. $validation_failed = false;
  9593. $validation_error_msg = '';
  9594. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9595. // 首次校验
  9596. if ($anime_script_id) {
  9597. if (empty($episode_arr['acts'])) {
  9598. $validation_failed = true;
  9599. $validation_error_msg = '未生成分镜剧本相关的内容';
  9600. } else {
  9601. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9602. $generated_roles = array_filter($generated_roles, function($role) {
  9603. return $role !== '旁白';
  9604. });
  9605. if (empty($generated_roles)) {
  9606. $validation_failed = true;
  9607. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9608. }
  9609. if (!$validation_failed && !empty($extra_roles)) {
  9610. $expected_roles = array_keys($extra_roles);
  9611. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9612. if (!empty($invalid_roles)) {
  9613. $validation_failed = true;
  9614. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9615. }
  9616. }
  9617. if (!$validation_failed && !empty($extra_scenes)) {
  9618. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9619. $expected_scenes = array_keys($extra_scenes);
  9620. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9621. if (!empty($invalid_scenes)) {
  9622. $validation_failed = true;
  9623. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9624. }
  9625. }
  9626. if (!$validation_failed && !empty($extra_props)) {
  9627. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9628. $expected_props = array_keys($extra_props);
  9629. $invalid_props = array_diff($generated_props, $expected_props);
  9630. if (!empty($invalid_props)) {
  9631. $validation_failed = true;
  9632. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9633. }
  9634. }
  9635. }
  9636. } else {
  9637. if (empty($episode_arr['acts'])) {
  9638. $validation_failed = true;
  9639. $validation_error_msg = '未生成分镜剧本相关的内容';
  9640. } else {
  9641. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9642. $generated_roles = array_filter($generated_roles, function($role) {
  9643. return $role !== '旁白';
  9644. });
  9645. if (empty($generated_roles)) {
  9646. $validation_failed = true;
  9647. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9648. }
  9649. }
  9650. }
  9651. // 重试循环
  9652. while ($validation_failed && $retry_count < $max_retries) {
  9653. $retry_count++;
  9654. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9655. 'reason' => $validation_error_msg,
  9656. 'anime_id' => $anime_id,
  9657. 'episode_number' => 1
  9658. ]);
  9659. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9660. 'reason' => $validation_error_msg,
  9661. 'anime_id' => $anime_id
  9662. ]);
  9663. yield [
  9664. 'type' => 'retry',
  9665. 'retry_count' => $retry_count,
  9666. 'reason' => $validation_error_msg
  9667. ];
  9668. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9669. if ($anime_script_id) {
  9670. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9671. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9672. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9673. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9674. } else {
  9675. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9676. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9677. }
  9678. $messages[] = [
  9679. 'role' => 'assistant',
  9680. 'content' => $fullContent
  9681. ];
  9682. $messages[] = [
  9683. 'role' => 'user',
  9684. 'content' => $retry_prompt
  9685. ];
  9686. $post_data['messages'] = $messages;
  9687. try {
  9688. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9689. $fullContent = '';
  9690. $fullReasoningContent = '';
  9691. foreach ($streamGenerator as $chunk) {
  9692. if (isset($chunk['type'])) {
  9693. if ($chunk['type'] === 'done') {
  9694. $fullContent = $chunk['full_content'];
  9695. $fullReasoningContent = $chunk['full_reasoning'];
  9696. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9697. } else {
  9698. yield $chunk;
  9699. }
  9700. }
  9701. }
  9702. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9703. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  9704. if ($fullContent === '') {
  9705. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  9706. yield [
  9707. 'type' => 'done',
  9708. 'script' => [],
  9709. 'episode' => [],
  9710. 'answer' => '',
  9711. 'reasoning' => $fullReasoningContent,
  9712. 'usage' => $usage,
  9713. 'error' => '生成接口未返回有效内容,请稍后重试'
  9714. ];
  9715. return;
  9716. }
  9717. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9718. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9719. $script_arr = handleScriptContentForAce($fullContent);
  9720. if ($mappedArtStyle !== '') {
  9721. $script_arr['art_style'] = $mappedArtStyle;
  9722. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9723. }
  9724. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9725. $validation_failed = false;
  9726. $validation_error_msg = '';
  9727. if ($anime_script_id) {
  9728. if (empty($episode_arr['acts'])) {
  9729. $validation_failed = true;
  9730. $validation_error_msg = '未生成分镜剧本相关的内容';
  9731. } else {
  9732. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9733. $generated_roles = array_filter($generated_roles, function($role) {
  9734. return $role !== '旁白';
  9735. });
  9736. if (empty($generated_roles)) {
  9737. $validation_failed = true;
  9738. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9739. }
  9740. if (!$validation_failed && !empty($extra_roles)) {
  9741. $expected_roles = array_keys($extra_roles);
  9742. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9743. if (!empty($invalid_roles)) {
  9744. $validation_failed = true;
  9745. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9746. }
  9747. }
  9748. if (!$validation_failed && !empty($extra_scenes)) {
  9749. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9750. $expected_scenes = array_keys($extra_scenes);
  9751. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9752. if (!empty($invalid_scenes)) {
  9753. $validation_failed = true;
  9754. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9755. }
  9756. }
  9757. if (!$validation_failed && !empty($extra_props)) {
  9758. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9759. $expected_props = array_keys($extra_props);
  9760. $invalid_props = array_diff($generated_props, $expected_props);
  9761. if (!empty($invalid_props)) {
  9762. $validation_failed = true;
  9763. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9764. }
  9765. }
  9766. }
  9767. } else {
  9768. if (empty($episode_arr['acts'])) {
  9769. $validation_failed = true;
  9770. $validation_error_msg = '未生成分镜剧本相关的内容';
  9771. } else {
  9772. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9773. $generated_roles = array_filter($generated_roles, function($role) {
  9774. return $role !== '旁白';
  9775. });
  9776. if (empty($generated_roles)) {
  9777. $validation_failed = true;
  9778. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9779. }
  9780. }
  9781. }
  9782. } catch (\Exception $e) {
  9783. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9784. 'trace' => $e->getTraceAsString()
  9785. ]);
  9786. break;
  9787. }
  9788. }
  9789. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  9790. if ($validation_failed && $retry_count >= $max_retries) {
  9791. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9792. 'retry_count' => $retry_count,
  9793. 'last_error' => $validation_error_msg
  9794. ]);
  9795. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9796. 'error' => $validation_error_msg,
  9797. 'anime_id' => $anime_id
  9798. ]);
  9799. $validation_failed = false;
  9800. $validation_error_msg = '';
  9801. }
  9802. // 如果重试后仍然失败
  9803. if ($validation_failed) {
  9804. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9805. 'retry_count' => $retry_count,
  9806. 'last_error' => $validation_error_msg
  9807. ]);
  9808. try {
  9809. $now = date('Y-m-d H:i:s');
  9810. $records = [
  9811. [
  9812. 'uid' => $uid,
  9813. 'anime_id' => $anime_id,
  9814. 'sequence' => 1,
  9815. 'role' => 'user',
  9816. 'content' => $prompt,
  9817. 'created_at' => $now,
  9818. 'updated_at' => $now
  9819. ],
  9820. [
  9821. 'uid' => $uid,
  9822. 'anime_id' => $anime_id,
  9823. 'sequence' => 1,
  9824. 'role' => 'assistant',
  9825. 'content' => $fullContent,
  9826. 'created_at' => $now,
  9827. 'updated_at' => $now
  9828. ]
  9829. ];
  9830. DB::table('mp_anime_records')->insert($records);
  9831. } catch (\Exception $e) {
  9832. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9833. }
  9834. yield [
  9835. 'type' => 'done',
  9836. 'script' => [],
  9837. 'episode' => [],
  9838. 'answer' => $fullContent,
  9839. 'reasoning' => $fullReasoningContent,
  9840. 'usage' => $usage,
  9841. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9842. ];
  9843. return;
  9844. }
  9845. // 验证成功,记录日志
  9846. if ($retry_count > 0) {
  9847. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9848. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9849. }
  9850. }
  9851. $table_data = [
  9852. 'user_id' => $uid,
  9853. 'model' => $model,
  9854. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  9855. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  9856. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  9857. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  9858. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  9859. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  9860. 'art_style_type' => $input_art_style,
  9861. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  9862. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  9863. 'status' => '解析完成',
  9864. 'generate_status' => '待执行',
  9865. 'updated_at' => date('Y-m-d H:i:s')
  9866. ];
  9867. if ($anime_name) $table_data['anime_name'] = $anime_name;
  9868. // 如果是修改集数,则将content内容更新(会改变原文)
  9869. if (isset($episode_count) && $episode_count > 0) {
  9870. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  9871. $table_data['start_episode_sequence'] = 1;
  9872. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  9873. }else {
  9874. // 如果需要生成原文内容,从script_arr中提取
  9875. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  9876. $table_data['content'] = $script_arr['content'];
  9877. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  9878. if (!$table_data['content']) {
  9879. yield [
  9880. 'type' => 'done',
  9881. 'script' => [],
  9882. 'episode' => [],
  9883. 'answer' => $fullContent,
  9884. 'reasoning' => $fullReasoningContent,
  9885. 'usage' => $usage,
  9886. 'error' => '未生成剧本内容,请调整提示词再试'
  9887. ];
  9888. return;
  9889. }
  9890. }
  9891. if (isset($table_data['content']) && $table_data['content']) {
  9892. $chapters = splitContent($table_data['content']);
  9893. $chapter_count = count($chapters);
  9894. if ($chapter_count > 0) {
  9895. $table_data['start_episode_sequence'] = 1;
  9896. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  9897. }
  9898. }
  9899. }
  9900. if ($extra_products) {
  9901. $table_data['extra_products'] = json_encode($extra_products, 256);
  9902. }
  9903. $single_episode = [];
  9904. try {
  9905. DB::beginTransaction();
  9906. $now = date('Y-m-d H:i:s');
  9907. // 更新动漫大纲
  9908. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  9909. if (!$boolen) {
  9910. dLog('deepseek')->info('对话修改失败', $table_data);
  9911. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  9912. Utils::throwError('20003:对话修改失败');
  9913. }
  9914. // 保存对话记录
  9915. $records = [
  9916. [
  9917. 'uid' => $uid,
  9918. 'anime_id' => $anime_id,
  9919. 'sequence' => 0,
  9920. 'role' => 'user',
  9921. 'content' => $prompt,
  9922. 'created_at' => $now,
  9923. 'updated_at' => $now
  9924. ],
  9925. [
  9926. 'uid' => $uid,
  9927. 'anime_id' => $anime_id,
  9928. 'sequence' => 0,
  9929. 'role' => 'assistant',
  9930. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9931. 'content' => $fullContent,
  9932. 'created_at' => $now,
  9933. 'updated_at' => $now
  9934. ]
  9935. ];
  9936. // 保存对话记录
  9937. $boolen3 = DB::table('mp_anime_records')->insert($records);
  9938. if (!$boolen3) {
  9939. Utils::throwError('20003:对话记录保存失败');
  9940. }
  9941. // 单剧集模式:生成并保存剧集信息
  9942. if ($is_single) {
  9943. $anime_name = getProp($anime, 'anime_name', '未命名');
  9944. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9945. if (empty($episode_arr['acts'])) {
  9946. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  9947. }
  9948. $saveResult = $this->saveEpisodeVersionData(
  9949. $anime_id,
  9950. 1,
  9951. $episode_arr,
  9952. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9953. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9954. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9955. null,
  9956. null,
  9957. false,
  9958. $content,
  9959. $now,
  9960. $ref_products
  9961. );
  9962. $single_episode = $saveResult['episode'];
  9963. $episode_id = $saveResult['episode_id'];
  9964. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  9965. 'roles' => json_encode($saveResult['merged_roles'], 256),
  9966. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  9967. 'props' => json_encode($saveResult['merged_props'], 256),
  9968. 'updated_at' => $now
  9969. ]);
  9970. if ($boolen5 === false) {
  9971. Utils::throwError('20003:单剧集主表资源同步失败');
  9972. }
  9973. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  9974. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  9975. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  9976. $episode_record_content = '确认分镜大纲';
  9977. if ($content !== '') {
  9978. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  9979. }
  9980. $episode_records = [
  9981. [
  9982. 'uid' => $uid,
  9983. 'anime_id' => $anime_id,
  9984. 'role' => 'user',
  9985. 'content' => $episode_record_content,
  9986. 'sequence' => 1,
  9987. 'episode_id' => $episode_id,
  9988. 'created_at' => $now,
  9989. 'updated_at' => $now
  9990. ],
  9991. [
  9992. 'uid' => $uid,
  9993. 'anime_id' => $anime_id,
  9994. 'role' => 'assistant',
  9995. 'content' => $fullContent,
  9996. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9997. 'sequence' => 1,
  9998. 'episode_id' => $episode_id,
  9999. 'created_at' => $now,
  10000. 'updated_at' => $now
  10001. ]
  10002. ];
  10003. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  10004. if (!$boolen4) {
  10005. Utils::throwError('20003:单剧集分镜记录保存失败');
  10006. }
  10007. }
  10008. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10009. if ($is_single && !empty($single_episode)) {
  10010. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10011. 'anime_id' => $anime_id,
  10012. 'episode_id' => $episode_id ?? 0,
  10013. 'model' => $model,
  10014. 'source' => 'reGenerateAnimeForAce',
  10015. ]);
  10016. }
  10017. }catch (\Exception $e) {
  10018. DB::rollBack();
  10019. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  10020. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  10021. yield [
  10022. 'type' => 'done',
  10023. 'answer' => $fullContent,
  10024. 'reasoning' => $fullReasoningContent,
  10025. 'usage' => $usage,
  10026. 'error' => $e->getMessage(),
  10027. ];
  10028. return;
  10029. }
  10030. DB::commit();
  10031. dLog('deepseek')->info('保存完毕');
  10032. if ($is_single && !empty($single_episode)) {
  10033. // $this->batchSetGlobalRoleImg([
  10034. // 'anime_id' => $anime_id,
  10035. // ]);
  10036. // $this->batchSetGlobalSceneImg([
  10037. // 'anime_id' => $anime_id,
  10038. // ]);
  10039. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10040. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10041. }
  10042. $table_data['anime_id'] = $anime_id;
  10043. $table_data['roles'] = json_decode($table_data['roles'], true);
  10044. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  10045. $table_data['props'] = json_decode($table_data['props'], true);
  10046. unset($table_data['updated_at']);
  10047. unset($table_data['status']);
  10048. yield [
  10049. 'type' => 'done',
  10050. 'script' => $table_data,
  10051. 'episode' => $single_episode,
  10052. 'answer' => $fullContent,
  10053. 'reasoning' => $fullReasoningContent,
  10054. 'usage' => $usage
  10055. ];
  10056. }
  10057. public function chatForAce($data) {
  10058. $uid = Site::getUid();
  10059. // 积分余额预检(不足直接报错)
  10060. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10061. $anime_id = getProp($data, 'anime_id');
  10062. $file = getProp($data, 'file');
  10063. $content = getProp($data, 'content', '');
  10064. $bid = getProp($data, 'bid', 0);
  10065. $script_id = getProp($data, 'script_id', 0);
  10066. $episode_number = getProp($data, 'episode_number', 1);
  10067. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10068. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10069. if (!$anime) Utils::throwError('20003:该对话不存在!');
  10070. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  10071. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  10072. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  10073. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  10074. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  10075. $roles = is_array($roles) ? $roles : [];
  10076. $scenes = is_array($scenes) ? $scenes : [];
  10077. $extra_products = getProp($data, 'products', []);
  10078. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  10079. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  10080. $anime_script_id = getProp($anime, 'script_id');
  10081. if ($anime_script_id) {
  10082. $cpid = Site::getCpid();
  10083. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  10084. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10085. ->where('mapping.script_id', $anime_script_id)
  10086. ->where('product.cpid', $cpid)
  10087. ->where('product.is_deleted', 0);
  10088. // 如果提供了 episode_number,则过滤指定集数
  10089. if ($episode_number !== null && $episode_number !== '') {
  10090. $script_products_mappings->where('mapping.episode_number', $episode_number);
  10091. }
  10092. $mappings = $script_products_mappings->select(
  10093. 'mapping.product_id',
  10094. 'mapping.episode_number',
  10095. 'product.product_name',
  10096. 'product.type',
  10097. 'product.product',
  10098. 'product.pic_prompt',
  10099. 'product.url',
  10100. 'product.pic_task_id',
  10101. 'product.pic_task_status',
  10102. 'product.three_view_image_url'
  10103. )
  10104. ->get();
  10105. // 按 product_id 分组,合并 episode_number
  10106. $productMap = [];
  10107. foreach ($mappings as $item) {
  10108. $product_id = $item->product_id;
  10109. $product_name = $item->product_name;
  10110. // 处理product_name两边的符号
  10111. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  10112. if (!isset($productMap[$product_id])) {
  10113. $productMap[$product_id] = [
  10114. 'product_id' => $product_id,
  10115. 'product_name' => $product_name,
  10116. 'type' => (int)$item->type,
  10117. 'product' => (int)$item->product,
  10118. 'pic_prompt' => $item->pic_prompt,
  10119. 'url' => $item->url,
  10120. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  10121. 'pic_task_id' => $item->pic_task_id,
  10122. 'pic_task_status' => $item->pic_task_status,
  10123. 'episode_numbers' => [],
  10124. ];
  10125. }
  10126. // 添加 episode_number(去重)
  10127. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  10128. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  10129. }
  10130. }
  10131. // 将查询到的剧本资产合并到extra_products中
  10132. // 先构建extra_products的索引(以product_id+episode_number为key)
  10133. $extraProductsMap = [];
  10134. foreach ($extra_products as $item) {
  10135. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  10136. $extraProductsMap[$key] = $item;
  10137. }
  10138. // 合并剧本资产(去重:product_id+episode_number)
  10139. foreach ($productMap as $product) {
  10140. foreach ($product['episode_numbers'] as $ep_num) {
  10141. $key = $product['product_id'] . '_' . $ep_num;
  10142. // 如果不存在则添加
  10143. if (!isset($extraProductsMap[$key])) {
  10144. $extraProductsMap[$key] = [
  10145. 'product_id' => $product['product_id'],
  10146. 'product_name' => $product['product_name'],
  10147. 'type' => $product['type'],
  10148. 'product' => $product['product'],
  10149. 'pic_prompt' => $product['pic_prompt'],
  10150. 'url' => $product['url'],
  10151. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  10152. 'pic_task_id' => $product['pic_task_id'],
  10153. 'pic_task_status' => $product['pic_task_status'],
  10154. 'episode_number' => $ep_num,
  10155. ];
  10156. }
  10157. }
  10158. }
  10159. // 重新赋值给extra_products
  10160. $extra_products = array_values($extraProductsMap);
  10161. }
  10162. // 处理提示词
  10163. if ($prompt && $extra_products) {
  10164. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  10165. foreach($extra_products as $item) {
  10166. $product_name = getProp($item, 'product_name');
  10167. if ($product_name) {
  10168. // 替换 {product_name} 为 product_name
  10169. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  10170. }
  10171. }
  10172. }
  10173. // 获取最后一集序号
  10174. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  10175. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  10176. // 转换主体列表和场景列表的格式
  10177. // 获取参考主体或场景
  10178. if ((int)$episode_number === 1) {
  10179. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  10180. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  10181. }else {
  10182. $prev_episode_number = $episode_number - 1;
  10183. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  10184. }
  10185. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  10186. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  10187. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  10188. // 合并anime_products和extra_products(extra_products优先,去重)
  10189. $anime_products = getProp($anime, 'extra_products');
  10190. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  10191. $ref_products = [];
  10192. foreach($anime_products as $item) {
  10193. $product_name = getProp($item, 'product_name');
  10194. $ref_products[$product_name] = $item;
  10195. }
  10196. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  10197. $extra_roles = []; // 从extra_products中提取的角色
  10198. $extra_scenes = []; // 从extra_products中提取的场景
  10199. $extra_props = []; // 从extra_products中提取的道具
  10200. if ($extra_products && is_array($extra_products)) {
  10201. foreach($extra_products as $item) {
  10202. $product = (int)getProp($item, 'product');
  10203. $product_name = getProp($item, 'product_name');
  10204. if ($product_name == '旁白') continue;
  10205. $pic_prompt = getProp($item, 'pic_prompt');
  10206. $ref_products[$product_name] = $item;
  10207. if ($product === 1) {
  10208. // 角色
  10209. $extra_roles[$product_name] = [
  10210. 'role' => $product_name,
  10211. 'pic_prompt' => $pic_prompt,
  10212. 'url' => getProp($item, 'url', ''),
  10213. ];
  10214. } elseif ($product === 2) {
  10215. // 场景
  10216. $extra_scenes[$product_name] = [
  10217. 'scene' => $product_name,
  10218. 'pic_prompt' => $pic_prompt,
  10219. 'url' => getProp($item, 'url', ''),
  10220. ];
  10221. } elseif ($product === 3) {
  10222. // 道具
  10223. $extra_props[$product_name] = [
  10224. 'prop' => $product_name,
  10225. 'pic_prompt' => $pic_prompt,
  10226. 'url' => getProp($item, 'url', ''),
  10227. ];
  10228. }
  10229. }
  10230. }
  10231. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  10232. $merged_roles = [];
  10233. foreach($ref_roles as $role) {
  10234. $role_name = getProp($role, 'role');
  10235. if (!isset($extra_roles[$role_name])) {
  10236. $merged_roles[$role_name] = $role;
  10237. }
  10238. }
  10239. // 添加extra_roles
  10240. foreach($extra_roles as $role_name => $role) {
  10241. $merged_roles[$role_name] = $role;
  10242. }
  10243. $ref_roles = array_values($merged_roles);
  10244. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  10245. $merged_scenes = [];
  10246. foreach($ref_scenes as $scene) {
  10247. $scene_name = getProp($scene, 'scene');
  10248. if (!isset($extra_scenes[$scene_name])) {
  10249. $merged_scenes[$scene_name] = $scene;
  10250. }
  10251. }
  10252. // 添加extra_scenes
  10253. foreach($extra_scenes as $scene_name => $scene) {
  10254. $merged_scenes[$scene_name] = $scene;
  10255. }
  10256. $ref_scenes = array_values($merged_scenes);
  10257. // 合并ref_props和extra_props(extra_props优先,去重)
  10258. $merged_props = [];
  10259. foreach($ref_props as $prop) {
  10260. $prop_name = getProp($prop, 'prop');
  10261. if (!isset($extra_props[$prop_name])) {
  10262. $merged_props[$prop_name] = $prop;
  10263. }
  10264. }
  10265. // 添加extra_props
  10266. foreach($extra_props as $prop_name => $prop) {
  10267. $merged_props[$prop_name] = $prop;
  10268. }
  10269. $ref_props = array_values($merged_props);
  10270. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  10271. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  10272. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  10273. // 构建强制主体、场景和道具提示词
  10274. $forced_roles_prompt = "";
  10275. $forced_scenes_prompt = "";
  10276. $forced_props_prompt = "";
  10277. if (!empty($extra_roles)) {
  10278. $forced_roles_list = "";
  10279. foreach($extra_roles as $role_name => $role) {
  10280. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  10281. }
  10282. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  10283. }
  10284. if (!empty($extra_scenes)) {
  10285. $forced_scenes_list = "";
  10286. foreach($extra_scenes as $scene_name => $scene) {
  10287. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  10288. }
  10289. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  10290. }
  10291. if (!empty($extra_props)) {
  10292. $forced_props_list = "";
  10293. foreach($extra_props as $prop_name => $prop) {
  10294. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  10295. }
  10296. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  10297. }
  10298. if ($anime_script_id) {
  10299. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  10300. }else if ($roles_content) {
  10301. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  10302. 主体范围:\n {$roles_content}\n
  10303. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  10304. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10305. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10306. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10307. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10308. }else {
  10309. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  10310. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10311. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10312. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10313. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10314. }
  10315. if ($anime_script_id) {
  10316. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  10317. }else if ($scenes_content) {
  10318. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10319. 场景范围:\n {$scenes_content}\n
  10320. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  10321. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  10322. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10323. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10324. }else {
  10325. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10326. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  10327. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10328. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10329. }
  10330. if ($anime_script_id) {
  10331. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  10332. }else if ($props_content) {
  10333. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10334. 道具范围:\n {$props_content}\n
  10335. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  10336. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  10337. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10338. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10339. }else {
  10340. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10341. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  10342. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10343. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10344. }
  10345. // 提取文件内容
  10346. if ($file) {
  10347. $uploaded_content = $this->extractFileContent($file);
  10348. if (!$uploaded_content) {
  10349. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  10350. }
  10351. } elseif ($script_id) {
  10352. $uploaded_content = $this->getContentByScriptId($script_id);
  10353. if (!$uploaded_content) {
  10354. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  10355. }
  10356. } elseif ($bid) {
  10357. $uploaded_content = $this->getContentByBid($bid);
  10358. if (!$uploaded_content) {
  10359. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  10360. }
  10361. } elseif ($content) {
  10362. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  10363. }
  10364. // elseif ($prompt) {
  10365. // $uploaded_content = filterContent($prompt);
  10366. // }
  10367. else {
  10368. $uploaded_content = '';
  10369. }
  10370. // 美术风格
  10371. $input_art_style = getProp($data, 'art_style');
  10372. if (!$input_art_style) {
  10373. $mappedArtStyle = getProp($anime, 'art_style');
  10374. }else {
  10375. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  10376. }
  10377. if (!$mappedArtStyle) {
  10378. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  10379. }else {
  10380. if (strstr($mappedArtStyle, '基础画风风格词')) {
  10381. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  10382. }else {
  10383. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  10384. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  10385. }
  10386. }
  10387. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10388. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  10389. // 强制要求:
  10390. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  10391. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  10392. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  10393. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  10394. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  10395. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  10396. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  10397. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  10398. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  10399. // 10.分镜要和场景列表、人物主体保持一致\n
  10400. // 普通要求:
  10401. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10402. // {$role_demo}
  10403. // {$scene_demo}
  10404. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10405. // 4.1片段分割逻辑(优先级从高到低):
  10406. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10407. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10408. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10409. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10410. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10411. // - 片段数量格式为: 片段数量:8
  10412. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10413. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10414. // 4.3分镜结构:每个分镜包含以下字段:
  10415. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  10416. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  10417. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10418. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  10419. // - 运镜:场景+画面描述+运镜
  10420. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  10421. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10422. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10423. // 5.$mappedArtStyle_prompt\n\n
  10424. // 示例格式:\n
  10425. // 第1集:隐形的守护者
  10426. // ###故事梗概
  10427. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10428. // ###美术风格
  10429. // 基础画风风格词:胡金铨武侠
  10430. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10431. // ###主体列表
  10432. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10433. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10434. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10435. // ###场景列表
  10436. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10437. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10438. // ###分段剧本
  10439. // 片段数量:8
  10440. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10441. // ##片段1
  10442. // 时长:12s
  10443. // 分镜1
  10444. // 场景:边境小镇街道
  10445. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10446. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10447. // 配音台词:
  10448. // 背景音效:
  10449. // 分镜2
  10450. // 场景:悦来酒馆
  10451. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10452. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10453. // 配音台词:
  10454. // 背景音效:
  10455. // 分镜3
  10456. // 场景:悦来酒馆
  10457. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10458. // 运镜:从中景推向令牌特写。
  10459. // 配音台词:
  10460. // 背景音效:
  10461. // 分镜4
  10462. // 场景:悦来酒馆
  10463. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10464. // 运镜:极速推向酒水溅起的瞬间。
  10465. // 配音台词:
  10466. // 背景音效:
  10467. // 分镜5
  10468. // 镜头描述
  10469. // 场景:悦来酒馆
  10470. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10471. // 运镜:固定机位,利用倾斜构图制造压迫感。
  10472. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10473. // 背景音效:
  10474. // \n\n";
  10475. /*
  10476. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  10477. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  10478. // ===================================================================
  10479. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10480. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10481. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10482. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10483. 强制要求:
  10484. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10485. 普通要求:
  10486. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10487. {$role_demo}
  10488. {$scene_demo}
  10489. {$prop_demo}
  10490. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10491. 5.1片段分割逻辑(优先级从高到低):
  10492. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10493. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10494. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10495. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10496. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10497. - 片段数量格式为: 片段数量:8
  10498. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10499. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10500. 5.3分镜结构:每个分镜包含以下字段:
  10501. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10502. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10503. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10504. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10505. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10506. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10507. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10508. - 运镜:场景+画面描述+运镜
  10509. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10510. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10511. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10512. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10513. 6.《情绪-视听语言映射表》:
  10514. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10515. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10516. -----|---------|------------|----------------
  10517. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10518. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10519. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10520. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10521. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10522. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10523. -----|---------|------------|----------------
  10524. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10525. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10526. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10527. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10528. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10529. --------|---------|--------------|-------------
  10530. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10531. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10532. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10533. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10534. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10535. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10536. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10537. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10538. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10539. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10540. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10541. -----|---------|------------|------------
  10542. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10543. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10544. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10545. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10546. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10547. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10548. --------|---------|--------------|----------
  10549. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10550. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10551. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10552. 6.6 声音设计与潜意识影响 (Soundscape)
  10553. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10554. -----|---------|------------|------------------
  10555. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10556. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10557. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10558. 理论基石:
  10559. - The Five C's of Cinematography by Joseph V. Mascelli
  10560. - Film Art: An Introduction by David Bordwell
  10561. - Sight, Sound, Motion by Herbert Zettl
  10562. - Notes on the Cinematograph by Robert Bresson
  10563. \n\n
  10564. 7.{$mappedArtStyle_prompt}
  10565. 示例格式:\n
  10566. 第1集:隐形的守护者
  10567. ###故事梗概
  10568. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10569. ###美术风格
  10570. 基础画风风格词:胡金铨武侠
  10571. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10572. ###主体列表
  10573. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10574. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10575. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10576. ###场景列表
  10577. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10578. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10579. ###道具列表
  10580. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10581. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10582. ###分段剧本
  10583. 片段数量:8
  10584. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10585. ##片段1
  10586. 时长:12s
  10587. 分镜1
  10588. 出场角色:刀疤脸
  10589. 场景:边境小镇街道
  10590. 出场道具:酒杯-高脚杯
  10591. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10592. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10593. 配音台词:
  10594. 背景音效:
  10595. 分镜2
  10596. 出场角色:刀疤脸
  10597. 场景:悦来酒馆
  10598. 出场道具:酒杯-高脚杯
  10599. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10600. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10601. 配音台词:
  10602. 背景音效:
  10603. 分镜3
  10604. 出场角色:刀疤脸
  10605. 场景:悦来酒馆
  10606. 出场道具:酒杯-高脚杯
  10607. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10608. 运镜:从中景推向令牌特写。
  10609. 配音台词:
  10610. 背景音效:
  10611. 分镜4
  10612. 出场角色:刀疤脸
  10613. 场景:悦来酒馆
  10614. 出场道具:酒杯-高脚杯
  10615. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10616. 运镜:极速推向酒水溅起的瞬间。
  10617. 配音台词:
  10618. 背景音效:
  10619. 分镜5
  10620. 出场角色:刀疤脸
  10621. 场景:悦来酒馆
  10622. 出场道具:酒杯-高脚杯
  10623. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10624. 运镜:固定机位,利用倾斜构图制造压迫感。
  10625. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10626. 背景音效:
  10627. \n\n";
  10628. */
  10629. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10630. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10631. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10632. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10633. 强制要求:
  10634. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10635. 普通要求:
  10636. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  10637. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  10638. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  10639. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  10640. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10641. 5.1片段分割逻辑(优先级从高到低):
  10642. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10643. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10644. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10645. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10646. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10647. - 片段数量格式为: 片段数量:8
  10648. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10649. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10650. 5.3分镜结构:每个分镜包含以下字段:
  10651. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  10652. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10653. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10654. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10655. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10656. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10657. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10658. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10659. - 运镜:场景+画面描述+运镜
  10660. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10661. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10662. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10663. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10664. 6.《情绪-视听语言映射表》:
  10665. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10666. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10667. -----|---------|------------|----------------
  10668. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10669. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10670. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10671. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10672. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10673. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10674. -----|---------|------------|----------------
  10675. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10676. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10677. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10678. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10679. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10680. --------|---------|--------------|-------------
  10681. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10682. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10683. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10684. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10685. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10686. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10687. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10688. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10689. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10690. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10691. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10692. -----|---------|------------|------------
  10693. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10694. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10695. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10696. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10697. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10698. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10699. --------|---------|--------------|----------
  10700. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10701. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10702. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10703. 6.6 声音设计与潜意识影响 (Soundscape)
  10704. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10705. -----|---------|------------|------------------
  10706. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10707. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10708. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10709. 理论基石:
  10710. - The Five C's of Cinematography by Joseph V. Mascelli
  10711. - Film Art: An Introduction by David Bordwell
  10712. - Sight, Sound, Motion by Herbert Zettl
  10713. - Notes on the Cinematograph by Robert Bresson
  10714. \n\n
  10715. 7.美术风格要求见文末【本次生成数据-美术风格】。
  10716. 示例格式:\n
  10717. 第1集:隐形的守护者
  10718. ###故事梗概
  10719. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10720. ###美术风格
  10721. 基础画风风格词:胡金铨武侠
  10722. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10723. ###主体列表
  10724. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10725. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10726. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10727. ###场景列表
  10728. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10729. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10730. ###道具列表
  10731. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10732. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10733. ###分段剧本
  10734. 片段数量:8
  10735. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10736. ##片段1
  10737. 时长:12s
  10738. 分镜1
  10739. 出场角色:刀疤脸
  10740. 场景:边境小镇街道
  10741. 出场道具:酒杯-高脚杯
  10742. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10743. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10744. 配音台词:
  10745. 背景音效:
  10746. 分镜2
  10747. 出场角色:刀疤脸
  10748. 场景:悦来酒馆
  10749. 出场道具:酒杯-高脚杯
  10750. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10751. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10752. 配音台词:
  10753. 背景音效:
  10754. 分镜3
  10755. 出场角色:刀疤脸
  10756. 场景:悦来酒馆
  10757. 出场道具:酒杯-高脚杯
  10758. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10759. 运镜:从中景推向令牌特写。
  10760. 配音台词:
  10761. 背景音效:
  10762. 分镜4
  10763. 出场角色:刀疤脸
  10764. 场景:悦来酒馆
  10765. 出场道具:酒杯-高脚杯
  10766. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10767. 运镜:极速推向酒水溅起的瞬间。
  10768. 配音台词:
  10769. 背景音效:
  10770. 分镜5
  10771. 出场角色:刀疤脸
  10772. 场景:悦来酒馆
  10773. 出场道具:酒杯-高脚杯
  10774. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10775. 运镜:固定机位,利用倾斜构图制造压迫感。
  10776. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10777. 背景音效:
  10778. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  10779. 【本次剧集信息】剧集序号是{$episode_number}。
  10780. 【本次生成数据-主体列表】{$role_demo}
  10781. 【本次生成数据-场景列表】{$scene_demo}
  10782. 【本次生成数据-道具列表】{$prop_demo}
  10783. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  10784. \n\n";
  10785. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10786. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  10787. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  10788. $is_regenerate_version = true;
  10789. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  10790. $prompt = $origin_prompt;
  10791. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  10792. // 获取章节内容
  10793. $full_content = getProp($anime, 'content');
  10794. if ($uploaded_content) {
  10795. $full_content = $uploaded_content;
  10796. }
  10797. // 根据章节内容拆分章节
  10798. $chapters = splitContent($full_content);
  10799. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  10800. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  10801. $messages = [];
  10802. if ($prompt == '确认分镜大纲') {
  10803. // 暂时保留
  10804. $content = $chapter_content;
  10805. if ($is_single) $content = $full_content; // 单剧集使用全文
  10806. if (!$content) {
  10807. Utils::throwError('20003:章节内容无法获取,请确认');
  10808. }
  10809. $question = $is_single
  10810. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  10811. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  10812. // 构建消息
  10813. $messages[] =
  10814. [
  10815. 'role' => 'user',
  10816. 'content' => $question
  10817. ];
  10818. }else if ($prompt == '继续策划下一集') {
  10819. if ($is_single) {
  10820. Utils::throwError('20003:单剧集不支持继续策划下一集');
  10821. }
  10822. $content = $chapter_content;
  10823. if (!$content) {
  10824. Utils::throwError('20003:章节内容无法获取,请确认');
  10825. }
  10826. // 获取上一集最后记录
  10827. $prev_sequence = $episode_number - 1;
  10828. $messages = array_merge(
  10829. [
  10830. [
  10831. 'role' => 'system',
  10832. 'content' => $demo
  10833. ]
  10834. ],
  10835. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  10836. );
  10837. // 构建消息
  10838. $messages[] =
  10839. [
  10840. 'role' => 'user',
  10841. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  10842. ];
  10843. /*
  10844. // 旧版逻辑
  10845. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  10846. // 构建消息
  10847. $messages[] =
  10848. [
  10849. 'role' => 'user',
  10850. 'content' => $question
  10851. ];
  10852. */
  10853. // dd($messages);
  10854. }else {
  10855. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  10856. if (!$content) {
  10857. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  10858. }
  10859. if (!$content) {
  10860. Utils::throwError('20003:章节内容无法获取,请确认');
  10861. }
  10862. $messages = array_merge(
  10863. [
  10864. [
  10865. 'role' => 'system',
  10866. 'content' => $demo
  10867. ]
  10868. ],
  10869. $this->getEpisodeChatMessages($anime_id, $episode_number)
  10870. );
  10871. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  10872. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  10873. if ($origin_prompt) {
  10874. $question .= "本次修改要求如下:\n{$origin_prompt}";
  10875. }
  10876. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  10877. $messages[] = [
  10878. 'role' => 'user',
  10879. 'content' => "本集剧情内容:\n\n{$content}\n"
  10880. ];
  10881. $messages[] =
  10882. [
  10883. 'role' => 'user',
  10884. 'content' => $question
  10885. ];
  10886. }
  10887. // 处理文本模型
  10888. $model = getProp($data, 'model');
  10889. if (!$model) {
  10890. // 用户没有输入,从anime表获取
  10891. $model = getProp($anime, 'model');
  10892. if (!$model) {
  10893. // anime表也没有,使用默认值
  10894. $model = 'deepseek-v4-pro';
  10895. }
  10896. }
  10897. // 验证模型是否在可用模型表中
  10898. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10899. $model = 'deepseek-v4-pro';
  10900. }
  10901. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  10902. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  10903. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  10904. if ($model === 'deepseek-chat') {
  10905. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  10906. $model = 'deepseek-v4-flash';
  10907. $thinkingMode = 'disabled';
  10908. } elseif ($model === 'deepseek-reasoner') {
  10909. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  10910. $model = 'deepseek-v4-flash';
  10911. $thinkingMode = 'enabled';
  10912. }
  10913. $post_data = [
  10914. 'model' => $model,
  10915. 'messages' => $messages,
  10916. // 'max_tokens' => 8192,
  10917. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10918. 'frequency_penalty' => 0,
  10919. 'presence_penalty' => 0,
  10920. 'response_format' => ['type' => 'text'],
  10921. 'thinking' => ['type' => $thinkingMode],
  10922. 'stream' => true // 启用流式输出
  10923. ];
  10924. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10925. // 根据模型类型选择调用方法
  10926. $fullContent = '';
  10927. $fullReasoningContent = '';
  10928. $usage = [];
  10929. try {
  10930. $streamGenerator = $this->dispatchStreamByModel($post_data);
  10931. // 验证返回值类型
  10932. if (!is_iterable($streamGenerator)) {
  10933. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  10934. dLog('deepseek')->error('chat流式生成器无效', [
  10935. 'generator_type' => $errorType,
  10936. 'model' => $model,
  10937. 'anime_id' => $anime_id,
  10938. 'episode_number' => $episode_number
  10939. ]);
  10940. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  10941. 'type' => $errorType,
  10942. 'model' => $model
  10943. ]);
  10944. yield [
  10945. 'type' => 'error',
  10946. 'episode' => [],
  10947. 'answer' => '',
  10948. 'reasoning' => '',
  10949. 'usage' => [],
  10950. 'error' => '接口返回数据异常,请重新请求'
  10951. ];
  10952. return;
  10953. }
  10954. // 处理流式输出
  10955. foreach ($streamGenerator as $chunk) {
  10956. if (isset($chunk['type'])) {
  10957. if ($chunk['type'] === 'done') {
  10958. // 最终结果
  10959. $fullContent = $chunk['full_content'];
  10960. $fullReasoningContent = $chunk['full_reasoning'];
  10961. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  10962. } else {
  10963. // 逐块yield数据
  10964. yield $chunk;
  10965. }
  10966. }
  10967. }
  10968. } catch (\Exception $e) {
  10969. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  10970. 'model' => $model,
  10971. 'anime_id' => $anime_id,
  10972. 'episode_number' => $episode_number,
  10973. 'trace' => $e->getTraceAsString()
  10974. ]);
  10975. logDB('deepseek', 'error', 'chat流式处理失败', [
  10976. 'error' => $e->getMessage(),
  10977. 'model' => $model
  10978. ]);
  10979. yield [
  10980. 'type' => 'error',
  10981. 'episode' => [],
  10982. 'answer' => '',
  10983. 'reasoning' => '',
  10984. 'usage' => [],
  10985. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  10986. ];
  10987. return;
  10988. }
  10989. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  10990. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  10991. dLog('deepseek')->info('完整内容: '.$fullContent);
  10992. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  10993. // 处理完整内容并返回最终结果
  10994. $episode_arr = handleEpisodeContentForAce($fullContent);
  10995. dLog('deepseek')->info('解析内容: ', $episode_arr);
  10996. logDB('deepseek', 'info', '解析内容', $episode_arr);
  10997. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  10998. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  10999. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11000. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  11001. // }
  11002. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  11003. $max_retries = 3;
  11004. $retry_count = 0;
  11005. $validation_failed = false;
  11006. $validation_error_msg = '';
  11007. // 验证生成的内容
  11008. if ($anime_script_id) {
  11009. // 检查是否有acts数据
  11010. if (empty($episode_arr['acts'])) {
  11011. $validation_failed = true;
  11012. $validation_error_msg = '未生成分镜剧本相关的内容';
  11013. } else {
  11014. // 校验主体列表:不能为空主体(旁白不算)
  11015. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11016. // 过滤掉"旁白"角色
  11017. $generated_roles = array_filter($generated_roles, function($role) {
  11018. return $role !== '旁白';
  11019. });
  11020. if (empty($generated_roles)) {
  11021. $validation_failed = true;
  11022. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11023. }
  11024. // 仅当存在强制主体设定时校验主体列表
  11025. if (!$validation_failed && !empty($extra_roles)) {
  11026. $expected_roles = array_keys($extra_roles);
  11027. // 找出生成的主体中不在预期列表中的主体
  11028. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11029. if (!empty($invalid_roles)) {
  11030. $validation_failed = true;
  11031. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11032. }
  11033. }
  11034. // 仅当存在强制场景设定时校验场景列表
  11035. if (!$validation_failed && !empty($extra_scenes)) {
  11036. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11037. $expected_scenes = array_keys($extra_scenes);
  11038. // 找出生成的场景中不在预期列表中的场景
  11039. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11040. if (!empty($invalid_scenes)) {
  11041. $validation_failed = true;
  11042. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11043. }
  11044. }
  11045. // 仅当存在强制道具设定时校验道具列表
  11046. if (!$validation_failed && !empty($extra_props)) {
  11047. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11048. $expected_props = array_keys($extra_props);
  11049. // 找出生成的道具中不在预期列表中的道具
  11050. $invalid_props = array_diff($generated_props, $expected_props);
  11051. if (!empty($invalid_props)) {
  11052. $validation_failed = true;
  11053. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11054. }
  11055. }
  11056. }
  11057. } else {
  11058. // 如果没有anime_script_id,只检查是否有acts数据
  11059. if (empty($episode_arr['acts'])) {
  11060. $validation_failed = true;
  11061. $validation_error_msg = '未生成分镜剧本相关的内容';
  11062. } else {
  11063. // 校验主体列表:不能为空主体(旁白不算)
  11064. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11065. // 过滤掉"旁白"角色
  11066. $generated_roles = array_filter($generated_roles, function($role) {
  11067. return $role !== '旁白';
  11068. });
  11069. if (empty($generated_roles)) {
  11070. $validation_failed = true;
  11071. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11072. }
  11073. }
  11074. }
  11075. // 重试逻辑
  11076. while ($validation_failed && $retry_count < $max_retries) {
  11077. $retry_count++;
  11078. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  11079. 'reason' => $validation_error_msg,
  11080. 'anime_id' => $anime_id,
  11081. 'episode_number' => $episode_number
  11082. ]);
  11083. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  11084. 'reason' => $validation_error_msg,
  11085. 'anime_id' => $anime_id
  11086. ]);
  11087. // 发送流式重试提示
  11088. yield [
  11089. 'type' => 'retry',
  11090. 'retry_count' => $retry_count,
  11091. 'reason' => $validation_error_msg
  11092. ];
  11093. // 构建重试提示词
  11094. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  11095. if ($anime_script_id) {
  11096. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  11097. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11098. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  11099. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  11100. } else {
  11101. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11102. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  11103. }
  11104. // 添加重试消息到messages
  11105. $messages[] = [
  11106. 'role' => 'assistant',
  11107. 'content' => $fullContent
  11108. ];
  11109. $messages[] = [
  11110. 'role' => 'user',
  11111. 'content' => $retry_prompt
  11112. ];
  11113. // 更新post_data的messages
  11114. $post_data['messages'] = $messages;
  11115. // 重新调用API
  11116. try {
  11117. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11118. // 处理流式输出
  11119. $fullContent = '';
  11120. $fullReasoningContent = '';
  11121. foreach ($streamGenerator as $chunk) {
  11122. if (isset($chunk['type'])) {
  11123. if ($chunk['type'] === 'done') {
  11124. $fullContent = $chunk['full_content'];
  11125. $fullReasoningContent = $chunk['full_reasoning'];
  11126. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11127. } else {
  11128. yield $chunk;
  11129. }
  11130. }
  11131. }
  11132. // 重新解析内容
  11133. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11134. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  11135. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  11136. $episode_arr = handleEpisodeContentForAce($fullContent);
  11137. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  11138. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11139. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11140. // }
  11141. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  11142. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  11143. // 重新验证
  11144. $validation_failed = false;
  11145. $validation_error_msg = '';
  11146. if ($anime_script_id) {
  11147. if (empty($episode_arr['acts'])) {
  11148. $validation_failed = true;
  11149. $validation_error_msg = '未生成分镜剧本相关的内容';
  11150. } else {
  11151. // 校验主体列表:不能为空主体(旁白不算)
  11152. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11153. // 过滤掉"旁白"角色
  11154. $generated_roles = array_filter($generated_roles, function($role) {
  11155. return $role !== '旁白';
  11156. });
  11157. if (empty($generated_roles)) {
  11158. $validation_failed = true;
  11159. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11160. }
  11161. // 仅当存在强制主体设定时校验主体列表
  11162. if (!$validation_failed && !empty($extra_roles)) {
  11163. $expected_roles = array_keys($extra_roles);
  11164. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11165. if (!empty($invalid_roles)) {
  11166. $validation_failed = true;
  11167. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11168. }
  11169. }
  11170. // 仅当存在强制场景设定时校验场景列表
  11171. if (!$validation_failed && !empty($extra_scenes)) {
  11172. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11173. $expected_scenes = array_keys($extra_scenes);
  11174. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11175. if (!empty($invalid_scenes)) {
  11176. $validation_failed = true;
  11177. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11178. }
  11179. }
  11180. // 仅当存在强制道具设定时校验道具列表
  11181. if (!$validation_failed && !empty($extra_props)) {
  11182. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11183. $expected_props = array_keys($extra_props);
  11184. $invalid_props = array_diff($generated_props, $expected_props);
  11185. if (!empty($invalid_props)) {
  11186. $validation_failed = true;
  11187. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11188. }
  11189. }
  11190. }
  11191. } else {
  11192. if (empty($episode_arr['acts'])) {
  11193. $validation_failed = true;
  11194. $validation_error_msg = '未生成分镜剧本相关的内容';
  11195. } else {
  11196. // 校验主体列表:不能为空主体(旁白不算)
  11197. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11198. // 过滤掉"旁白"角色
  11199. $generated_roles = array_filter($generated_roles, function($role) {
  11200. return $role !== '旁白';
  11201. });
  11202. if (empty($generated_roles)) {
  11203. $validation_failed = true;
  11204. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11205. }
  11206. }
  11207. }
  11208. } catch (\Exception $e) {
  11209. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  11210. 'trace' => $e->getTraceAsString()
  11211. ]);
  11212. break;
  11213. }
  11214. }
  11215. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  11216. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  11217. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  11218. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  11219. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  11220. if ($validation_failed && $retry_count >= $max_retries) {
  11221. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  11222. 'retry_count' => $retry_count,
  11223. 'last_error' => $validation_error_msg
  11224. ]);
  11225. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  11226. 'error' => $validation_error_msg,
  11227. 'anime_id' => $anime_id
  11228. ]);
  11229. $validation_failed = false;
  11230. $validation_error_msg = '';
  11231. }
  11232. // 如果重试后仍然失败
  11233. if ($validation_failed) {
  11234. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  11235. 'retry_count' => $retry_count,
  11236. 'last_error' => $validation_error_msg
  11237. ]);
  11238. try {
  11239. $now = date('Y-m-d H:i:s');
  11240. $records = [
  11241. [
  11242. 'uid' => $uid,
  11243. 'anime_id' => $anime_id,
  11244. 'sequence' => $episode_number,
  11245. 'role' => 'user',
  11246. 'content' => $prompt,
  11247. 'created_at' => $now,
  11248. 'updated_at' => $now
  11249. ],
  11250. [
  11251. 'uid' => $uid,
  11252. 'anime_id' => $anime_id,
  11253. 'sequence' => $episode_number,
  11254. 'role' => 'assistant',
  11255. 'content' => $fullContent,
  11256. 'created_at' => $now,
  11257. 'updated_at' => $now
  11258. ]
  11259. ];
  11260. DB::table('mp_anime_records')->insert($records);
  11261. } catch (\Exception $e) {
  11262. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  11263. }
  11264. yield [
  11265. 'type' => 'done',
  11266. 'episode' => [],
  11267. 'answer' => $fullContent,
  11268. 'reasoning' => $fullReasoningContent,
  11269. 'usage' => $usage,
  11270. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  11271. ];
  11272. return;
  11273. }
  11274. // 验证成功,记录日志
  11275. if ($retry_count > 0) {
  11276. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  11277. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  11278. }
  11279. // 老逻辑
  11280. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  11281. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  11282. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  11283. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  11284. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  11285. $existing_props = is_array($existing_props) ? $existing_props : [];
  11286. $now = date('Y-m-d H:i:s');
  11287. try {
  11288. DB::beginTransaction();
  11289. $saveResult = $this->saveEpisodeVersionData(
  11290. $anime_id,
  11291. $episode_number,
  11292. $episode_arr,
  11293. $existing_roles,
  11294. $existing_scenes,
  11295. $existing_props,
  11296. $current_episode,
  11297. $base_episode,
  11298. $is_regenerate_version,
  11299. $content,
  11300. $now,
  11301. $ref_products
  11302. );
  11303. $episode = $saveResult['episode'];
  11304. $episode_id = $saveResult['episode_id'];
  11305. $merged_roles = $saveResult['merged_roles'];
  11306. $merged_scenes = $saveResult['merged_scenes'];
  11307. $merged_props = $saveResult['merged_props'];
  11308. $record_content = $origin_prompt;
  11309. if ($uploaded_content !== '') {
  11310. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  11311. }
  11312. $records = [
  11313. [
  11314. 'uid' => $uid,
  11315. 'anime_id' => $anime_id,
  11316. 'role' => 'user',
  11317. 'content' => $record_content,
  11318. 'sequence' => $episode_number,
  11319. 'episode_id' => $episode_id,
  11320. 'created_at' => $now,
  11321. 'updated_at' => $now
  11322. ],
  11323. [
  11324. 'uid' => $uid,
  11325. 'anime_id' => $anime_id,
  11326. 'role' => 'assistant',
  11327. 'content' => $fullContent,
  11328. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  11329. 'sequence' => $episode_number,
  11330. 'episode_id' => $episode_id,
  11331. 'created_at' => $now,
  11332. 'updated_at' => $now
  11333. ]
  11334. ];
  11335. $boolen4 = DB::table('mp_anime_records')->insert($records);
  11336. if (!$boolen4) {
  11337. Utils::throwError('20003:对话记录保存失败');
  11338. }
  11339. // 保存模型到anime表
  11340. $update_anime_data = [
  11341. 'model' => $model,
  11342. 'updated_at' => $now
  11343. ];
  11344. if ($uploaded_content) {
  11345. $update_anime_data['content'] = $uploaded_content;
  11346. }
  11347. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  11348. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11349. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11350. 'anime_id' => $anime_id,
  11351. 'episode_number' => $episode_number,
  11352. 'model' => $model,
  11353. 'source' => 'chatForAce',
  11354. ]);
  11355. }catch (\Exception $e) {
  11356. DB::rollBack();
  11357. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  11358. yield [
  11359. 'type' => 'done',
  11360. 'answer' => $fullContent,
  11361. 'reasoning' => $fullReasoningContent,
  11362. 'usage' => $usage,
  11363. 'error' => $e->getMessage(),
  11364. ];
  11365. return;
  11366. }
  11367. DB::commit();
  11368. if ($is_global_generate_pics) {
  11369. // // 批量生成全局角色图片
  11370. // $this->batchSetGlobalRoleImg([
  11371. // 'anime_id' => $anime_id,
  11372. // ], true);
  11373. // // 批量生成全局场景图片
  11374. // $this->batchSetGlobalSceneImg([
  11375. // 'anime_id' => $anime_id,
  11376. // ], true);
  11377. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  11378. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  11379. }
  11380. $episode['episode_id'] = $episode_id;
  11381. $episode['roles'] = $merged_roles;
  11382. $episode['scenes'] = $merged_scenes;
  11383. $episode['props'] = $merged_props;
  11384. $episode['end_episode_sequence'] = $end_episode_sequence;
  11385. // 获取mp_animes表中的视频参数
  11386. $episode['video_params'] = [
  11387. 'video_model' => getProp($anime, 'video_model'),
  11388. 'video_resolution' => getProp($anime, 'video_resolution'),
  11389. 'ratio' => getProp($anime, 'video_ratio'),
  11390. ];
  11391. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11392. yield [
  11393. 'type' => 'done',
  11394. 'episode' => $episode,
  11395. 'answer' => $fullContent,
  11396. 'reasoning' => $fullReasoningContent,
  11397. 'usage' => $usage
  11398. ];
  11399. }
  11400. /**
  11401. * chatForAce的非流式版本 - 用于定时任务
  11402. * 只获取最终 type=done 的数据,并验证必要字段
  11403. *
  11404. * @param array $data 请求数据
  11405. * @return array 生成结果
  11406. */
  11407. public function chatForAceNonStream($data) {
  11408. $finalResult = null;
  11409. // 调用流式方法,只保存 type=done 的数据
  11410. foreach ($this->chatForAce($data) as $chunk) {
  11411. // 只关注最终结果
  11412. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  11413. $finalResult = $chunk;
  11414. break; // 找到 done 就退出循环
  11415. }
  11416. }
  11417. // 验证最终结果
  11418. if (!$finalResult) {
  11419. return ['error' => '生成失败:未获取到最终结果'];
  11420. }
  11421. // 检查是否有错误
  11422. if (isset($finalResult['error']) && $finalResult['error']) {
  11423. return $finalResult;
  11424. }
  11425. // 验证必要字段
  11426. $episode = $finalResult['episode'] ?? [];
  11427. // 验证 roles(旁白不算主体,过滤后不能为空)
  11428. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  11429. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  11430. }
  11431. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  11432. return $role !== '旁白';
  11433. });
  11434. if (empty($nonNarratorRoles)) {
  11435. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  11436. }
  11437. // 验证 scenes
  11438. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  11439. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  11440. }
  11441. // 验证 props(道具可以为空,但必须存在且为数组)
  11442. if (!isset($episode['props']) || !is_array($episode['props'])) {
  11443. $episode['props'] = [];
  11444. }
  11445. // 验证 acts(分镜剧本)
  11446. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  11447. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  11448. }
  11449. // 更新验证后的 episode 数据
  11450. $finalResult['episode'] = $episode;
  11451. // 记录验证成功日志
  11452. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  11453. 'roles_count' => count($episode['roles']),
  11454. 'scenes_count' => count($episode['scenes']),
  11455. 'props_count' => count($episode['props']),
  11456. 'acts_count' => count($episode['acts'])
  11457. ]);
  11458. return $finalResult;
  11459. }
  11460. /**
  11461. * 批量生成多个分集
  11462. *
  11463. * @param array $data 请求数据
  11464. * @return array 任务信息
  11465. */
  11466. public function batchGenerateEpisodes($data) {
  11467. $uid = Site::getUid();
  11468. $cpid = Site::getCpid();
  11469. $anime_id = getProp($data, 'anime_id');
  11470. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  11471. $start_episode_number = getProp($data, 'start_episode_number');
  11472. $end_episode_number = getProp($data, 'end_episode_number');
  11473. if (!$anime_id) {
  11474. Utils::throwError('20003:anime_id参数缺失');
  11475. }
  11476. if ($generate_episode_number < 1) {
  11477. Utils::throwError('20003:生成集数必须大于0');
  11478. }
  11479. // 获取动漫信息
  11480. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11481. if (!$anime) {
  11482. Utils::throwError('20003:该剧集不存在');
  11483. }
  11484. // 检查是否是全能模式
  11485. if ((int)getProp($anime, 'ace_mode') !== 1) {
  11486. Utils::throwError('20003:只有全能模式才支持批量生成');
  11487. }
  11488. // 检查是否是多剧集模式
  11489. if ((int)getProp($anime, 'is_multi') !== 1) {
  11490. Utils::throwError('20003:单剧集不支持批量生成');
  11491. }
  11492. // 指定起始/结束剧集序号时的校验
  11493. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  11494. || ($end_episode_number !== null && $end_episode_number !== '');
  11495. if ($hasSpecifiedRange) {
  11496. if ($start_episode_number === null || $start_episode_number === ''
  11497. || $end_episode_number === null || $end_episode_number === '') {
  11498. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  11499. }
  11500. $start_episode_number = (int)$start_episode_number;
  11501. $end_episode_number = (int)$end_episode_number;
  11502. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  11503. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  11504. }
  11505. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  11506. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11507. ->where('anime_id', $anime_id)
  11508. ->where('is_default', 1)
  11509. ->max('episode_number');
  11510. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11511. $nextEpisodeNumber = $currentMaxEpisode + 1;
  11512. if ($start_episode_number !== $nextEpisodeNumber) {
  11513. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  11514. }
  11515. $startEpisodeNumber = $start_episode_number;
  11516. $endEpisodeNumber = $end_episode_number;
  11517. } else {
  11518. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  11519. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11520. ->where('anime_id', $anime_id)
  11521. ->where('is_default', 1)
  11522. ->max('episode_number');
  11523. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11524. // 确定起始集数
  11525. $startEpisodeNumber = $currentMaxEpisode + 1;
  11526. // 计算结束集数
  11527. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  11528. }
  11529. // 本次实际生成的集数
  11530. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  11531. // 检查是否超过总集数限制
  11532. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  11533. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  11534. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  11535. }
  11536. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  11537. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  11538. ->where('anime_id', $anime_id)
  11539. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11540. ->pluck('episode_number')
  11541. ->unique()
  11542. ->sort()
  11543. ->values()
  11544. ->toArray();
  11545. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  11546. ->where('anime_id', $anime_id)
  11547. ->where('is_default', 1)
  11548. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11549. ->pluck('episode_number')
  11550. ->unique()
  11551. ->sort()
  11552. ->values()
  11553. ->toArray();
  11554. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  11555. $duplicateMessages = [];
  11556. if (!empty($duplicatedBatchEpisodes)) {
  11557. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  11558. }
  11559. if (!empty($duplicatedAnimeEpisodes)) {
  11560. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  11561. }
  11562. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  11563. }
  11564. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  11565. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  11566. ->where('anime_id', $anime_id)
  11567. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11568. ->whereIn('status', ['pending', 'processing', 'completed'])
  11569. ->count();
  11570. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  11571. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  11572. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  11573. if ($needEpisodeCount > 0) {
  11574. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  11575. }
  11576. $now = date('Y-m-d H:i:s');
  11577. $createdTasks = [];
  11578. $skippedTasks = [];
  11579. // 为每一集创建详情记录
  11580. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  11581. // 检查是否已有该集的任务记录
  11582. $existingTask = DB::table('mp_batch_episode_generation_details')
  11583. ->where('anime_id', $anime_id)
  11584. ->where('episode_number', $episodeNumber)
  11585. ->first();
  11586. if ($existingTask) {
  11587. // 如果已存在且未完成,跳过
  11588. if (in_array($existingTask->status, ['pending', 'processing'])) {
  11589. $skippedTasks[] = $episodeNumber;
  11590. continue;
  11591. }
  11592. // 如果是失败状态,可以重新创建(删除旧记录)
  11593. if ($existingTask->status === 'failed') {
  11594. DB::table('mp_batch_episode_generation_details')
  11595. ->where('id', $existingTask->id)
  11596. ->delete();
  11597. }
  11598. // 如果是已完成状态,也跳过
  11599. if ($existingTask->status === 'completed') {
  11600. $skippedTasks[] = $episodeNumber;
  11601. continue;
  11602. }
  11603. }
  11604. // 准备任务数据
  11605. $taskData = [
  11606. 'anime_id' => $anime_id,
  11607. 'uid' => $uid,
  11608. 'cpid' => $cpid,
  11609. 'episode_number' => $episodeNumber,
  11610. 'status' => 'pending',
  11611. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  11612. 'retry_count' => 0,
  11613. 'created_at' => $now,
  11614. 'updated_at' => $now
  11615. ];
  11616. // 创建任务记录
  11617. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  11618. if ($taskId) {
  11619. $createdTasks[] = $episodeNumber;
  11620. }
  11621. }
  11622. if (empty($createdTasks)) {
  11623. if (!empty($skippedTasks)) {
  11624. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  11625. } else {
  11626. Utils::throwError('20003:创建批量生成任务失败');
  11627. }
  11628. }
  11629. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  11630. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  11631. $uid,
  11632. $cpid,
  11633. $anime_id,
  11634. $generate_episode_number,
  11635. $startEpisodeNumber,
  11636. $endEpisodeNumber
  11637. );
  11638. return [
  11639. 'anime_id' => $anime_id,
  11640. 'start_episode' => $startEpisodeNumber,
  11641. 'end_episode' => $endEpisodeNumber,
  11642. 'total_episodes' => $totalEpisodeCount,
  11643. 'created_episodes' => $createdTasks,
  11644. 'skipped_episodes' => $skippedTasks,
  11645. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  11646. "已创建: " . implode(',', $createdTasks) .
  11647. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  11648. 'task_center_id' => $taskCenterId
  11649. ];
  11650. }
  11651. /**
  11652. * 根据入参创建或复用批量生成分集的任务中心记录
  11653. *
  11654. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  11655. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  11656. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  11657. *
  11658. * @param int|string $uid
  11659. * @param int|string $cpid
  11660. * @param int|string $anime_id
  11661. * @param int $generate_episode_number
  11662. * @param int $startEpisodeNumber
  11663. * @param int $endEpisodeNumber
  11664. * @return int 任务中心ID
  11665. */
  11666. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  11667. $params = [
  11668. 'anime_id' => (int)$anime_id,
  11669. 'generate_episode_number' => (int)$generate_episode_number,
  11670. 'start_episode' => (int)$startEpisodeNumber,
  11671. 'end_episode' => (int)$endEpisodeNumber,
  11672. ];
  11673. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  11674. $paramsMd5 = md5(json_encode([
  11675. 'anime_id' => (int)$anime_id,
  11676. 'generate_episode_number' => (int)$generate_episode_number,
  11677. 'start_episode' => (int)$startEpisodeNumber,
  11678. 'end_episode' => (int)$endEpisodeNumber,
  11679. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  11680. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  11681. $existing = DB::table('mp_task_center')
  11682. ->where('uid', (int)$uid)
  11683. ->where('cpid', (int)$cpid)
  11684. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11685. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11686. ->where('params_md5', $paramsMd5)
  11687. ->orderBy('id', 'desc')
  11688. ->first();
  11689. if ($existing) {
  11690. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  11691. 'anime_id' => $anime_id,
  11692. 'task_center_id' => $existing->id,
  11693. 'params_md5' => $paramsMd5,
  11694. ]);
  11695. return (int)$existing->id;
  11696. }
  11697. $now = date('Y-m-d H:i:s');
  11698. DB::table('mp_task_center')->insertOrIgnore([
  11699. 'uid' => (int)$uid,
  11700. 'cpid' => (int)$cpid,
  11701. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  11702. 'title' => '批量生成分集',
  11703. 'ref_task_id' => 0,
  11704. 'status' => MpTaskCenter::STATUS_PROCESSING,
  11705. 'result' => null,
  11706. 'error_message' => null,
  11707. 'prompt' => null,
  11708. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  11709. 'params_md5' => $paramsMd5,
  11710. 'created_at' => $now,
  11711. 'updated_at' => $now,
  11712. ]);
  11713. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  11714. $taskId = (int)DB::table('mp_task_center')
  11715. ->where('uid', (int)$uid)
  11716. ->where('cpid', (int)$cpid)
  11717. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11718. ->where('params_md5', $paramsMd5)
  11719. ->orderBy('id', 'desc')
  11720. ->value('id');
  11721. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  11722. 'anime_id' => $anime_id,
  11723. 'task_center_id' => $taskId,
  11724. 'params_md5' => $paramsMd5,
  11725. ]);
  11726. return $taskId;
  11727. }
  11728. /**
  11729. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  11730. *
  11731. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  11732. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  11733. * 统一汇总更新,避免在每个更新点重复处理。
  11734. *
  11735. * @param int|string $animeId
  11736. * @return int 更新的任务中心记录数
  11737. */
  11738. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  11739. $animeId = (int)$animeId;
  11740. $updated = 0;
  11741. // 该 anime 是否还有未结束的详情任务
  11742. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  11743. ->where('anime_id', $animeId)
  11744. ->whereIn('status', ['pending', 'processing'])
  11745. ->exists();
  11746. // 扫描该 anime 相关的未完成任务中心记录
  11747. $tasks = DB::table('mp_task_center')
  11748. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11749. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11750. ->orderBy('id', 'desc')
  11751. ->limit(500)
  11752. ->get();
  11753. if ($hasUnfinished && !$tasks) {
  11754. return 0;
  11755. }
  11756. foreach ($tasks as $task) {
  11757. try {
  11758. $taskParams = json_decode((string)$task->params, true);
  11759. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  11760. continue;
  11761. }
  11762. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  11763. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  11764. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  11765. continue;
  11766. }
  11767. $details = DB::table('mp_batch_episode_generation_details')
  11768. ->where('anime_id', $animeId)
  11769. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  11770. ->get();
  11771. // 该批次范围内存在缺失记录,等待下一次检查
  11772. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  11773. continue;
  11774. }
  11775. $completedEpisodes = [];
  11776. $failedEpisodes = [];
  11777. $allFinished = true;
  11778. foreach ($details as $detail) {
  11779. if ($detail->status === 'completed') {
  11780. $completedEpisodes[] = $detail->episode_number;
  11781. } elseif ($detail->status === 'failed') {
  11782. $failedEpisodes[] = [
  11783. 'episode_number' => $detail->episode_number,
  11784. 'error_message' => $detail->error_message ?? '',
  11785. ];
  11786. } else {
  11787. // pending/processing(防御处理,正常不会走到)
  11788. $allFinished = false;
  11789. break;
  11790. }
  11791. }
  11792. if (!$allFinished) {
  11793. continue;
  11794. }
  11795. $result = json_encode([
  11796. 'anime_id' => $animeId,
  11797. 'start_episode' => $startEpisode,
  11798. 'end_episode' => $endEpisode,
  11799. 'total_episodes' => count($details),
  11800. 'completed_count' => count($completedEpisodes),
  11801. 'failed_count' => count($failedEpisodes),
  11802. 'completed_episodes' => $completedEpisodes,
  11803. 'failed_episodes' => $failedEpisodes,
  11804. ], JSON_UNESCAPED_UNICODE);
  11805. DB::table('mp_task_center')
  11806. ->where('id', $task->id)
  11807. ->update([
  11808. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  11809. 'result' => $result,
  11810. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  11811. 'updated_at' => date('Y-m-d H:i:s'),
  11812. ]);
  11813. $updated++;
  11814. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  11815. 'task_center_id' => $task->id,
  11816. 'anime_id' => $animeId,
  11817. 'start_episode' => $startEpisode,
  11818. 'end_episode' => $endEpisode,
  11819. ]);
  11820. } catch (\Exception $e) {
  11821. dLog('command')->error('更新批量生成分集任务中心异常', [
  11822. 'task_center_id' => $task->id,
  11823. 'anime_id' => $animeId,
  11824. 'error' => $e->getMessage(),
  11825. ]);
  11826. }
  11827. }
  11828. return $updated;
  11829. }
  11830. /**
  11831. * 获取批量生成任务状态
  11832. *
  11833. * @param array $data 请求数据
  11834. * @return array 任务状态信息
  11835. */
  11836. public function getBatchGenerationTaskStatus($data) {
  11837. $anime_id = getProp($data, 'anime_id');
  11838. if (!$anime_id) {
  11839. Utils::throwError('20003:anime_id参数缺失');
  11840. }
  11841. // 获取该anime的所有任务
  11842. $tasks = DB::table('mp_batch_episode_generation_details')
  11843. ->where('anime_id', $anime_id)
  11844. ->orderBy('episode_number')
  11845. ->get()
  11846. ->map(function($item) {
  11847. return [
  11848. 'id' => $item->id,
  11849. 'episode_number' => $item->episode_number,
  11850. 'status' => $item->status,
  11851. 'error_message' => $item->error_message,
  11852. 'retry_count' => $item->retry_count,
  11853. 'created_at' => $item->created_at,
  11854. 'updated_at' => $item->updated_at,
  11855. 'completed_at' => $item->completed_at
  11856. ];
  11857. })
  11858. ->toArray();
  11859. if (empty($tasks)) {
  11860. Utils::throwError('20003:该剧集没有批量生成任务');
  11861. }
  11862. // 统计各状态数量
  11863. $totalCount = count($tasks);
  11864. $pendingCount = 0;
  11865. $processingCount = 0;
  11866. $completedCount = 0;
  11867. $failedCount = 0;
  11868. $failed_episodes = [];
  11869. foreach ($tasks as $task) {
  11870. switch ($task['status']) {
  11871. case 'pending':
  11872. $pendingCount++;
  11873. break;
  11874. case 'processing':
  11875. $processingCount++;
  11876. break;
  11877. case 'completed':
  11878. $completedCount++;
  11879. break;
  11880. case 'failed':
  11881. $failedCount++;
  11882. // 组装失败分集对象(新对象):分集序号、错误原因
  11883. $failed_episodes[] = [
  11884. 'episode_number' => $task['episode_number'],
  11885. 'error_message' => $task['error_message'] ?? ''
  11886. ];
  11887. break;
  11888. }
  11889. }
  11890. // 计算进度百分比
  11891. $progress = 0;
  11892. if ($totalCount > 0) {
  11893. $progress = round(($completedCount / $totalCount) * 100, 2);
  11894. }
  11895. // 判断整体状态
  11896. $overallStatus = 'processing';
  11897. if ($completedCount === $totalCount) {
  11898. $overallStatus = 'completed';
  11899. } elseif ($pendingCount === $totalCount) {
  11900. $overallStatus = 'pending';
  11901. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  11902. $overallStatus = 'failed';
  11903. }
  11904. return [
  11905. 'anime_id' => $anime_id,
  11906. 'total_episodes' => $totalCount,
  11907. 'pending_count' => $pendingCount,
  11908. 'processing_count' => $processingCount,
  11909. 'completed_count' => $completedCount,
  11910. 'failed_count' => $failedCount,
  11911. 'progress' => $progress,
  11912. 'overall_status' => $overallStatus,
  11913. 'failed_episodes' => $failed_episodes,
  11914. 'tasks' => $tasks
  11915. ];
  11916. }
  11917. /**
  11918. * 将生成内容中不在强制列表中的资源合并进强制列表
  11919. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  11920. *
  11921. * @param array $generated 生成内容中的资源列表
  11922. * @param array $forced 强制资源列表(key为资源名称)
  11923. * @param string $type 资源类型:role、scene、prop
  11924. * @return array
  11925. */
  11926. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  11927. {
  11928. foreach ($generated as $item) {
  11929. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  11930. if ($name === null || $name === '') {
  11931. continue;
  11932. }
  11933. if ($name === '旁白') {
  11934. continue;
  11935. }
  11936. if (!isset($forced[$name])) {
  11937. $forced[$name] = $item;
  11938. }
  11939. }
  11940. return $forced;
  11941. }
  11942. /**
  11943. * 智能匹配并替换主体和场景名称
  11944. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  11945. *
  11946. * @param array $episode_arr 解析后的剧集数据
  11947. * @param array $extra_roles 强制主体设定(key为主体名称)
  11948. * @param array $extra_scenes 强制场景设定(key为场景名称)
  11949. * @return array 替换后的剧集数据
  11950. */
  11951. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  11952. $replaced_count = 0;
  11953. // 1. 处理主体列表
  11954. if (!empty($episode_arr['roles'])) {
  11955. foreach ($episode_arr['roles'] as &$role) {
  11956. $generated_role_name = $role['role'] ?? '';
  11957. // 跳过旁白
  11958. if ($generated_role_name === '旁白') {
  11959. continue;
  11960. }
  11961. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  11962. if (!isset($extra_roles[$generated_role_name])) {
  11963. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  11964. if ($matched_role) {
  11965. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  11966. $role['role'] = $matched_role;
  11967. $replaced_count++;
  11968. }
  11969. }
  11970. }
  11971. }
  11972. // 2. 处理场景列表
  11973. if (!empty($episode_arr['scenes'])) {
  11974. foreach ($episode_arr['scenes'] as &$scene) {
  11975. $generated_scene_name = $scene['scene'] ?? '';
  11976. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  11977. if (!isset($extra_scenes[$generated_scene_name])) {
  11978. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  11979. if ($matched_scene) {
  11980. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  11981. $scene['scene'] = $matched_scene;
  11982. $replaced_count++;
  11983. }
  11984. }
  11985. }
  11986. }
  11987. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  11988. if (!empty($episode_arr['acts'])) {
  11989. foreach ($episode_arr['acts'] as &$act) {
  11990. if (!empty($act['segments'])) {
  11991. foreach ($act['segments'] as &$segment) {
  11992. if (!empty($segment['segment_content'])) {
  11993. $original_content = $segment['segment_content'];
  11994. $replaced_content = $original_content;
  11995. // 替换场景名 - 在文本中查找并替换
  11996. foreach (array_keys($extra_scenes) as $full_scene_name) {
  11997. // 尝试找到可能的短名称
  11998. $potential_short_names = [];
  11999. // 提取场景名的主要部分(冒号之前)
  12000. if (mb_strpos($full_scene_name, ':') !== false) {
  12001. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12002. $potential_short_names[] = $short_name;
  12003. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  12004. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12005. $potential_short_names[] = $short_name;
  12006. }
  12007. // 替换场景字段中的短名称
  12008. foreach ($potential_short_names as $short_name) {
  12009. if ($short_name !== $full_scene_name) {
  12010. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  12011. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  12012. if ($new_content !== $replaced_content) {
  12013. $replaced_content = $new_content;
  12014. $replaced_count++;
  12015. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  12016. }
  12017. }
  12018. }
  12019. }
  12020. // 替换配音角色名(跳过旁白)
  12021. foreach (array_keys($extra_roles) as $full_role_name) {
  12022. if ($full_role_name === '旁白') {
  12023. continue;
  12024. }
  12025. // 尝试找到可能的短名称
  12026. $potential_short_names = [];
  12027. // 提取角色名的主要部分(短横线之前)
  12028. if (mb_strpos($full_role_name, '-') !== false) {
  12029. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  12030. $potential_short_names[] = $short_name;
  12031. }
  12032. // 替换配音台词中的短名称
  12033. foreach ($potential_short_names as $short_name) {
  12034. if ($short_name !== $full_role_name) {
  12035. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  12036. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  12037. if ($new_content !== $replaced_content) {
  12038. $replaced_content = $new_content;
  12039. $replaced_count++;
  12040. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  12041. }
  12042. }
  12043. }
  12044. }
  12045. // 如果有替换,更新segment_content
  12046. if ($replaced_content !== $original_content) {
  12047. $segment['segment_content'] = $replaced_content;
  12048. }
  12049. }
  12050. }
  12051. }
  12052. }
  12053. }
  12054. if ($replaced_count > 0) {
  12055. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  12056. 'replaced_count' => $replaced_count
  12057. ]);
  12058. }
  12059. return $episode_arr;
  12060. }
  12061. /**
  12062. * 查找匹配的名称
  12063. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  12064. *
  12065. * @param string $generated_name 生成的名称
  12066. * @param array $expected_names 预期的名称列表
  12067. * @return string|null 匹配到的名称,如果没有匹配则返回null
  12068. */
  12069. private function findMatchingName($generated_name, $expected_names) {
  12070. if (empty($generated_name)) {
  12071. return null;
  12072. }
  12073. // 尝试精确匹配
  12074. if (in_array($generated_name, $expected_names)) {
  12075. return $generated_name;
  12076. }
  12077. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  12078. foreach ($expected_names as $expected_name) {
  12079. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  12080. if (mb_strpos($expected_name, $generated_name) === 0) {
  12081. return $expected_name;
  12082. }
  12083. }
  12084. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  12085. // 这样可以处理一些变体,但优先级较低
  12086. foreach ($expected_names as $expected_name) {
  12087. if (mb_strpos($expected_name, $generated_name) !== false) {
  12088. return $expected_name;
  12089. }
  12090. }
  12091. return null;
  12092. }
  12093. /**
  12094. * 重新生成分段剧本
  12095. * @param array $data 包含以下字段:
  12096. * - prompt: string|null 用户修改要求(可选)
  12097. * - template_id: int|null 提示词模板ID(可选)
  12098. * - act_id: int|null 单个片段ID(与episode_id二选一)
  12099. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  12100. * @return array 返回生成结果
  12101. */
  12102. public function regenerateSegmentScript($data) {
  12103. $uid = Site::getUid();
  12104. $prompt = trim((string)getProp($data, 'prompt', ''));
  12105. $template_id = getProp($data, 'template_id', 0);
  12106. $act_id = getProp($data, 'act_id', 0);
  12107. $episode_id = getProp($data, 'episode_id', 0);
  12108. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  12109. // 单片段模式:act_id 可以是数据库真实ID(数字)或预览生成的虚拟ID(字符串),非空即单片段模式
  12110. $isActIdMode = !empty($act_id);
  12111. // 验证:prompt和template_id至少提供一个
  12112. if (empty($prompt) && empty($template_id)) {
  12113. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  12114. }
  12115. // 验证:act_id和episode_id二选一
  12116. if (empty($act_id) && empty($episode_id)) {
  12117. Utils::throwError('20003:请提供片段ID或剧集ID');
  12118. }
  12119. if (!empty($act_id) && !empty($episode_id)) {
  12120. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  12121. }
  12122. // 积分余额预检:act_id 单片段模式按 normal 档,episode_id 剧集模式按 special 档
  12123. $chargeType = $isActIdMode ? 'normal' : 'special';
  12124. if ($isActIdMode) {
  12125. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12126. } else {
  12127. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  12128. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  12129. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12130. }
  12131. // 如果提供了template_id,获取模板提示词
  12132. $template_prompt = '';
  12133. if ($template_id > 0) {
  12134. $template = DB::table('mp_prompt_templates')
  12135. ->where('id', $template_id)
  12136. ->where('is_deleted', 0)
  12137. ->first();
  12138. if (!$template) {
  12139. Utils::throwError('20003:提示词模板不存在或已删除');
  12140. }
  12141. $template_prompt = $template->template_prompt ?? '';
  12142. }
  12143. // 合并用户提示词和模板提示词(模板提示词与用户输入基本一致时只保留一个,避免重复提示词)
  12144. $final_prompt = '';
  12145. if (!empty($template_prompt)) {
  12146. $trimmedPrompt = trim((string)$prompt);
  12147. if ($trimmedPrompt !== '' && mb_strtolower($trimmedPrompt) === mb_strtolower(trim($template_prompt))) {
  12148. $final_prompt = $template_prompt;
  12149. } elseif (!empty($prompt)) {
  12150. $final_prompt = $template_prompt . "\n\n补充要求:" . $prompt;
  12151. } else {
  12152. $final_prompt = $template_prompt;
  12153. }
  12154. } else {
  12155. $final_prompt = $prompt;
  12156. }
  12157. // 获取需要重新生成的内容参考
  12158. $reference_content = '';
  12159. $target_episode_id = 0;
  12160. $target_anime_id = 0;
  12161. $target_episode_number = 0;
  12162. if ($isActIdMode) {
  12163. // 单个片段模式:获取该片段的内容
  12164. $segment = DB::table('mp_episode_segments')
  12165. ->where('id', $act_id)
  12166. ->first();
  12167. // 数据库不存在时,尝试从预览虚拟 act_id 保存的 redis 数据中恢复
  12168. if (!$segment) {
  12169. $previewData = Redis::get($this->buildActPreviewKey($act_id));
  12170. if ($previewData) {
  12171. $previewData = json_decode($previewData, true);
  12172. $segment = (object)[
  12173. 'anime_id' => getProp($previewData, 'anime_id'),
  12174. 'episode_id' => getProp($previewData, 'episode_id'),
  12175. 'episode_number' => getProp($previewData, 'episode_number'),
  12176. 'act_number' => getProp($previewData, 'act_number'),
  12177. 'act_duration' => getProp($previewData, 'act_duration'),
  12178. 'act_content' => getProp($previewData, 'act_content'),
  12179. ];
  12180. }
  12181. }
  12182. if (!$segment) {
  12183. Utils::throwError('20003:片段不存在');
  12184. }
  12185. $target_episode_id = $segment->episode_id;
  12186. $target_anime_id = $segment->anime_id;
  12187. $target_episode_number = $segment->episode_number;
  12188. $reference_content = $segment->act_content ?? '';
  12189. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12190. } else {
  12191. // 整个剧集模式:获取所有片段的内容
  12192. $segments = DB::table('mp_episode_segments')
  12193. ->where('episode_id', $episode_id)
  12194. ->orderBy('act_number')
  12195. ->get();
  12196. if ($segments->isEmpty()) {
  12197. Utils::throwError('20003:该剧集没有片段数据');
  12198. }
  12199. $target_episode_id = $episode_id;
  12200. $target_anime_id = $segments[0]->anime_id;
  12201. $target_episode_number = $segments[0]->episode_number;
  12202. // 拼接所有片段内容,保留格式用于AI理解
  12203. $act_contents = [];
  12204. foreach ($segments as $seg) {
  12205. $act_number = $seg->act_number;
  12206. $act_content = $seg->act_content ?? '';
  12207. if (!empty($act_content)) {
  12208. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  12209. }
  12210. }
  12211. $reference_content = implode("\n\n", $act_contents);
  12212. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  12213. if ($episode_content) {
  12214. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【原分段剧本内容】\n{$reference_content}";
  12215. //$reference_content = "\n\n【本集原始内容】\n{$episode_content}";
  12216. }else {
  12217. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12218. }
  12219. }
  12220. if (empty($reference_content)) {
  12221. Utils::throwError('20003:没有可参考的片段内容');
  12222. }
  12223. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  12224. $episode = DB::table('mp_anime_episodes')
  12225. ->where('id', $target_episode_id)
  12226. ->first();
  12227. if (!$episode) {
  12228. Utils::throwError('20003:剧集不存在');
  12229. }
  12230. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  12231. $anime_script_id = getProp($anime, 'script_id');
  12232. $intro = $episode->intro ?? '';
  12233. $art_style = $episode->art_style ?? '';
  12234. $roles = json_decode($episode->roles ?? '[]', true);
  12235. $scenes = json_decode($episode->scenes ?? '[]', true);
  12236. $props = json_decode($episode->props ?? '[]', true);
  12237. // 构建提示词中的主体列表和场景列表参考
  12238. $roles_ref = '';
  12239. if (!empty($roles) && is_array($roles)) {
  12240. $roles_list = [];
  12241. foreach ($roles as $role) {
  12242. $role_name = getProp($role, 'role', '');
  12243. $role_desc = getProp($role, 'description', '');
  12244. $pic_prompt = getProp($role, 'pic_prompt', '');
  12245. $voice_prompt = getProp($role, 'voice_prompt', '');
  12246. if (!empty($role_name)) {
  12247. $role_line = $role_name;
  12248. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  12249. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  12250. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  12251. $roles_list[] = $role_line;
  12252. }
  12253. }
  12254. if (!empty($roles_list)) {
  12255. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  12256. }
  12257. }
  12258. $scenes_ref = '';
  12259. if (!empty($scenes) && is_array($scenes)) {
  12260. $scenes_list = [];
  12261. foreach ($scenes as $scene) {
  12262. $scene_name = getProp($scene, 'scene', '');
  12263. $scene_desc = getProp($scene, 'description', '');
  12264. $pic_prompt = getProp($scene, 'pic_prompt', '');
  12265. if (!empty($scene_name)) {
  12266. $scene_line = $scene_name;
  12267. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  12268. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  12269. $scenes_list[] = $scene_line;
  12270. }
  12271. }
  12272. if (!empty($scenes_list)) {
  12273. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  12274. }
  12275. }
  12276. $props_ref = '';
  12277. if (!empty($props) && is_array($props)) {
  12278. $props_list = [];
  12279. foreach ($props as $prop) {
  12280. $prop_name = getProp($prop, 'prop', '');
  12281. $prop_desc = getProp($prop, 'description', '');
  12282. $pic_prompt = getProp($prop, 'pic_prompt', '');
  12283. if (!empty($prop_name)) {
  12284. $prop_line = $prop_name;
  12285. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  12286. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  12287. $props_list[] = $prop_line;
  12288. }
  12289. }
  12290. if (!empty($props_list)) {
  12291. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  12292. }
  12293. }
  12294. // 构建美术风格参考
  12295. $art_style_ref = '';
  12296. if (!empty($art_style)) {
  12297. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  12298. }
  12299. // 构建内容简介参考
  12300. $intro_ref = '';
  12301. if (!empty($intro)) {
  12302. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  12303. }
  12304. // 构建完整的AI提示词
  12305. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  12306. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  12307. $user_prompt .= $intro_ref;
  12308. $user_prompt .= $art_style_ref;
  12309. $user_prompt .= $reference_content;
  12310. $user_prompt .= "\n\n【生成要求】\n- 请以【原分段剧本内容】为蓝本,保留剧情脉络、角色、场景与分段结构,但必须围绕【用户要求】对相关片段进行实质性修改;若【用户要求】未指定具体修改点,也需对画面、运镜、台词等描述进行改写,禁止整段原样复制。\n";
  12311. // $user_prompt .= $roles_ref;
  12312. // $user_prompt .= $scenes_ref;
  12313. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  12314. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  12315. if ($isActIdMode) {
  12316. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12317. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12318. } else {
  12319. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12320. }
  12321. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  12322. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  12323. // 整集模式:强制生成与原来一致的片段数量
  12324. if ($episode_id > 0 && isset($segments)) {
  12325. $originSegmentCount = count($segments);
  12326. $user_prompt .= "- 本集原有{$originSegmentCount}个片段,必须严格生成{$originSegmentCount}个片段(##片段1 到 ##片段{$originSegmentCount}),不得多不得少。\n";
  12327. }
  12328. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  12329. if ($isActIdMode) {
  12330. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  12331. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12332. } else {
  12333. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  12334. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  12335. }
  12336. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  12337. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  12338. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  12339. $system_prompt .= "【强制要求】\n";
  12340. // $system_prompt .= "- 请严格参考【本集原始内容】或【原分段剧本内容】进行本次生成,注意新生成的分段剧本内容一定不要跟【原分段剧本内容】一致,要进行一定程度调整\n";
  12341. $system_prompt .= "- 【重要】必须参考【本集原始内容】与【原分段剧本内容】中的剧情脉络、角色、场景、道具和分段结构,但严禁原样复制或几乎照抄原文;必须围绕【用户要求】对相关内容进行实质性修改,若生成结果与【原分段剧本内容】完全一致或未体现用户要求,视为生成失败\n";
  12342. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:\n";
  12343. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)\n";
  12344. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  12345. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  12346. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  12347. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  12348. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  12349. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  12350. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  12351. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  12352. $segmentHeader = '';
  12353. if ($episode_id > 0) {
  12354. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  12355. }
  12356. $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背景音效:";
  12357. // 获取模型配置
  12358. $model = getProp($data, 'model');
  12359. if (!$model) {
  12360. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  12361. }
  12362. // 验证模型是否在可用模型表中
  12363. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12364. $model = 'deepseek-v4-pro';
  12365. }
  12366. // 模型兼容性处理
  12367. $thinkingMode = 'disabled';
  12368. $reasoningEffort = 'high';
  12369. if ($model === 'deepseek-chat') {
  12370. $model = 'deepseek-v4-flash';
  12371. $thinkingMode = 'disabled';
  12372. } elseif ($model === 'deepseek-reasoner') {
  12373. $model = 'deepseek-v4-flash';
  12374. $thinkingMode = 'enabled';
  12375. }
  12376. // 构建消息
  12377. $messages = [
  12378. [
  12379. 'role' => 'system',
  12380. 'content' => $system_prompt
  12381. ],
  12382. [
  12383. 'role' => 'user',
  12384. 'content' => $user_prompt
  12385. ]
  12386. ];
  12387. // dd($messages);
  12388. // 构建请求参数
  12389. $post_data = [
  12390. 'model' => $model,
  12391. 'messages' => $messages,
  12392. 'temperature' => 1.35,
  12393. 'frequency_penalty' => 0.3,
  12394. 'presence_penalty' => 0,
  12395. 'response_format' => ['type' => 'text'],
  12396. 'thinking' => ['type' => $thinkingMode],
  12397. 'stream' => false // 非流式输出
  12398. ];
  12399. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12400. // 调用AI生成新的分段剧本
  12401. try {
  12402. $fullContent = '';
  12403. $usage = [];
  12404. // 根据模型类型选择调用方法
  12405. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  12406. if (is_array($chatResult)) {
  12407. $fullContent = $chatResult['fullContent'] ?? '';
  12408. $usage = $chatResult['usage'] ?? [];
  12409. }
  12410. $generated_content = $fullContent;
  12411. // 归一化"场景:"标签换行格式:场景:\n场景名\n => 场景:场景名\n,保证场景字段为一行
  12412. $generated_content = preg_replace('/场景[::]\s*\n\s*([^\n]+)/u', '场景:$1', $generated_content);
  12413. if (empty($generated_content)) {
  12414. Utils::throwError('20003:AI生成内容为空,请重试');
  12415. }
  12416. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  12417. 'act_id' => $act_id,
  12418. 'episode_id' => $episode_id,
  12419. 'content_length' => mb_strlen($generated_content),
  12420. 'content_head' => mb_substr($generated_content, 0, 500),
  12421. 'content_tail' => mb_substr($generated_content, -200),
  12422. ]);
  12423. // 解析生成的内容 - 按片段分割
  12424. $parsed_segments = [];
  12425. // 先在开头添加换行符,确保第1片段也能被正确分割
  12426. $normalizedText = "\n" . $generated_content;
  12427. $parts = preg_split('/\n\s*##/', $normalizedText);
  12428. foreach ($parts as $part) {
  12429. $part = trim($part);
  12430. if (empty($part)) continue;
  12431. // 匹配"片段X"格式
  12432. if (!preg_match('/^片段\d+/', $part)) {
  12433. continue;
  12434. }
  12435. // 分离标题和内容
  12436. $lines = explode("\n", $part, 2);
  12437. $actTitle = trim($lines[0]);
  12438. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  12439. // 解析标题,提取序号
  12440. $actNumber = 0;
  12441. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  12442. $actNumber = intval($segmentTitleMatch[1]);
  12443. } else {
  12444. $actNumber = count($parsed_segments) + 1;
  12445. }
  12446. // 提取时长(仅保留数字)
  12447. $actDuration = 0;
  12448. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  12449. $actDurationStr = trim($actDurationMatch[1]);
  12450. // 提取数字部分(支持整数和小数)
  12451. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  12452. $actDuration = (float)$numMatch[1];
  12453. }
  12454. }
  12455. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12456. if ($actDuration > 15) {
  12457. $actDuration = 15;
  12458. }
  12459. if ($actDuration < 4) {
  12460. $actDuration = 4;
  12461. }
  12462. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  12463. $cleaned_content = $this->cleanSegmentContent($actContent);
  12464. $parsed_segments[] = [
  12465. 'act_number' => $actNumber,
  12466. 'act_title' => $actTitle,
  12467. 'act_duration' => $actDuration,
  12468. 'act_content' => $cleaned_content,
  12469. ];
  12470. }
  12471. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  12472. if (empty($parsed_segments)) {
  12473. $fallbackContent = $this->cleanSegmentContent($generated_content);
  12474. if ($fallbackContent !== '') {
  12475. $fallbackDuration = 0;
  12476. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  12477. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  12478. $fallbackDuration = (float)$numMatch[1];
  12479. }
  12480. }
  12481. // 内容未带时长时,单片段模式沿用原片段的时长
  12482. if ($fallbackDuration <= 0 && $isActIdMode && !empty($segment->act_duration)) {
  12483. $fallbackDuration = (float)$segment->act_duration;
  12484. }
  12485. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12486. if ($fallbackDuration > 15) {
  12487. $fallbackDuration = 15;
  12488. }
  12489. if ($fallbackDuration < 4) {
  12490. $fallbackDuration = 4;
  12491. }
  12492. $parsed_segments[] = [
  12493. 'act_number' => 1,
  12494. 'act_title' => '片段1',
  12495. 'act_duration' => $fallbackDuration,
  12496. 'act_content' => $fallbackContent,
  12497. ];
  12498. }
  12499. }
  12500. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  12501. if ($isActIdMode && count($parsed_segments) > 1) {
  12502. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  12503. 'act_id' => $act_id,
  12504. 'original_count' => count($parsed_segments),
  12505. ]);
  12506. $parsed_segments = array_slice($parsed_segments, 0, 1);
  12507. }
  12508. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  12509. 'act_id' => $act_id,
  12510. 'episode_id' => $episode_id,
  12511. 'segment_count' => count($parsed_segments),
  12512. 'segments' => array_map(function ($seg) {
  12513. return [
  12514. 'act_number' => $seg['act_number'],
  12515. 'act_duration' => $seg['act_duration'],
  12516. 'content_length' => mb_strlen($seg['act_content']),
  12517. ];
  12518. }, $parsed_segments),
  12519. ]);
  12520. if (empty($parsed_segments)) {
  12521. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  12522. 'act_id' => $act_id,
  12523. 'episode_id' => $episode_id,
  12524. 'content_length' => mb_strlen($generated_content),
  12525. 'content_head' => mb_substr($generated_content, 0, 1000),
  12526. 'content_tail' => mb_substr($generated_content, -300),
  12527. ]);
  12528. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  12529. }
  12530. // 收集所有资产名称(角色、场景、道具)
  12531. $product_names = [];
  12532. // 收集角色名称
  12533. if (!empty($roles) && is_array($roles)) {
  12534. foreach ($roles as $role) {
  12535. $role_name = getProp($role, 'role', '');
  12536. if (!empty($role_name)) {
  12537. $product_names[] = $role_name;
  12538. }
  12539. }
  12540. }
  12541. // 收集场景名称
  12542. if (!empty($scenes) && is_array($scenes)) {
  12543. foreach ($scenes as $scene) {
  12544. $scene_name = getProp($scene, 'scene', '');
  12545. if (!empty($scene_name)) {
  12546. $product_names[] = $scene_name;
  12547. }
  12548. }
  12549. }
  12550. // 收集道具名称
  12551. if (!empty($props) && is_array($props)) {
  12552. foreach ($props as $prop) {
  12553. $prop_name = getProp($prop, 'prop', '');
  12554. if (!empty($prop_name)) {
  12555. $product_names[] = $prop_name;
  12556. }
  12557. }
  12558. }
  12559. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  12560. $product_names = array_unique($product_names);
  12561. usort($product_names, function($a, $b) {
  12562. return mb_strlen($b) - mb_strlen($a);
  12563. });
  12564. // 处理每个片段的 act_show_content
  12565. foreach ($parsed_segments as &$segment) {
  12566. $act_content = getProp($segment, 'act_content', '');
  12567. if (empty($act_content)) {
  12568. $segment['act_show_content'] = '';
  12569. continue;
  12570. }
  12571. $processed_content = $act_content;
  12572. // 统一替换所有资产名称为 {资产名} 格式
  12573. // 使用占位符避免嵌套替换问题
  12574. $placeholder_map = [];
  12575. $placeholder_index = 0;
  12576. foreach ($product_names as $product_name) {
  12577. // 转义特殊字符
  12578. $escaped_product = preg_quote($product_name, '/');
  12579. // 检查是否匹配且未被 {} 包裹
  12580. $processed_content = preg_replace_callback(
  12581. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  12582. function($matches) use (&$placeholder_map, &$placeholder_index) {
  12583. // 使用唯一占位符
  12584. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  12585. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  12586. $placeholder_index++;
  12587. return $placeholder;
  12588. },
  12589. $processed_content
  12590. );
  12591. }
  12592. // 将所有占位符替换回实际内容
  12593. foreach ($placeholder_map as $placeholder => $replacement) {
  12594. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  12595. }
  12596. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  12597. $shot_counter = 0;
  12598. $processed_content = preg_replace_callback(
  12599. // 兼容“【镜头 1】”“【分镜 1】”等分镜/镜头与数字间带空格的情况
  12600. '/【(?:镜头|分镜)\s*(\d+)】/u',
  12601. function($matches) use (&$shot_counter) {
  12602. $shot_counter++;
  12603. return '【镜头' . $shot_counter . '】';
  12604. },
  12605. $processed_content
  12606. );
  12607. $segment['act_show_content'] = $processed_content;
  12608. }
  12609. unset($segment); // 解除引用
  12610. // 保存到数据库
  12611. $now = date('Y-m-d H:i:s');
  12612. $saved_acts = []; // 用于记录保存后的片段信息
  12613. if ($isActIdMode) {
  12614. // 单个片段模式:更新单条记录
  12615. if (count($parsed_segments) > 0) {
  12616. $new_segment = $parsed_segments[0];
  12617. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  12618. if ($check_mode === 1) {
  12619. // 单片段预览生成即按 normal 档扣费
  12620. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12621. 'anime_id' => $target_anime_id,
  12622. 'episode_id' => $target_episode_id,
  12623. 'model' => $model,
  12624. 'source' => 'regenerateSegmentScript',
  12625. ], 'normal');
  12626. return [
  12627. 'check_mode' => 1,
  12628. 'act_id' => $act_id,
  12629. 'act_title' => getProp($new_segment, 'act_title', ''),
  12630. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12631. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  12632. ];
  12633. }
  12634. // 虚拟 act_id 仅用于预览/参考,不允许直接保存到数据库
  12635. if (!is_numeric($act_id)) {
  12636. Utils::throwError('20003:该片段不可直接保存');
  12637. }
  12638. $update_data = [
  12639. 'act_content' => getProp($new_segment, 'act_content', ''),
  12640. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  12641. 'act_title' => getProp($new_segment, 'act_title', ''),
  12642. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12643. 'updated_at' => $now,
  12644. ];
  12645. DB::table('mp_episode_segments')
  12646. ->where('id', $act_id)
  12647. ->update($update_data);
  12648. // 获取更新后的记录
  12649. $updated_act = DB::table('mp_episode_segments')
  12650. ->where('id', $act_id)
  12651. ->first();
  12652. if ($updated_act) {
  12653. $saved_acts[] = [
  12654. 'act_id' => $updated_act->id,
  12655. 'act_number' => $updated_act->act_number,
  12656. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  12657. 'act_content' => $updated_act->act_content,
  12658. 'act_show_content' => $updated_act->act_show_content,
  12659. 'video_url' => $updated_act->video_url ?? '',
  12660. 'video_duration' => $updated_act->video_duration ?? 0,
  12661. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  12662. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  12663. ];
  12664. }
  12665. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  12666. // 单片段模式成功扣费(normal 档)
  12667. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12668. 'anime_id' => $target_anime_id,
  12669. 'episode_id' => $target_episode_id,
  12670. 'model' => $model,
  12671. 'source' => 'regenerateSegmentScript',
  12672. ], 'normal');
  12673. }
  12674. } else {
  12675. // 预览确认模式(check_mode=1):不落库,返回展示参数供前端确认后调用 saveEpisodeActs 保存
  12676. if ($check_mode === 1) {
  12677. // 剧集模式预览生成即扣除积分并记录 token 明细(special 档)
  12678. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12679. 'anime_id' => $target_anime_id,
  12680. 'episode_id' => $target_episode_id,
  12681. 'model' => $model,
  12682. 'source' => 'regenerateSegmentScript',
  12683. ], 'special');
  12684. // 为每个片段生成虚拟 act_id 并写入 redis(1天有效),供后续按虚拟 act_id 恢复片段数据
  12685. $previewActs = [];
  12686. foreach ($parsed_segments as $seg) {
  12687. $virtualActId = 'preview_' . time() . '_' . uniqid();
  12688. Redis::setex($this->buildActPreviewKey($virtualActId), 86400, json_encode([
  12689. 'anime_id' => $target_anime_id,
  12690. 'episode_id' => $target_episode_id,
  12691. 'episode_number' => $target_episode_number,
  12692. 'act_number' => $seg['act_number'],
  12693. 'act_title' => $seg['act_title'],
  12694. 'act_duration' => $seg['act_duration'],
  12695. 'act_content' => $seg['act_content'],
  12696. 'act_show_content'=> $seg['act_show_content'],
  12697. ], JSON_UNESCAPED_UNICODE));
  12698. $previewActs[] = [
  12699. 'act_id' => $virtualActId,
  12700. 'act_number' => $seg['act_number'],
  12701. 'act_title' => $seg['act_title'],
  12702. 'act_duration' => $seg['act_duration'],
  12703. 'act_content' => $seg['act_content'],
  12704. 'act_show_content' => $seg['act_show_content'],
  12705. 'video_url' => '',
  12706. 'video_duration' => 0,
  12707. 'video_time_point_start' => 0,
  12708. 'video_time_point_end' => 0,
  12709. 'last_frame_url' => '',
  12710. 'current_type' => 0,
  12711. ];
  12712. }
  12713. return [
  12714. 'check_mode' => 1,
  12715. 'anime_id' => $target_anime_id,
  12716. 'episode_id' => $target_episode_id,
  12717. 'title' => getProp($episode, 'title', ''),
  12718. 'episode_number' => $target_episode_number,
  12719. 'is_generated' => getProp($episode, 'is_generated', 0),
  12720. 'acts' => $previewActs,
  12721. ];
  12722. }
  12723. // 整个剧集模式:删除原有记录并批量保存新记录
  12724. DB::beginTransaction();
  12725. try {
  12726. // 删除原有的所有片段记录
  12727. DB::table('mp_episode_segments')
  12728. ->where('episode_id', $target_episode_id)
  12729. ->delete();
  12730. // 批量插入新的片段记录
  12731. $segments_to_insert = [];
  12732. foreach ($parsed_segments as $index => $segment) {
  12733. $act_number = $index + 1;
  12734. $segments_to_insert[] = [
  12735. 'anime_id' => $target_anime_id,
  12736. 'episode_id' => $target_episode_id,
  12737. 'episode_number' => $target_episode_number,
  12738. 'act_number' => $act_number,
  12739. 'act_title' => getProp($segment, 'act_title', ''),
  12740. 'act_duration' => getProp($segment, 'act_duration', 0),
  12741. 'act_content' => getProp($segment, 'act_content', ''),
  12742. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  12743. 'created_at' => $now,
  12744. 'updated_at' => $now,
  12745. ];
  12746. }
  12747. if (!empty($segments_to_insert)) {
  12748. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12749. }
  12750. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(special 档,与保存同事务)
  12751. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12752. 'anime_id' => $target_anime_id,
  12753. 'episode_id' => $target_episode_id,
  12754. 'model' => $model,
  12755. 'source' => 'regenerateSegmentScript',
  12756. ], 'special');
  12757. DB::commit();
  12758. // 查询保存后的所有片段记录
  12759. $saved_segments = DB::table('mp_episode_segments')
  12760. ->where('episode_id', $target_episode_id)
  12761. ->orderBy('act_number')
  12762. ->get();
  12763. foreach ($saved_segments as $saved_segment) {
  12764. $saved_acts[] = [
  12765. 'act_id' => $saved_segment->id,
  12766. 'act_number' => $saved_segment->act_number,
  12767. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  12768. 'act_content' => $saved_segment->act_content,
  12769. 'act_show_content' => $saved_segment->act_show_content,
  12770. 'video_url' => $saved_segment->video_url ?? '',
  12771. 'video_duration' => $saved_segment->video_duration ?? 0,
  12772. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  12773. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  12774. ];
  12775. }
  12776. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  12777. 'episode_id' => $target_episode_id,
  12778. 'segments_count' => count($segments_to_insert)
  12779. ]);
  12780. } catch (\Exception $e) {
  12781. DB::rollBack();
  12782. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  12783. Utils::throwError('20003:保存失败,请重试');
  12784. }
  12785. }
  12786. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  12787. return [
  12788. 'anime_id' => $target_anime_id,
  12789. 'episode_id' => $target_episode_id,
  12790. 'title' => getProp($episode, 'title', ''),
  12791. 'episode_number' => $target_episode_number,
  12792. 'is_generated' => getProp($episode, 'is_generated', 0),
  12793. 'acts' => $saved_acts,
  12794. ];
  12795. } catch (\Exception $e) {
  12796. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  12797. throw $e;
  12798. }
  12799. }
  12800. /**
  12801. * 保存剧集片段(预览确认模式使用):删除旧数据并批量保存新数据到 mp_episode_segments
  12802. *
  12803. * 逻辑与 regenerateSegmentScript 的 episode_id + check_mode=0 保存保持一致。
  12804. *
  12805. * @param array $data 请求参数:episode_id 必填,acts 必填(预览返回的片段数组)
  12806. * @return array
  12807. */
  12808. public function saveEpisodeActs($data) {
  12809. $uid = Site::getUid();
  12810. $episode_id = (int)getProp($data, 'episode_id', 0);
  12811. $acts = getProp($data, 'acts', []);
  12812. if (!$episode_id) {
  12813. Utils::throwError('20003:请提供剧集ID');
  12814. }
  12815. if (!is_array($acts) || empty($acts)) {
  12816. Utils::throwError('20003:请提供片段数据');
  12817. }
  12818. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  12819. if (!$episode) {
  12820. Utils::throwError('20003:剧集不存在');
  12821. }
  12822. // 用户校验:只能调整自己的剧集
  12823. $anime = DB::table('mp_animes')->where('id', $episode->anime_id)->first();
  12824. if (!$anime || (int)$anime->user_id !== (int)$uid) {
  12825. Utils::throwError('20003:没有权限操作该剧集');
  12826. }
  12827. $anime_id = (int)$episode->anime_id;
  12828. $episode_number = (int)$episode->episode_number;
  12829. $now = date('Y-m-d H:i:s');
  12830. try {
  12831. DB::beginTransaction();
  12832. // 删除原有的所有片段记录
  12833. DB::table('mp_episode_segments')
  12834. ->where('episode_id', $episode_id)
  12835. ->delete();
  12836. // 批量插入新的片段记录
  12837. $segments_to_insert = [];
  12838. $index = 0;
  12839. foreach ($acts as $act) {
  12840. if (!is_array($act)) {
  12841. continue;
  12842. }
  12843. $index++;
  12844. $segments_to_insert[] = [
  12845. 'anime_id' => $anime_id,
  12846. 'episode_id' => $episode_id,
  12847. 'episode_number' => $episode_number,
  12848. 'act_number' => (int)getProp($act, 'act_number', $index),
  12849. 'act_title' => (string)getProp($act, 'act_title', ''),
  12850. 'act_duration' => (float)getProp($act, 'act_duration', 0),
  12851. 'act_content' => (string)getProp($act, 'act_content', ''),
  12852. // 'act_show_content' => (string)getProp($act, 'act_show_content', ''),
  12853. 'created_at' => $now,
  12854. 'updated_at' => $now,
  12855. ];
  12856. }
  12857. if (empty($segments_to_insert)) {
  12858. DB::rollBack();
  12859. Utils::throwError('20003:没有有效的片段数据');
  12860. }
  12861. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12862. DB::commit();
  12863. } catch (\Exception $e) {
  12864. DB::rollBack();
  12865. dLog('deepseek')->error('保存剧集片段失败: ' . $e->getMessage(), [
  12866. 'episode_id' => $episode_id,
  12867. ]);
  12868. Utils::throwError('20003:保存失败,请重试');
  12869. }
  12870. // 查询保存后的所有片段记录(数组化,与 episodeInfoForAce 处理一致)
  12871. $saved_segments = DB::table('mp_episode_segments')
  12872. ->where('episode_id', $episode_id)
  12873. ->orderBy('act_number')
  12874. ->get()
  12875. ->map(function ($value) {
  12876. return (array)$value;
  12877. })
  12878. ->toArray();
  12879. // 构造与 episodeInfoForAce 一致的 acts 与 total_duration
  12880. $acts = [];
  12881. $totalDuration = 0;
  12882. foreach ($saved_segments as $segment) {
  12883. $videoDuration = getProp($segment, 'video_duration');
  12884. $actDuration = getProp($segment, 'act_duration');
  12885. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  12886. $totalDuration += floatval($videoDuration);
  12887. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  12888. $totalDuration += floatval($actDuration);
  12889. } else {
  12890. $totalDuration += 5;
  12891. }
  12892. $acts[] = [
  12893. 'act_id' => getProp($segment, 'id'),
  12894. 'act_number' => getProp($segment, 'act_number'),
  12895. 'act_title' => getProp($segment, 'act_title'),
  12896. 'act_duration' => getProp($segment, 'act_duration'),
  12897. 'act_content' => getProp($segment, 'act_content'),
  12898. 'video_url' => getProp($segment, 'video_url'),
  12899. 'video_duration' => getProp($segment, 'video_duration', 0),
  12900. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  12901. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  12902. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  12903. 'current_type' => getProp($segment, 'current_type'),
  12904. ];
  12905. }
  12906. // 顶层与 episodeInfoForAce 一致
  12907. $result = [
  12908. 'episode_id' => $episode_id,
  12909. 'anime_id' => $anime_id,
  12910. 'episode_number' => $episode_number,
  12911. 'title' => getProp($episode, 'title'),
  12912. 'intro' => getProp($episode, 'intro'),
  12913. 'art_style' => getProp($episode, 'art_style'),
  12914. 'roles' => json_decode(getProp($episode, 'roles', '[]'), true),
  12915. 'scenes' => json_decode(getProp($episode, 'scenes', '[]'), true),
  12916. 'props' => getProp($episode, 'props') ? json_decode(getProp($episode, 'props'), true) : [],
  12917. 'is_generated' => getProp($episode, 'is_generated'),
  12918. 'acts' => array_values($acts),
  12919. 'total_duration' => intval(round($totalDuration)),
  12920. ];
  12921. // video_params(从 mp_animes 取,与 episodeInfoForAce 一致)
  12922. $animeRow = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  12923. $result['video_params'] = [
  12924. 'video_model' => getProp($animeRow, 'video_model'),
  12925. 'video_resolution' => getProp($animeRow, 'video_resolution'),
  12926. 'ratio' => getProp($animeRow, 'video_ratio'),
  12927. ];
  12928. return $result;
  12929. }
  12930. /**
  12931. * 预览虚拟 act_id 在 redis 中的键
  12932. *
  12933. * @param mixed $actId
  12934. * @return string
  12935. */
  12936. private function buildActPreviewKey($actId): string
  12937. {
  12938. return 'anime_act_preview:' . $actId;
  12939. }
  12940. /**
  12941. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  12942. *
  12943. * @param string $actContent
  12944. * @return string
  12945. */
  12946. private function cleanSegmentContent(string $actContent): string
  12947. {
  12948. $cleaned_content = '';
  12949. $content_lines = explode("\n", $actContent);
  12950. $is_capturing = false; // 标记是否开始捕获分镜内容
  12951. $count = 0;
  12952. foreach ($content_lines as $line) {
  12953. $trimmed_line = trim($line);
  12954. // 跳过时长、旁白音色等非分镜行
  12955. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  12956. continue;
  12957. }
  12958. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X,以及分镜/镜头与数字间带空格的情况)
  12959. if (preg_match('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  12960. $count++;
  12961. $is_capturing = true;
  12962. // 统一归一化为【分镜N】/【镜头N】(兼容“镜头 1”“【镜头 1】”等写法)
  12963. $trimmed_line = preg_replace('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', '【$1$2】', $trimmed_line);
  12964. if ($count > 1) {
  12965. $trimmed_line = "\n" . $trimmed_line;
  12966. }
  12967. }
  12968. if ($is_capturing && !empty($trimmed_line)) {
  12969. $cleaned_content .= $trimmed_line . "\n";
  12970. }
  12971. }
  12972. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  12973. return $cleaned_content;
  12974. }
  12975. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  12976. {
  12977. $episode_arr = [
  12978. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  12979. 'intro' => getProp($script_arr, 'intro'),
  12980. 'art_style' => getProp($script_arr, 'art_style'),
  12981. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  12982. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  12983. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  12984. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  12985. ];
  12986. if (empty($episode_arr['acts'])) {
  12987. $fallback_episode_arr = handleEpisodeContent($fullContent);
  12988. if (!empty($fallback_episode_arr['acts'])) {
  12989. $episode_arr = array_merge($fallback_episode_arr, [
  12990. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  12991. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  12992. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  12993. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  12994. ]);
  12995. }
  12996. }
  12997. // if (!getProp($episode_arr, 'episode_title')) {
  12998. // $episode_title = '';
  12999. // $episodes = getProp($script_arr, 'episodes', []);
  13000. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  13001. // $episode_title = '第1集:' . $episodes[0]['title'];
  13002. // }
  13003. // if (!$episode_title) {
  13004. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  13005. // }
  13006. // $episode_arr['episode_title'] = $episode_title;
  13007. // }
  13008. return $episode_arr;
  13009. }
  13010. private function saveEpisodeVersionData(
  13011. int $anime_id,
  13012. int $episode_number,
  13013. array $episode_arr,
  13014. array $existing_roles,
  13015. array $existing_scenes,
  13016. array $existing_props,
  13017. $current_episode,
  13018. $base_episode,
  13019. bool $is_regenerate_version,
  13020. string $content,
  13021. string $now,
  13022. array $ref_products = []
  13023. ): array {
  13024. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  13025. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  13026. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  13027. // 过滤掉关键字段为空的条目
  13028. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  13029. return !empty($item['role'] ?? null);
  13030. }));
  13031. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  13032. return !empty($item['scene'] ?? null);
  13033. }));
  13034. $merged_props = array_values(array_filter($generated_props, function ($item) {
  13035. return !empty($item['prop'] ?? null);
  13036. }));
  13037. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  13038. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  13039. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  13040. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  13041. $ace_mode = getProp($anime, 'ace_mode');
  13042. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  13043. $global_roles = json_decode(getProp($anime, 'roles'), true);
  13044. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  13045. $global_roles = is_array($global_roles) ? $global_roles : [];
  13046. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  13047. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  13048. $art_style_type = getProp($anime, 'art_style_type');
  13049. // 检查并创建 roles 的图片生成任务
  13050. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  13051. // 检查并创建 scenes 的图片生成任务
  13052. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  13053. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  13054. if ($arr && is_array($arr)) {
  13055. $merged_roles = $arr['roles'];
  13056. $merged_scenes = $arr['scenes'];
  13057. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  13058. }
  13059. // 确保数据是数组类型
  13060. if (!is_array($merged_roles)) {
  13061. dLog('deepseek')->error('merged_roles不是数组类型', [
  13062. 'type' => gettype($merged_roles),
  13063. 'value' => $merged_roles
  13064. ]);
  13065. $merged_roles = [];
  13066. }
  13067. if (!is_array($merged_scenes)) {
  13068. dLog('deepseek')->error('merged_scenes不是数组类型', [
  13069. 'type' => gettype($merged_scenes),
  13070. 'value' => $merged_scenes
  13071. ]);
  13072. $merged_scenes = [];
  13073. }
  13074. if (!is_array($merged_props)) {
  13075. dLog('deepseek')->error('merged_props不是数组类型', [
  13076. 'type' => gettype($merged_props),
  13077. 'value' => $merged_props
  13078. ]);
  13079. $merged_props = [];
  13080. }
  13081. // 同步新出现的主体和场景到全局
  13082. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  13083. $role_arr = [];
  13084. foreach ($merged_roles as $item) {
  13085. $role_arr[$item['role']] = $item;
  13086. }
  13087. $version_count = DB::table('mp_anime_episodes')
  13088. ->where('anime_id', $anime_id)
  13089. ->where('episode_number', $episode_number)
  13090. ->count('id');
  13091. $episode = [
  13092. 'anime_id' => $anime_id,
  13093. 'episode_number' => $episode_number,
  13094. 'title' => getProp($episode_arr, 'episode_title'),
  13095. 'content' => $content,
  13096. 'intro' => getProp($episode_arr, 'intro'),
  13097. 'art_style' => getProp($episode_arr, 'art_style'),
  13098. 'roles' => json_encode($merged_roles, 256),
  13099. 'scenes' => json_encode($merged_scenes, 256),
  13100. 'props' => json_encode($merged_props, 256),
  13101. 'generate_status' => '待执行',
  13102. 'generate_at' => $now,
  13103. 'is_default' => 1,
  13104. 'updated_at' => $now,
  13105. ];
  13106. $del_flag = false;
  13107. if ($is_regenerate_version) {
  13108. DB::table('mp_anime_episodes')
  13109. ->where('anime_id', $anime_id)
  13110. ->where('episode_number', $episode_number)
  13111. ->update(['is_default' => 0, 'updated_at' => $now]);
  13112. $episode['sequence'] = $version_count + 1;
  13113. $episode['created_at'] = $now;
  13114. $episode['cpid'] = Site::getCpid();
  13115. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13116. if (!$episode_id) {
  13117. Utils::throwError('20003:创建剧集版本失败');
  13118. }
  13119. } else {
  13120. $target_episode = $current_episode ?: $base_episode;
  13121. if ($target_episode) {
  13122. $episode_id = getProp($target_episode, 'id');
  13123. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  13124. DB::table('mp_anime_episodes')
  13125. ->where('anime_id', $anime_id)
  13126. ->where('episode_number', $episode_number)
  13127. ->where('id', '<>', $episode_id)
  13128. ->update(['is_default' => 0, 'updated_at' => $now]);
  13129. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  13130. if ($boolen === false) {
  13131. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  13132. Utils::throwError('20003:分集内容保存失败');
  13133. }
  13134. $del_flag = true;
  13135. } else {
  13136. DB::table('mp_anime_episodes')
  13137. ->where('anime_id', $anime_id)
  13138. ->where('episode_number', $episode_number)
  13139. ->update(['is_default' => 0, 'updated_at' => $now]);
  13140. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  13141. $episode['created_at'] = $now;
  13142. $episode['cpid'] = Site::getCpid();
  13143. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13144. if (!$episode_id) {
  13145. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  13146. Utils::throwError('20003:分集内容保存失败');
  13147. }
  13148. }
  13149. }
  13150. $segments = [];
  13151. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  13152. // 如果是第2集及以后,获取上一集的主体音色数据
  13153. $previous_roles_voice = [];
  13154. if ($episode_number >= 2) {
  13155. $previous_episode = DB::table('mp_anime_episodes')
  13156. ->where('anime_id', $anime_id)
  13157. ->where('episode_number', $episode_number - 1)
  13158. ->where('is_default', 1)
  13159. ->first();
  13160. if ($previous_episode) {
  13161. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  13162. if (is_array($previous_roles)) {
  13163. foreach ($previous_roles as $prev_role) {
  13164. $role_name = getProp($prev_role, 'role');
  13165. if ($role_name) {
  13166. $previous_roles_voice[$role_name] = [
  13167. 'voice_name' => getProp($prev_role, 'voice_name'),
  13168. 'voice_type' => getProp($prev_role, 'voice_type'),
  13169. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  13170. ];
  13171. $voice_prompt = getProp($prev_role, 'voice_prompt');
  13172. if ($voice_prompt) {
  13173. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  13174. }
  13175. }
  13176. }
  13177. }
  13178. }
  13179. }
  13180. // 将继承的音色数据同步到当前集的主体列表
  13181. if (!empty($previous_roles_voice)) {
  13182. foreach ($merged_roles as &$role) {
  13183. $role_name = getProp($role, 'role');
  13184. if ($role_name && isset($previous_roles_voice[$role_name])) {
  13185. // 强制继承上一集的音色数据
  13186. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  13187. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  13188. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  13189. // 如果上一集有 voice_prompt 则继承,否则跳过
  13190. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  13191. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  13192. }
  13193. }
  13194. }
  13195. unset($role); // 解除引用
  13196. // 更新 role_arr 以便后续使用
  13197. $role_arr = [];
  13198. foreach ($merged_roles as $item) {
  13199. $role_arr[$item['role']] = $item;
  13200. }
  13201. }
  13202. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  13203. $emotion_list = array_flip($emotion_list);
  13204. foreach ($acts as $act) {
  13205. $act_segments = getProp($act, 'segments', []);
  13206. if (!is_array($act_segments)) {
  13207. continue;
  13208. }
  13209. if ((int)$ace_mode === 1) {
  13210. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  13211. $merged_parts = [];
  13212. foreach ($act_segments as $seg) {
  13213. $seg_num = getProp($seg, 'segment_number');
  13214. $seg_content = getProp($seg, 'segment_content');
  13215. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  13216. }
  13217. $act_content = implode("\n", $merged_parts);
  13218. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13219. $segments[] = [
  13220. 'anime_id' => $anime_id,
  13221. 'episode_id' => $episode_id,
  13222. 'episode_number' => $episode_number,
  13223. 'act_number' => getProp($act, 'act_number'),
  13224. 'act_title' => getProp($act, 'act_title'),
  13225. 'act_duration' => getProp($act, 'act_duration'),
  13226. 'act_content' => $act_content,
  13227. 'created_at' => $now,
  13228. 'updated_at' => $now
  13229. ];
  13230. } else {
  13231. foreach ($act_segments as $segment) {
  13232. $voice_actor = getProp($segment, 'voice_actor');
  13233. // 优先从上一集继承音色数据
  13234. $timbre_info = [];
  13235. if (isset($previous_roles_voice[$voice_actor])) {
  13236. // 从上一集继承音色数据
  13237. $timbre_info = $previous_roles_voice[$voice_actor];
  13238. } elseif (isset($role_arr[$voice_actor])) {
  13239. // 使用当前集的主体音色数据
  13240. $timbre_info = $role_arr[$voice_actor];
  13241. }
  13242. $voice_type = getProp($timbre_info, 'voice_type');
  13243. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  13244. if ($timbre_emotion) {
  13245. $timbre_emotion = explode(',', $timbre_emotion);
  13246. } else {
  13247. $timbre_emotion = [];
  13248. }
  13249. $emotion = getProp($segment, 'emotion', '中性');
  13250. if (!in_array($emotion, $timbre_emotion)) {
  13251. $emotion = '中性';
  13252. }
  13253. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  13254. $segments[] = [
  13255. 'anime_id' => $anime_id,
  13256. 'episode_id' => $episode_id,
  13257. 'episode_number' => $episode_number,
  13258. 'act_number' => getProp($act, 'act_number'),
  13259. 'act_title' => getProp($act, 'act_title'),
  13260. 'act_duration' => getProp($act, 'act_duration'),
  13261. 'segment_id' => getProp($segment, 'segment_id'),
  13262. 'segment_number' => getProp($segment, 'segment_number'),
  13263. 'segment_content' => getProp($segment, 'segment_content'),
  13264. 'description' => getProp($segment, 'description'),
  13265. 'composition' => getProp($segment, 'composition'),
  13266. 'camera_movement' => getProp($segment, 'camera_movement'),
  13267. 'voice_actor' => $voice_actor,
  13268. 'dialogue' => getProp($segment, 'dialogue'),
  13269. 'frame_type' => getProp($segment, 'frame_type'),
  13270. 'scene' => getProp($segment, 'scene'),
  13271. 'characters' => getProp($segment, 'characters'),
  13272. 'tail_frame' => getProp($segment, 'tail_frame'),
  13273. 'voice_name' => getProp($timbre_info, 'voice_name'),
  13274. 'voice_type' => $voice_type,
  13275. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  13276. 'emotion' => $emotion,
  13277. 'emotion_type' => $emotion_type,
  13278. 'gender' => getProp($segment, 'gender', '0'),
  13279. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  13280. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  13281. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  13282. 'pitch' => getProp($segment, 'pitch', 0),
  13283. 'created_at' => $now,
  13284. 'updated_at' => $now
  13285. ];
  13286. }
  13287. }
  13288. }
  13289. if ($segments) {
  13290. if ($del_flag) {
  13291. DB::table('mp_episode_segments')
  13292. ->where('anime_id', $anime_id)
  13293. ->where('episode_id', $episode_id)
  13294. ->delete();
  13295. }
  13296. $boolen = DB::table('mp_episode_segments')->insert($segments);
  13297. if (!$boolen) {
  13298. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  13299. Utils::throwError('20003:分镜内容保存失败');
  13300. }
  13301. }
  13302. dLog('deepseek')->info('segments', $segments);
  13303. // ace_mode=1: acts 返回值按合并格式调整
  13304. if ((int)$ace_mode === 1) {
  13305. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  13306. $act_map = [];
  13307. foreach ($table_act_data as $item) {
  13308. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  13309. }
  13310. $restructured_acts = [];
  13311. foreach ($acts as $act) {
  13312. $act_segments = getProp($act, 'segments', []);
  13313. if (!is_array($act_segments)) {
  13314. continue;
  13315. }
  13316. $merged_parts = [];
  13317. foreach ($act_segments as $seg) {
  13318. $seg_num = getProp($seg, 'segment_number');
  13319. $seg_content = getProp($seg, 'segment_content');
  13320. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  13321. }
  13322. $act_content = implode("\n", $merged_parts);
  13323. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13324. $restructured_acts[] = [
  13325. 'anime_id' => $anime_id,
  13326. 'episode_id' => $episode_id,
  13327. 'episode_number' => $episode_number,
  13328. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  13329. 'act_number' => getProp($act, 'act_number'),
  13330. 'act_title' => getProp($act, 'act_title'),
  13331. 'act_duration' => getProp($act, 'act_duration'),
  13332. 'act_content' => $act_content,
  13333. 'created_at' => $now,
  13334. 'updated_at' => $now,
  13335. ];
  13336. }
  13337. $acts = $restructured_acts;
  13338. }
  13339. $episode['episode_id'] = $episode_id;
  13340. $episode['roles'] = $merged_roles;
  13341. $episode['scenes'] = $merged_scenes;
  13342. $episode['props'] = $merged_props;
  13343. $episode['acts'] = $acts;
  13344. return [
  13345. 'episode' => $episode,
  13346. 'episode_id' => $episode_id,
  13347. 'merged_roles' => $merged_roles,
  13348. 'merged_scenes' => $merged_scenes,
  13349. 'merged_props' => $merged_props,
  13350. ];
  13351. }
  13352. private function buildEpisodeItemContent(array $items, string $nameKey): string
  13353. {
  13354. $content = '';
  13355. foreach ($items as $item) {
  13356. $name = trim((string)getProp($item, $nameKey));
  13357. if ($name === '' || $name === '旁白') {
  13358. continue;
  13359. }
  13360. $description = trim((string)getProp($item, 'description'));
  13361. $content .= $name . ': ' . $description;
  13362. if ($nameKey == 'role') {
  13363. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13364. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13365. $voice_name = trim(getProp($item, 'voice_name'));
  13366. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13367. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  13368. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13369. }else {
  13370. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13371. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13372. }
  13373. $content .= "\n";
  13374. }
  13375. return trim($content);
  13376. }
  13377. private function getEpisodeChatContent($animeId, $sequence, $content) {
  13378. if ((int)$sequence <= 0) {
  13379. return [];
  13380. }
  13381. $origin_content = '';
  13382. if ($content) {
  13383. $origin_content = '本集剧情内容:'.$content;
  13384. }else {
  13385. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  13386. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  13387. }
  13388. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  13389. // 获取分集信息
  13390. $episode = DB::table('mp_anime_episodes')
  13391. ->where('anime_id', $animeId)
  13392. ->where('episode_number', $sequence)
  13393. ->where('is_default', 1)
  13394. ->first();
  13395. if (!$episode) {
  13396. return [];
  13397. }
  13398. $episode_id = getProp($episode, 'id');
  13399. $episode_number = getProp($episode, 'episode_number');
  13400. $title = getProp($episode, 'title');
  13401. $intro = getProp($episode, 'intro');
  13402. $art_style = getProp($episode, 'art_style');
  13403. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13404. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13405. // 组装纯文本内容
  13406. $content = '';
  13407. // 添加分集标题和梗概
  13408. $content .= "###第{$episode_number}集:{$title}\n\n";
  13409. $content .= "###故事梗概\n";
  13410. $content .= trim($intro) . "\n\n";
  13411. // 添加美术风格
  13412. $content .= "###美术风格\n";
  13413. $content .= trim($art_style) . "\n\n";
  13414. // 添加主体列表
  13415. $content .= "###主体列表\n";
  13416. $pangbai_voice_prompt = "";
  13417. foreach ($roles as $role) {
  13418. $name = getProp($role, 'role');
  13419. $description = getProp($role, 'description');
  13420. $pic_prompt = getProp($role, 'pic_prompt');
  13421. $voice_prompt = getProp($role, 'voice_prompt');
  13422. $voice_name = getProp($role, 'voice_name');
  13423. $content .= "{$name}: {$description}";
  13424. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13425. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13426. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13427. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  13428. $content .= "\n";
  13429. }
  13430. $content .= "\n";
  13431. // 添加场景列表
  13432. $content .= "###场景列表\n";
  13433. foreach ($scenes as $scene) {
  13434. $name = getProp($scene, 'scene');
  13435. $description = getProp($scene, 'description');
  13436. $pic_prompt = getProp($scene, 'pic_prompt');
  13437. $content .= "{$name}: {$description}";
  13438. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13439. $content .= "\n";
  13440. }
  13441. $content .= "\n";
  13442. // 获取分镜信息
  13443. $segments = DB::table('mp_episode_segments')
  13444. ->where('anime_id', $animeId)
  13445. ->where('episode_id', $episode_id)
  13446. ->orderBy('segment_number')
  13447. ->get();
  13448. if ($segments && count($segments) > 0) {
  13449. if ((int)$ace_mode === 1) {
  13450. $content .= "###分段剧本\n";
  13451. // 获取片段数量
  13452. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  13453. $content .= "片段数量:{$act_count}\n";
  13454. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  13455. $content .= "\n";
  13456. }else {
  13457. $content .= "###分镜剧本\n";
  13458. }
  13459. // 按幕分组
  13460. $currentAct = null;
  13461. foreach ($segments as $segment) {
  13462. $act_number = getProp($segment, 'act_number');
  13463. $act_title = getProp($segment, 'act_title');
  13464. $act_duration = getProp($segment, 'act_duration');
  13465. $segment_number = getProp($segment, 'segment_number');
  13466. $segment_content = getProp($segment, 'segment_content');
  13467. $scene_description = getProp($segment, 'scene_description');
  13468. $scene_name = getProp($segment, 'scene_name');
  13469. $composition = getProp($segment, 'composition');
  13470. $camera_movement = getProp($segment, 'camera_movement');
  13471. $voice_type = getProp($segment, 'voice_type');
  13472. $characters = getProp($segment, 'characters');
  13473. $dialogue = getProp($segment, 'dialogue');
  13474. $frame_type = getProp($segment, 'frame_type');
  13475. $tail_frame_description = getProp($segment, 'tail_frame_description');
  13476. // 判断是否是全能模式
  13477. if ((int)$ace_mode === 1) { // 全能模式
  13478. // 如果是新的分段,添加分段标题
  13479. if ($act_number !== $currentAct) {
  13480. $currentAct = $act_number;
  13481. $content .= "##{$act_title}\n";
  13482. $content .= "时长:{$act_duration}s\n";
  13483. }
  13484. }else {
  13485. // 如果是新的幕,添加幕标题
  13486. if ($act_number !== $currentAct) {
  13487. $currentAct = $act_number;
  13488. $content .= "##第{$act_number}幕:{$scene_name}\n";
  13489. }
  13490. }
  13491. // 添加分镜信息
  13492. $content .= "分镜{$segment_number}\n";
  13493. $content .= "分镜内容:\n{$segment_content}\n";
  13494. // $content .= "画面描述:{$scene_description}\n";
  13495. // $content .= "场景:{$scene_name}\n";
  13496. // $content .= "构图设计:{$composition}\n";
  13497. // $content .= "运镜调度:{$camera_movement}\n";
  13498. // if (!empty($voice_type)) {
  13499. // $content .= "配音角色:{$voice_type}\n";
  13500. // }
  13501. // if (!empty($characters)) {
  13502. // $content .= "出镜角色:{$characters}\n";
  13503. // }
  13504. // if (!empty($dialogue)) {
  13505. // $content .= "台词内容:\"{$dialogue}\"\n";
  13506. // }
  13507. // $content .= "画面类型:{$frame_type}\n";
  13508. // $content .= "尾帧描述:{$tail_frame_description}\n";
  13509. $content .= "\n";
  13510. }
  13511. }
  13512. $content = trim($content);
  13513. if($content) $content = "上集剧本内容:\n{$content}";
  13514. return [
  13515. [
  13516. 'role' => 'user',
  13517. 'content' => $origin_content
  13518. ],
  13519. [
  13520. 'role' => 'assistant',
  13521. 'content' => $content
  13522. ]
  13523. ];
  13524. }
  13525. private function getEpisodeChatMessages($animeId, $sequence): array
  13526. {
  13527. if ((int)$sequence <= 0) {
  13528. return [];
  13529. }
  13530. return DB::table('mp_anime_records')
  13531. ->where('anime_id', $animeId)
  13532. ->where('sequence', $sequence)
  13533. ->where('episode_id', '>', 0)
  13534. ->select('role', 'content')
  13535. ->orderBy('created_at')
  13536. ->orderBy('id')
  13537. ->get()
  13538. ->map(function ($value) {
  13539. return (array)$value;
  13540. })
  13541. ->toArray();
  13542. }
  13543. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  13544. {
  13545. $existingMap = [];
  13546. foreach ($existingItems as $item) {
  13547. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13548. if ($itemKey === '') {
  13549. continue;
  13550. }
  13551. $existingMap[$itemKey] = $item;
  13552. }
  13553. if (!$generatedItems) {
  13554. return array_values($existingItems);
  13555. }
  13556. $merged = [];
  13557. foreach ($generatedItems as $item) {
  13558. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13559. if ($itemKey === '') {
  13560. continue;
  13561. }
  13562. if (isset($existingMap[$itemKey])) {
  13563. if (trim((string)getProp($item, 'description')) === '') {
  13564. $merged[] = $existingMap[$itemKey];
  13565. continue;
  13566. }
  13567. // 检查内容是否发生变化
  13568. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  13569. if (!$isChanged) {
  13570. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  13571. $mergedItem = [
  13572. $nameKey => trim((string)getProp($item, $nameKey)),
  13573. 'description' => trim((string)getProp($item, 'description')),
  13574. ];
  13575. // 如果有 pic_prompt,添加到合并项中
  13576. $picPrompt = getProp($item, 'pic_prompt');
  13577. if (!empty($picPrompt)) {
  13578. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13579. }
  13580. // 继承现有项的 URL
  13581. $existingUrl = getProp($existingMap[$itemKey], 'url');
  13582. if (!empty($existingUrl)) {
  13583. $mergedItem['url'] = $existingUrl;
  13584. }
  13585. // 继承现有项的 task_id
  13586. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  13587. if (!empty($existingTaskId)) {
  13588. $mergedItem['task_id'] = $existingTaskId;
  13589. }
  13590. // 继承现有项的 task_status
  13591. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  13592. if (!empty($existingTaskStatus)) {
  13593. $mergedItem['task_status'] = $existingTaskStatus;
  13594. }
  13595. // 保留生成项的音色字段
  13596. $voiceName = getProp($item, 'voice_name');
  13597. if (!empty($voiceName)) {
  13598. $mergedItem['voice_name'] = $voiceName;
  13599. }
  13600. $voiceType = getProp($item, 'voice_type');
  13601. if (!empty($voiceType)) {
  13602. $mergedItem['voice_type'] = $voiceType;
  13603. }
  13604. $audioUrl = getProp($item, 'voice_audio_url');
  13605. if (!empty($audioUrl)) {
  13606. $mergedItem['voice_audio_url'] = $audioUrl;
  13607. }
  13608. $merged[] = $mergedItem;
  13609. } else {
  13610. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  13611. $mergedItem = [
  13612. $nameKey => trim((string)getProp($item, $nameKey)),
  13613. 'description' => trim((string)getProp($item, 'description')),
  13614. ];
  13615. // 如果有 pic_prompt,添加到合并项中
  13616. $picPrompt = getProp($item, 'pic_prompt');
  13617. if (!empty($picPrompt)) {
  13618. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13619. }
  13620. // 保留生成项的音色字段
  13621. $voiceName = getProp($item, 'voice_name');
  13622. if (!empty($voiceName)) {
  13623. $mergedItem['voice_name'] = $voiceName;
  13624. }
  13625. $voiceType = getProp($item, 'voice_type');
  13626. if (!empty($voiceType)) {
  13627. $mergedItem['voice_type'] = $voiceType;
  13628. }
  13629. $audioUrl = getProp($item, 'voice_audio_url');
  13630. if (!empty($audioUrl)) {
  13631. $mergedItem['voice_audio_url'] = $audioUrl;
  13632. }
  13633. // 不继承 URL、task_id 和 task_status(重置状态)
  13634. $merged[] = $mergedItem;
  13635. }
  13636. } else {
  13637. // 新增项,保留生成项的所有字段
  13638. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  13639. }
  13640. }
  13641. return $merged ?: array_values($existingItems);
  13642. }
  13643. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  13644. {
  13645. $resetItem = [
  13646. $nameKey => trim((string)getProp($item, $nameKey)),
  13647. 'description' => trim((string)getProp($item, 'description')),
  13648. ];
  13649. // 保留指定的字段
  13650. foreach ($preserveFields as $field) {
  13651. $value = getProp($item, $field);
  13652. if (!empty($value)) {
  13653. $resetItem[$field] = $value;
  13654. }
  13655. }
  13656. return $resetItem;
  13657. }
  13658. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  13659. {
  13660. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  13661. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  13662. if ($existingKey !== $generatedKey) {
  13663. return true;
  13664. }
  13665. // 比较 description 是否变化
  13666. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  13667. return true;
  13668. }
  13669. // 比较 pic_prompt 是否变化
  13670. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  13671. }
  13672. private function normalizeEpisodeResourceKey($value): string
  13673. {
  13674. $value = trim((string)$value);
  13675. if ($value === '') {
  13676. return '';
  13677. }
  13678. return strtolower((string)preg_replace('/\s+/u', '', $value));
  13679. }
  13680. // 生成全局角色图片
  13681. private function batchSetGlobalRoleImg($data, $is_force=false) {
  13682. $anime_id = getProp($data, 'anime_id');
  13683. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13684. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13685. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13686. $art_style = getProp($anime, 'art_style');
  13687. $update_flag = false;
  13688. foreach ($roles as &$role) {
  13689. $role_name = getProp($role, 'role');
  13690. if ($role_name == '旁白') continue;
  13691. // 优先使用 pic_prompt,如果没有则使用 description
  13692. $pic_prompt = getProp($role, 'pic_prompt');
  13693. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13694. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13695. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13696. // 参考图地址
  13697. $ref_img_url = getProp($role, 'url');
  13698. if (!$is_force && $ref_img_url) continue;
  13699. $update_flag = true;
  13700. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13701. try {
  13702. $params = [
  13703. 'prompt' => $description,
  13704. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  13705. 'ref_img_urls' => []
  13706. ];
  13707. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13708. $task_id = $task->id;
  13709. if (!$task_id) {
  13710. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  13711. }
  13712. $role['task_id'] = $task_id;
  13713. $role['task_status'] = 'processing';
  13714. } catch (\Exception $e) {
  13715. Utils::throwError("20003:" . $e->getMessage());
  13716. }
  13717. }
  13718. if (!$update_flag) return true;
  13719. // 保存角色信息
  13720. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13721. 'roles' => json_encode($roles, 256),
  13722. 'generate_status' => '执行中',
  13723. 'generate_at' => date('Y-m-d H:i:s'),
  13724. 'updated_at' => date('Y-m-d H:i:s')
  13725. ]);
  13726. if (!$boolen) {
  13727. Utils::throwError('20003:保存角色信息失败');
  13728. }
  13729. return $boolen;
  13730. }
  13731. // 生成全局场景图片
  13732. private function batchSetGlobalSceneImg($data, $is_force=false) {
  13733. $anime_id = getProp($data, 'anime_id');
  13734. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13735. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13736. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13737. $art_style = getProp($anime, 'art_style');
  13738. $update_flag = false;
  13739. foreach ($scenes as &$scene) {
  13740. $scene_name = getProp($scene, 'scene');
  13741. // 优先使用 pic_prompt,如果没有则使用 description
  13742. $pic_prompt = getProp($scene, 'pic_prompt');
  13743. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13744. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  13745. // 参考图地址
  13746. $ref_img_url = getProp($scene, 'url');
  13747. if (!$is_force && $ref_img_url) continue;
  13748. $update_flag = true;
  13749. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13750. try {
  13751. $params = [
  13752. 'prompt' => $description,
  13753. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  13754. 'ref_img_urls' => []
  13755. ];
  13756. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13757. $task_id = $task->id;
  13758. if (!$task_id) {
  13759. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  13760. }
  13761. $scene['task_id'] = $task_id;
  13762. $scene['task_status'] = 'processing';
  13763. } catch (\Exception $e) {
  13764. Utils::throwError("20003:" . $e->getMessage());
  13765. }
  13766. }
  13767. if (!$update_flag) return true;
  13768. // 保存角色信息
  13769. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13770. 'scenes' => json_encode($scenes, 256),
  13771. 'generate_status' => '执行中',
  13772. 'generate_at' => date('Y-m-d H:i:s'),
  13773. 'updated_at' => date('Y-m-d H:i:s')
  13774. ]);
  13775. if (!$boolen) {
  13776. Utils::throwError('20003:保存角色信息失败');
  13777. }
  13778. return $boolen;
  13779. }
  13780. // 生成分镜主体、场景和道具图片
  13781. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  13782. $character_prefix = '';
  13783. $scene_prefix = '';
  13784. $prop_prefix = '';
  13785. if ($art_style_type) {
  13786. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  13787. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  13788. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  13789. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  13790. }
  13791. $update_flag = false;
  13792. // 获取上一集的roles、scenes和props数据
  13793. $prev_roles = [];
  13794. $prev_scenes = [];
  13795. $prev_props = [];
  13796. if ($episode_number > 1) {
  13797. $prev_episode = DB::table('mp_anime_episodes')
  13798. ->where('anime_id', $anime_id)
  13799. ->where('episode_number', $episode_number - 1)
  13800. ->where('is_default', 1)
  13801. ->first();
  13802. if ($prev_episode) {
  13803. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  13804. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  13805. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  13806. dLog('deepseek')->info("获取上一集数据成功", [
  13807. 'anime_id' => $anime_id,
  13808. 'prev_episode_number' => $episode_number - 1,
  13809. 'prev_roles_count' => count($prev_roles),
  13810. 'prev_scenes_count' => count($prev_scenes),
  13811. 'prev_props_count' => count($prev_props)
  13812. ]);
  13813. }
  13814. }
  13815. // 处理角色图片生成
  13816. foreach ($roles as &$role) {
  13817. $role_name = getProp($role, 'role');
  13818. if ($role_name == '旁白') continue;
  13819. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  13820. if (isset($ref_products[$role_name])) {
  13821. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  13822. $role['three_view_image_url'] = isset($ref_products[$role_name]['three_view_image_url']) ? $ref_products[$role_name]['three_view_image_url'] : '';
  13823. if ($role['url']) continue;
  13824. }
  13825. $role_description = getProp($role, 'description');
  13826. $role_pic_prompt = getProp($role, 'pic_prompt');
  13827. $role_url = getProp($role, 'url');
  13828. // 检查是否可以从上一集继承
  13829. $inherited = false;
  13830. if (!$is_force && !empty($prev_roles)) {
  13831. foreach ($prev_roles as $prev_role) {
  13832. $prev_role_name = getProp($prev_role, 'role');
  13833. $prev_description = getProp($prev_role, 'description');
  13834. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  13835. $prev_url = getProp($prev_role, 'url');
  13836. $prev_task_id = getProp($prev_role, 'task_id');
  13837. $prev_task_status = getProp($prev_role, 'task_status');
  13838. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  13839. if ($role_name == $prev_role_name
  13840. && $role_description == $prev_description
  13841. && $role_pic_prompt == $prev_pic_prompt
  13842. && !empty($prev_url)) {
  13843. $role['task_id'] = $prev_task_id;
  13844. $role['task_status'] = $prev_task_status;
  13845. $role['url'] = $prev_url;
  13846. $inherited = true;
  13847. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  13848. 'anime_id' => $anime_id,
  13849. 'episode_number' => $episode_number,
  13850. 'task_id' => $prev_task_id,
  13851. 'url' => $prev_url
  13852. ]);
  13853. break;
  13854. }
  13855. }
  13856. }
  13857. // 如果已继承或已有url,跳过生成
  13858. if ($inherited || (!$is_force && $role_url)) {
  13859. continue;
  13860. }
  13861. // 优先使用 pic_prompt,如果没有则使用 description
  13862. $pic_prompt = getProp($role, 'pic_prompt');
  13863. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13864. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13865. $update_flag = true;
  13866. // 调用AIImageGenerationService的生成图片任务接口
  13867. try {
  13868. $params = [
  13869. 'prompt' => $description,
  13870. 'ref_img_urls' => []
  13871. ];
  13872. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13873. $task_id = $task->id;
  13874. if (!$task_id) {
  13875. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  13876. continue; // 不中断,继续处理其他角色
  13877. }
  13878. $role['task_id'] = $task_id;
  13879. $role['task_status'] = 'processing';
  13880. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  13881. 'anime_id' => $anime_id,
  13882. 'episode_number' => $episode_number,
  13883. 'task_id' => $task_id
  13884. ]);
  13885. } catch (\Exception $e) {
  13886. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  13887. // 不抛出异常,继续处理其他角色
  13888. }
  13889. }
  13890. // 处理场景图片生成
  13891. foreach ($scenes as &$scene) {
  13892. $scene_name = getProp($scene, 'scene');
  13893. $scene_description = getProp($scene, 'description');
  13894. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  13895. $scene_url = getProp($scene, 'url');
  13896. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  13897. if (isset($ref_products[$scene_name])) {
  13898. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  13899. $scene['three_view_image_url'] = isset($ref_products[$scene_name]['three_view_image_url']) ? $ref_products[$scene_name]['three_view_image_url'] : '';
  13900. if ($scene['url']) continue;
  13901. }
  13902. // 检查是否可以从上一集继承
  13903. $inherited = false;
  13904. if (!$is_force && !empty($prev_scenes)) {
  13905. foreach ($prev_scenes as $prev_scene) {
  13906. $prev_scene_name = getProp($prev_scene, 'scene');
  13907. $prev_description = getProp($prev_scene, 'description');
  13908. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  13909. $prev_url = getProp($prev_scene, 'url');
  13910. $prev_task_id = getProp($prev_scene, 'task_id');
  13911. $prev_task_status = getProp($prev_scene, 'task_status');
  13912. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  13913. if ($scene_name == $prev_scene_name
  13914. && $scene_description == $prev_description
  13915. && $scene_pic_prompt == $prev_pic_prompt
  13916. && !empty($prev_url)) {
  13917. $scene['task_id'] = $prev_task_id;
  13918. $scene['task_status'] = $prev_task_status;
  13919. $scene['url'] = $prev_url;
  13920. $inherited = true;
  13921. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  13922. 'anime_id' => $anime_id,
  13923. 'episode_number' => $episode_number,
  13924. 'task_id' => $prev_task_id,
  13925. 'url' => $prev_url
  13926. ]);
  13927. break;
  13928. }
  13929. }
  13930. }
  13931. // 如果已继承或已有url,跳过生成
  13932. if ($inherited || (!$is_force && $scene_url)) {
  13933. continue;
  13934. }
  13935. // 优先使用 pic_prompt,如果没有则使用 description
  13936. $pic_prompt = getProp($scene, 'pic_prompt');
  13937. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13938. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13939. $update_flag = true;
  13940. // 调用AIImageGenerationService的生成图片任务接口
  13941. try {
  13942. $params = [
  13943. 'prompt' => $description,
  13944. 'ref_img_urls' => []
  13945. ];
  13946. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13947. $task_id = $task->id;
  13948. if (!$task_id) {
  13949. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  13950. continue; // 不中断,继续处理其他场景
  13951. }
  13952. $scene['task_id'] = $task_id;
  13953. $scene['task_status'] = 'processing';
  13954. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  13955. 'anime_id' => $anime_id,
  13956. 'episode_number' => $episode_number,
  13957. 'task_id' => $task_id
  13958. ]);
  13959. } catch (\Exception $e) {
  13960. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  13961. // 不抛出异常,继续处理其他场景
  13962. }
  13963. }
  13964. // 处理道具图片生成(逻辑与场景一致)
  13965. foreach ($props as &$prop) {
  13966. $prop_name = getProp($prop, 'prop');
  13967. $prop_description = getProp($prop, 'description');
  13968. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  13969. $prop_url = getProp($prop, 'url');
  13970. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  13971. if (isset($ref_products[$prop_name])) {
  13972. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  13973. $prop['three_view_image_url'] = isset($ref_products[$prop_name]['three_view_image_url']) ? $ref_products[$prop_name]['three_view_image_url'] : '';
  13974. if ($prop['url']) continue;
  13975. }
  13976. // 检查是否可以从上一集继承
  13977. $inherited = false;
  13978. if (!$is_force && !empty($prev_props)) {
  13979. foreach ($prev_props as $prev_prop) {
  13980. $prev_prop_name = getProp($prev_prop, 'prop');
  13981. $prev_description = getProp($prev_prop, 'description');
  13982. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  13983. $prev_url = getProp($prev_prop, 'url');
  13984. $prev_task_id = getProp($prev_prop, 'task_id');
  13985. $prev_task_status = getProp($prev_prop, 'task_status');
  13986. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  13987. if ($prop_name == $prev_prop_name
  13988. && $prop_description == $prev_description
  13989. && $prop_pic_prompt == $prev_pic_prompt
  13990. && !empty($prev_url)) {
  13991. $prop['task_id'] = $prev_task_id;
  13992. $prop['task_status'] = $prev_task_status;
  13993. $prop['url'] = $prev_url;
  13994. $inherited = true;
  13995. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  13996. 'anime_id' => $anime_id,
  13997. 'episode_number' => $episode_number,
  13998. 'task_id' => $prev_task_id,
  13999. 'url' => $prev_url
  14000. ]);
  14001. break;
  14002. }
  14003. }
  14004. }
  14005. // 如果已继承或已有url,跳过生成
  14006. if ($inherited || (!$is_force && $prop_url)) {
  14007. continue;
  14008. }
  14009. // 优先使用 pic_prompt,如果没有则使用 description
  14010. $pic_prompt = getProp($prop, 'pic_prompt');
  14011. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  14012. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14013. $update_flag = true;
  14014. // 调用AIImageGenerationService的生成图片任务接口
  14015. try {
  14016. $params = [
  14017. 'prompt' => $description,
  14018. 'ref_img_urls' => []
  14019. ];
  14020. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14021. $task_id = $task->id;
  14022. if (!$task_id) {
  14023. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  14024. continue; // 不中断,继续处理其他道具
  14025. }
  14026. $prop['task_id'] = $task_id;
  14027. $prop['task_status'] = 'processing';
  14028. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  14029. 'anime_id' => $anime_id,
  14030. 'episode_number' => $episode_number,
  14031. 'task_id' => $task_id
  14032. ]);
  14033. } catch (\Exception $e) {
  14034. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  14035. // 不抛出异常,继续处理其他道具
  14036. }
  14037. }
  14038. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14039. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  14040. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  14041. // // 保存剧集的角色和场景信息
  14042. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  14043. // 'roles' => json_encode($roles, 256),
  14044. // 'scenes' => json_encode($scenes, 256),
  14045. // 'generate_status' => '执行中',
  14046. // 'generate_at' => date('Y-m-d H:i:s'),
  14047. // 'updated_at' => date('Y-m-d H:i:s')
  14048. // ]);
  14049. // if (!$boolen) {
  14050. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  14051. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  14052. // }
  14053. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  14054. // 'episode_id' => $episode_id,
  14055. 'roles_count' => count($roles),
  14056. 'scenes_count' => count($scenes),
  14057. 'props_count' => count($props)
  14058. ]);
  14059. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14060. }
  14061. /**
  14062. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  14063. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  14064. *
  14065. * @param int $anime_id 动漫对话ID
  14066. * @param array $episode_roles 剧集角色数据
  14067. * @param array $episode_scenes 剧集场景数据
  14068. * @param array $episode_props 剧集道具数据
  14069. * @return bool
  14070. */
  14071. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  14072. // 获取全局数据
  14073. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14074. if (!$anime) {
  14075. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14076. return false;
  14077. }
  14078. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14079. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14080. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  14081. $roles_added = false;
  14082. $roles_updated = false;
  14083. $scenes_added = false;
  14084. $props_added = false;
  14085. // 处理角色同步
  14086. foreach ($episode_roles as $episode_role) {
  14087. $episode_role_name = getProp($episode_role, 'role');
  14088. $episode_description = getProp($episode_role, 'description');
  14089. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14090. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  14091. // 跳过旁白
  14092. if ($episode_role_name == '旁白') {
  14093. continue;
  14094. }
  14095. // 检查全局中是否已存在相同的角色
  14096. $exists = false;
  14097. $global_role_index = -1;
  14098. foreach ($global_roles as $index => $global_role) {
  14099. $global_role_name = getProp($global_role, 'role');
  14100. $global_description = getProp($global_role, 'description');
  14101. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14102. // 如果role、description、pic_prompt三项都一致,则认为已存在
  14103. if ($episode_role_name == $global_role_name
  14104. && $episode_description == $global_description
  14105. && $episode_pic_prompt == $global_pic_prompt) {
  14106. $exists = true;
  14107. $global_role_index = $index;
  14108. break;
  14109. }
  14110. }
  14111. // 如果不存在,则添加到全局
  14112. if (!$exists) {
  14113. $global_roles[] = $episode_role;
  14114. $roles_added = true;
  14115. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  14116. 'anime_id' => $anime_id,
  14117. 'role' => $episode_role_name
  14118. ]);
  14119. } else {
  14120. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  14121. if (!empty($episode_voice_prompt)) {
  14122. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  14123. // 如果全局没有voice_prompt或与剧集不一致,则更新
  14124. if ($global_voice_prompt !== $episode_voice_prompt) {
  14125. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  14126. $roles_updated = true;
  14127. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  14128. 'anime_id' => $anime_id,
  14129. 'role' => $episode_role_name,
  14130. 'voice_prompt' => $episode_voice_prompt
  14131. ]);
  14132. }
  14133. }
  14134. }
  14135. }
  14136. // 处理场景同步
  14137. foreach ($episode_scenes as $episode_scene) {
  14138. $episode_scene_name = getProp($episode_scene, 'scene');
  14139. $episode_description = getProp($episode_scene, 'description');
  14140. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14141. // 检查全局中是否已存在相同的场景
  14142. $exists = false;
  14143. foreach ($global_scenes as $global_scene) {
  14144. $global_scene_name = getProp($global_scene, 'scene');
  14145. $global_description = getProp($global_scene, 'description');
  14146. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14147. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  14148. if ($episode_scene_name == $global_scene_name
  14149. && $episode_description == $global_description
  14150. && $episode_pic_prompt == $global_pic_prompt) {
  14151. $exists = true;
  14152. break;
  14153. }
  14154. }
  14155. // 如果不存在,则添加到全局
  14156. if (!$exists) {
  14157. $global_scenes[] = $episode_scene;
  14158. $scenes_added = true;
  14159. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  14160. 'anime_id' => $anime_id,
  14161. 'scene' => $episode_scene_name
  14162. ]);
  14163. }
  14164. }
  14165. // 处理道具同步(逻辑与场景一致)
  14166. foreach ($episode_props as $episode_prop) {
  14167. $episode_prop_name = getProp($episode_prop, 'prop');
  14168. $episode_description = getProp($episode_prop, 'description');
  14169. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  14170. // 检查全局中是否已存在相同的道具
  14171. $exists = false;
  14172. foreach ($global_props as $global_prop) {
  14173. $global_prop_name = getProp($global_prop, 'prop');
  14174. $global_description = getProp($global_prop, 'description');
  14175. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  14176. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  14177. if ($episode_prop_name == $global_prop_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_props[] = $episode_prop;
  14187. $props_added = true;
  14188. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  14189. 'anime_id' => $anime_id,
  14190. 'prop' => $episode_prop_name
  14191. ]);
  14192. }
  14193. }
  14194. // 如果有新增或更新,则更新全局数据
  14195. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  14196. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14197. if ($roles_added || $roles_updated) {
  14198. $update_data['roles'] = json_encode($global_roles, 256);
  14199. }
  14200. if ($scenes_added) {
  14201. $update_data['scenes'] = json_encode($global_scenes, 256);
  14202. }
  14203. if ($props_added) {
  14204. $update_data['props'] = json_encode($global_props, 256);
  14205. }
  14206. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  14207. dLog('deepseek')->info('剧集数据同步到全局完成', [
  14208. 'anime_id' => $anime_id,
  14209. 'roles_added' => $roles_added,
  14210. 'roles_updated' => $roles_updated,
  14211. 'scenes_added' => $scenes_added,
  14212. 'props_added' => $props_added,
  14213. 'global_roles_count' => count($global_roles),
  14214. 'global_scenes_count' => count($global_scenes),
  14215. 'global_props_count' => count($global_props)
  14216. ]);
  14217. }
  14218. return true;
  14219. }
  14220. /**
  14221. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  14222. *
  14223. * @param int $anime_id 动漫对话ID
  14224. * @param int $episode_id 分集ID
  14225. * @return bool
  14226. */
  14227. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  14228. // 获取全局角色和场景数据
  14229. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14230. if (!$anime) {
  14231. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14232. return false;
  14233. }
  14234. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14235. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14236. // 获取指定的分集
  14237. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  14238. if (!$episode) {
  14239. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  14240. return false;
  14241. }
  14242. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  14243. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  14244. $roles_updated = false;
  14245. $scenes_updated = false;
  14246. // 继承角色的task_id、task_status和url
  14247. foreach ($episode_roles as &$episode_role) {
  14248. $episode_role_name = getProp($episode_role, 'role');
  14249. $episode_description = getProp($episode_role, 'description');
  14250. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14251. $episode_url = getProp($episode_role, 'url');
  14252. // 跳过旁白角色
  14253. if ($episode_role_name == '旁白') {
  14254. continue;
  14255. }
  14256. // 如果剧集中已有URL,跳过
  14257. if (!empty($episode_url)) {
  14258. continue;
  14259. }
  14260. // 遍历全局角色数据,查找匹配的角色
  14261. foreach ($global_roles as $global_role) {
  14262. $global_role_name = getProp($global_role, 'role');
  14263. $global_description = getProp($global_role, 'description');
  14264. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14265. $global_url = getProp($global_role, 'url');
  14266. $global_task_id = getProp($global_role, 'task_id');
  14267. $global_task_status = getProp($global_role, 'task_status');
  14268. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14269. if ($episode_role_name == $global_role_name
  14270. && $episode_description == $global_description
  14271. && $episode_pic_prompt == $global_pic_prompt) {
  14272. // 继承 task_id、task_status 和 url
  14273. if (!empty($global_task_id)) {
  14274. $episode_role['task_id'] = $global_task_id;
  14275. $episode_role['task_status'] = $global_task_status;
  14276. $roles_updated = true;
  14277. dLog('deepseek')->info('剧集角色继承全局task_id', [
  14278. 'episode_id' => $episode_id,
  14279. 'role' => $episode_role_name,
  14280. 'task_id' => $global_task_id,
  14281. 'task_status' => $global_task_status
  14282. ]);
  14283. }
  14284. if (!empty($global_url)) {
  14285. $episode_role['url'] = $global_url;
  14286. $roles_updated = true;
  14287. dLog('deepseek')->info('剧集角色继承全局url', [
  14288. 'episode_id' => $episode_id,
  14289. 'role' => $episode_role_name,
  14290. 'url' => $global_url
  14291. ]);
  14292. }
  14293. break;
  14294. }
  14295. }
  14296. }
  14297. // 继承场景的task_id、task_status和url
  14298. foreach ($episode_scenes as &$episode_scene) {
  14299. $episode_scene_name = getProp($episode_scene, 'scene');
  14300. $episode_description = getProp($episode_scene, 'description');
  14301. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14302. $episode_url = getProp($episode_scene, 'url');
  14303. // 如果剧集中已有URL,跳过
  14304. if (!empty($episode_url)) {
  14305. continue;
  14306. }
  14307. // 遍历全局场景数据,查找匹配的场景
  14308. foreach ($global_scenes as $global_scene) {
  14309. $global_scene_name = getProp($global_scene, 'scene');
  14310. $global_description = getProp($global_scene, 'description');
  14311. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14312. $global_url = getProp($global_scene, 'url');
  14313. $global_task_id = getProp($global_scene, 'task_id');
  14314. $global_task_status = getProp($global_scene, 'task_status');
  14315. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14316. if ($episode_scene_name == $global_scene_name
  14317. && $episode_description == $global_description
  14318. && $episode_pic_prompt == $global_pic_prompt) {
  14319. // 继承 task_id、task_status 和 url
  14320. if (!empty($global_task_id)) {
  14321. $episode_scene['task_id'] = $global_task_id;
  14322. $episode_scene['task_status'] = $global_task_status;
  14323. $scenes_updated = true;
  14324. dLog('deepseek')->info('剧集场景继承全局task_id', [
  14325. 'episode_id' => $episode_id,
  14326. 'scene' => $episode_scene_name,
  14327. 'task_id' => $global_task_id,
  14328. 'task_status' => $global_task_status
  14329. ]);
  14330. }
  14331. if (!empty($global_url)) {
  14332. $episode_scene['url'] = $global_url;
  14333. $scenes_updated = true;
  14334. dLog('deepseek')->info('剧集场景继承全局url', [
  14335. 'episode_id' => $episode_id,
  14336. 'scene' => $episode_scene_name,
  14337. 'url' => $global_url
  14338. ]);
  14339. }
  14340. break;
  14341. }
  14342. }
  14343. }
  14344. // 如果有更新,则保存到数据库
  14345. if ($roles_updated || $scenes_updated) {
  14346. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14347. if ($roles_updated) {
  14348. $update_data['roles'] = json_encode($episode_roles, 256);
  14349. }
  14350. if ($scenes_updated) {
  14351. $update_data['scenes'] = json_encode($episode_scenes, 256);
  14352. }
  14353. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  14354. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  14355. 'episode_id' => $episode_id,
  14356. 'roles_updated' => $roles_updated,
  14357. 'scenes_updated' => $scenes_updated
  14358. ]);
  14359. }
  14360. return true;
  14361. }
  14362. public function chatChangeImg($data) {
  14363. // 文生文计费预检(normal 档)
  14364. $uid = Site::getUid();
  14365. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  14366. $segment = getProp($data, 'segment');
  14367. $segment_content = getProp($segment, 'segment_content');
  14368. $prompt = getProp($data, 'prompt');
  14369. $ref_img = getProp($data, 'ref_img');
  14370. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  14371. // 处理文本模型
  14372. $model = getProp($data, 'model');
  14373. if (!$model) {
  14374. // 用户没有输入,从anime表获取
  14375. $segment_id = getProp($segment, 'segment_id');
  14376. if ($segment_id) {
  14377. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  14378. if ($episode_id) {
  14379. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  14380. if ($anime_id) {
  14381. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  14382. }
  14383. }
  14384. }
  14385. if (!$model) {
  14386. // anime表也没有,使用默认值
  14387. $model = 'doubao-seed-2-0-mini-260215';
  14388. }
  14389. }
  14390. // 验证模型是否在可用模型表中
  14391. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  14392. $model = 'doubao-seed-2-0-mini-260215';
  14393. }
  14394. $messages[] =
  14395. [
  14396. 'role' => 'user',
  14397. 'content' => $question
  14398. ];
  14399. $post_data = [
  14400. 'model' => $model,
  14401. 'messages' => $messages,
  14402. // 'max_tokens' => 8192,
  14403. 'temperature' => 0.7,
  14404. 'frequency_penalty' => 0,
  14405. 'presence_penalty' => 0,
  14406. 'response_format' => ['type' => 'text'],
  14407. 'stream' => false // 是否启用流式输出
  14408. ];
  14409. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14410. if (is_array($chatResult)) {
  14411. extract($chatResult);
  14412. }else {
  14413. Utils::throwError('20003: 接口调用失败!');
  14414. }
  14415. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  14416. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  14417. 'model' => $model,
  14418. 'source' => 'chatChangeImg',
  14419. ], 'normal');
  14420. return [
  14421. 'type' => 'done',
  14422. // 'episode' => $episode,
  14423. 'answer' => $fullContent,
  14424. 'reasoning' => $fullReasoningContent,
  14425. 'usage' => $usage
  14426. ];
  14427. }
  14428. /**
  14429. * 仅调用 deepseek 对话接口(非流式)
  14430. *
  14431. * @param array $post_data
  14432. * @param int $timeout
  14433. * @return array
  14434. */
  14435. private function chatOnly($post_data, $timeout = 1800) {
  14436. $post_data['max_tokens'] = 300000;
  14437. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  14438. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  14439. $response = $result->getBody()->getContents();
  14440. $response_arr = json_decode($response, true);
  14441. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  14442. $fullContent = '';
  14443. $fullReasoningContent = [];
  14444. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14445. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14446. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14447. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  14448. }
  14449. return [
  14450. 'fullContent' => $fullContent,
  14451. 'fullReasoningContent' => $fullReasoningContent,
  14452. 'usage' => $usage
  14453. ];
  14454. }
  14455. /**
  14456. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  14457. *
  14458. * @param string $errorMessage
  14459. * @return string|null
  14460. */
  14461. public function analyzeErrorMessage($errorMessage)
  14462. {
  14463. try {
  14464. $post_data = [
  14465. 'model' => 'deepseek-v4-flash',
  14466. 'messages' => [
  14467. [
  14468. 'role' => 'system',
  14469. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  14470. ],
  14471. [
  14472. 'role' => 'user',
  14473. 'content' => (string)$errorMessage,
  14474. ],
  14475. ],
  14476. 'temperature' => 0.3,
  14477. 'frequency_penalty' => 0,
  14478. 'presence_penalty' => 0,
  14479. 'response_format' => ['type' => 'text'],
  14480. 'stream' => false,
  14481. ];
  14482. $result = $this->chatOnly($post_data, 8);
  14483. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  14484. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  14485. 'model' => 'deepseek-v4-flash',
  14486. 'source' => 'analyzeErrorMessage',
  14487. ], 'deepseek-v4-flash');
  14488. $content = trim((string)($result['fullContent'] ?? ''));
  14489. if ($content === '') {
  14490. return null;
  14491. }
  14492. return mb_substr($content, 0, 50);
  14493. } catch (\Exception $e) {
  14494. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  14495. 'error_message' => $errorMessage
  14496. ]);
  14497. return null;
  14498. }
  14499. }
  14500. // 仅调用 GPT-5.4 对话接口(非流式)
  14501. private function gpt54ChatOnly($post_data) {
  14502. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  14503. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  14504. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  14505. if ($modelName === 'gpt-5.4') {
  14506. $modelName = 'gpt-5.6-terra';
  14507. $post_data['model'] = $modelName;
  14508. }
  14509. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  14510. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  14511. $usedLunaFallback = false;
  14512. if (empty($apiKey)) {
  14513. Utils::throwError('20003:GPT-5.4 API Key未配置');
  14514. }
  14515. // 先探活,服务不可用时自动重试
  14516. $this->ensureGptServiceAvailable($apiKey);
  14517. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14518. // 移除 thinking 参数,GPT-5.4 不支持
  14519. if (isset($post_data['thinking'])) {
  14520. unset($post_data['thinking']);
  14521. }
  14522. if (isset($post_data['reasoning_effort'])) {
  14523. unset($post_data['reasoning_effort']);
  14524. }
  14525. $post_data['max_completion_tokens'] = 100000;
  14526. // GPT-5.x 上游不支持 max_tokens,与 gpt54StreamResponse 保持一致,显式移除避免 400。
  14527. unset($post_data['max_tokens']);
  14528. // GPT-5.x 上游不接受 frequency_penalty / presence_penalty,移除默认值 0 不影响行为。
  14529. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  14530. // 确保 stream 为 false
  14531. $post_data['stream'] = false;
  14532. $maxRetries = $this->gptRetryTimes();
  14533. $interval = $this->gptRetryInterval();
  14534. $attempt = 0;
  14535. while (true) {
  14536. try {
  14537. $headers = [
  14538. 'Authorization' => 'Bearer ' . $apiKey,
  14539. 'Content-Type' => 'application/json'
  14540. ];
  14541. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  14542. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  14543. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  14544. 'json' => $post_data,
  14545. 'headers' => $headers
  14546. ]);
  14547. $response = $result->getBody()->getContents();
  14548. $response_arr = json_decode($response, true);
  14549. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  14550. $fullContent = '';
  14551. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14552. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14553. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14554. }
  14555. return [
  14556. 'fullContent' => $fullContent,
  14557. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  14558. 'usage' => $usage
  14559. ];
  14560. } catch (\Exception $e) {
  14561. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  14562. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  14563. $usedLunaFallback = true;
  14564. $apiKey = $lunaApiKey;
  14565. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  14566. continue;
  14567. }
  14568. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  14569. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  14570. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  14571. throw $e;
  14572. }
  14573. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  14574. 'retry' => $attempt + 1,
  14575. 'max_retries' => $maxRetries,
  14576. 'error' => $e->getMessage()
  14577. ]);
  14578. sleep($interval);
  14579. $attempt++;
  14580. }
  14581. }
  14582. }
  14583. public function getContentByBid($bid) {
  14584. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  14585. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  14586. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  14587. $content = '';
  14588. foreach ($chapters as $chapter) {
  14589. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  14590. }
  14591. return $content;
  14592. }
  14593. public function getContentByScriptId($script_id) {
  14594. $content = '';
  14595. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  14596. if ($contents) {
  14597. $content = implode(PHP_EOL, $contents);
  14598. }else {
  14599. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  14600. }
  14601. return $content;
  14602. }
  14603. /**
  14604. * 根据文件类型提取文本内容
  14605. *
  14606. * @param mixed $file 文件对象或文件路径
  14607. * @return string
  14608. */
  14609. public function extractFileContent($file) {
  14610. // 获取文件路径和扩展名
  14611. if (is_string($file)) {
  14612. $filePath = $file;
  14613. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  14614. } else {
  14615. // Laravel UploadedFile 对象
  14616. $filePath = $file->getRealPath();
  14617. $extension = strtolower($file->getClientOriginalExtension());
  14618. }
  14619. $content = '';
  14620. switch ($extension) {
  14621. case 'txt':
  14622. $content = $this->extractTxtContent($filePath);
  14623. break;
  14624. case 'pdf':
  14625. $content = $this->extractPdfContent($filePath);
  14626. break;
  14627. case 'doc':
  14628. case 'docx':
  14629. $content = $this->extractWordContent($filePath);
  14630. break;
  14631. // case 'jpg':
  14632. // case 'jpeg':
  14633. // case 'png':
  14634. // case 'gif':
  14635. // case 'bmp':
  14636. // case 'webp':
  14637. // $content = $this->extractImageContent($filePath);
  14638. // break;
  14639. default:
  14640. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  14641. }
  14642. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  14643. if (!mb_check_encoding($content, 'UTF-8')) {
  14644. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  14645. $content = $cleaned === false ? $content : $cleaned;
  14646. }
  14647. return $content;
  14648. }
  14649. /**
  14650. * 提取 TXT 文件内容
  14651. */
  14652. private function extractTxtContent($filePath) {
  14653. if (!file_exists($filePath)) {
  14654. Utils::throwError('20003:文件不存在');
  14655. }
  14656. $content = file_get_contents($filePath);
  14657. // 尝试检测并转换编码
  14658. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  14659. if ($encoding && $encoding !== 'UTF-8') {
  14660. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  14661. }
  14662. return trim($content);
  14663. }
  14664. /**
  14665. * 提取 PDF 文件内容
  14666. */
  14667. private function extractPdfContent($filePath) {
  14668. if (!file_exists($filePath)) {
  14669. Utils::throwError('20003:文件不存在');
  14670. }
  14671. try {
  14672. $parser = new PdfParser();
  14673. $pdf = $parser->parseFile($filePath);
  14674. $content = $pdf->getText();
  14675. return trim($content);
  14676. } catch (\Exception $e) {
  14677. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  14678. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  14679. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  14680. }
  14681. }
  14682. /**
  14683. * 提取 Word 文件内容(支持 doc 和 docx)
  14684. */
  14685. private function extractWordContent($filePath) {
  14686. if (!file_exists($filePath)) {
  14687. Utils::throwError('20003:文件不存在');
  14688. }
  14689. try {
  14690. $phpWord = WordIOFactory::load($filePath);
  14691. $content = '';
  14692. foreach ($phpWord->getSections() as $section) {
  14693. foreach ($section->getElements() as $element) {
  14694. $content .= $this->extractWordElementText($element);
  14695. // 段落边界补换行(段落内的软换行已在元素递归中处理)
  14696. $content .= "\n";
  14697. }
  14698. }
  14699. return trim($content);
  14700. } catch (\Exception $e) {
  14701. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  14702. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  14703. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  14704. }
  14705. }
  14706. /**
  14707. * 递归提取 Word 元素中的文本
  14708. */
  14709. private function extractWordElementText($element) {
  14710. $text = '';
  14711. if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak
  14712. || $element instanceof \PhpOffice\PhpWord\Element\LineBreak) {
  14713. // 软换行:保留 Word 中的换行显示,避免"第X集"标题与正文粘连
  14714. $text .= "\n";
  14715. } elseif (method_exists($element, 'getElements')) {
  14716. foreach ($element->getElements() as $childElement) {
  14717. $text .= $this->extractWordElementText($childElement);
  14718. }
  14719. } elseif (method_exists($element, 'getText')) {
  14720. $text .= $element->getText();
  14721. }
  14722. return $text;
  14723. }
  14724. /**
  14725. * 提取图片内容(使用火山引擎 OCR)
  14726. */
  14727. private function extractImageContent($filePath) {
  14728. if (!file_exists($filePath)) {
  14729. Utils::throwError('20003:文件不存在');
  14730. }
  14731. try {
  14732. // 读取图片并转换为 base64
  14733. $imageData = file_get_contents($filePath);
  14734. $base64Image = base64_encode($imageData);
  14735. // 调用火山引擎 OCR 服务
  14736. $content = $this->callVolcEngineOCR($base64Image);
  14737. return trim($content);
  14738. } catch (\Exception $e) {
  14739. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  14740. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  14741. Utils::throwError('20003:图片识别失败');
  14742. }
  14743. }
  14744. /**
  14745. * 调用火山引擎 OCR 服务识别图片文字
  14746. *
  14747. * @param string $base64Image base64 编码的图片数据
  14748. * @return string 识别的文字内容
  14749. */
  14750. private function callVolcEngineOCR($base64Image) {
  14751. $method = 'POST';
  14752. $service = 'cv';
  14753. $host = 'visual.volcengineapi.com';
  14754. $region = env('VOLC_REGION', 'cn-north-1');
  14755. $access_key = env('VOLC_AK');
  14756. $secret_key = env('VOLC_SK');
  14757. $action = 'OCRNormal';
  14758. $version = '2020-08-26';
  14759. if (!$access_key || !$secret_key) {
  14760. Utils::throwError('20003:请配置火山引擎 AK/SK');
  14761. }
  14762. // 请求体
  14763. $body = json_encode([
  14764. 'image_base64' => $base64Image
  14765. ]);
  14766. // 生成签名
  14767. $headers = $this->getVolcEngineSignHeaders(
  14768. $method, $service, $host, $region,
  14769. "Action={$action}&Version={$version}",
  14770. $access_key, $secret_key, $body
  14771. );
  14772. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14773. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  14774. 'headers' => $headers,
  14775. 'body' => $body
  14776. ]);
  14777. $response_arr = json_decode($response->getBody()->getContents(), true);
  14778. // 提取识别的文字
  14779. $textLines = [];
  14780. if (isset($response_arr['data']['line_texts'])) {
  14781. $textLines = $response_arr['data']['line_texts'];
  14782. } elseif (isset($response_arr['data']['ocr_infos'])) {
  14783. foreach ($response_arr['data']['ocr_infos'] as $info) {
  14784. if (isset($info['text'])) {
  14785. $textLines[] = $info['text'];
  14786. }
  14787. }
  14788. }
  14789. if (empty($textLines)) {
  14790. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  14791. return '';
  14792. }
  14793. return implode("\n", $textLines);
  14794. }
  14795. /**
  14796. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  14797. */
  14798. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  14799. $contentType = 'application/json';
  14800. $accept = 'application/json';
  14801. // 获取当前UTC时间
  14802. $t = new DateTime('now', new DateTimeZone('UTC'));
  14803. $xDate = $t->format('Ymd\THis\Z');
  14804. $dateStamp = $t->format('Ymd');
  14805. // 计算 body 的 sha256 哈希
  14806. $payloadHash = hash('sha256', $body);
  14807. // 1. 拼接规范请求串
  14808. $canonicalUri = '/';
  14809. $canonicalQueryString = $queryString;
  14810. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  14811. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  14812. $canonicalRequest = implode("\n", [
  14813. $method,
  14814. $canonicalUri,
  14815. $canonicalQueryString,
  14816. $canonicalHeaders,
  14817. $signedHeaders,
  14818. $payloadHash
  14819. ]);
  14820. // 2. 拼接待签名字符串
  14821. $algorithm = 'HMAC-SHA256';
  14822. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  14823. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  14824. $stringToSign = implode("\n", [
  14825. $algorithm,
  14826. $xDate,
  14827. $credentialScope,
  14828. $hashedCanonicalRequest
  14829. ]);
  14830. // 3. 计算签名
  14831. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  14832. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  14833. // 4. 添加签名到请求头
  14834. $authorizationHeader = sprintf(
  14835. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  14836. $algorithm,
  14837. $access_key,
  14838. $credentialScope,
  14839. $signedHeaders,
  14840. $signature
  14841. );
  14842. return [
  14843. 'Accept' => $accept,
  14844. 'Content-Type' => $contentType,
  14845. 'Host' => $host,
  14846. 'X-Date' => $xDate,
  14847. 'X-Content-Sha256'=> $payloadHash,
  14848. 'Authorization' => $authorizationHeader
  14849. ];
  14850. }
  14851. public function generateScriptWords($cid, $model = 'r1') {
  14852. ini_set('max_execution_time', 0);
  14853. if (!$cid) Utils::throwError('20003: 请选择章节!');
  14854. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  14855. // 模型兼容性处理和思考模式设置
  14856. $thinkingMode = 'disabled';
  14857. $reasoningEffort = 'high';
  14858. if ($model == 'r1') {
  14859. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  14860. $thinkingMode = 'enabled';
  14861. } else {
  14862. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  14863. $thinkingMode = 'disabled';
  14864. }
  14865. $messages = [
  14866. [
  14867. 'role' => 'system',
  14868. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  14869. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  14870. 2.非对话部分请全部用旁白角色代替
  14871. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  14872. ],
  14873. [
  14874. 'role' => 'user',
  14875. 'content' => $content
  14876. ]
  14877. ];
  14878. $post_data = [
  14879. 'model' => $model,
  14880. 'messages' => $messages,
  14881. // 'max_tokens' => 8192,
  14882. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  14883. 'frequency_penalty' => 0,
  14884. 'presence_penalty' => 0,
  14885. 'thinking' => ['type' => $thinkingMode],
  14886. 'response_format' => [
  14887. 'type' => 'text'
  14888. ],
  14889. 'stream' => false
  14890. ];
  14891. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  14892. // 根据模型类型选择调用方法
  14893. $fullContent = '';
  14894. $usage = [];
  14895. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14896. if (is_array($chatResult)) {
  14897. $fullContent = $chatResult['fullContent'];
  14898. $usage = $chatResult['usage'] ?? [];
  14899. }
  14900. // 仅记录 token 使用明细(不扣积分)
  14901. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  14902. 'model' => $model,
  14903. 'cid' => $cid,
  14904. 'source' => 'generateScriptWords',
  14905. ], $model);
  14906. return $fullContent;
  14907. }
  14908. /**
  14909. * 智能化解析集数信息
  14910. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  14911. *
  14912. * @param string $prompt 用户输入的提示词
  14913. * @return int|null 解析出的集数,如果没有找到则返回null
  14914. */
  14915. private function extractEpisodeNumber($prompt)
  14916. {
  14917. if (empty($prompt)) {
  14918. return null;
  14919. }
  14920. // 定义各种可能的表达模式
  14921. $patterns = [
  14922. // 基本模式:改成N集、调整成N集、修改成N集
  14923. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  14924. // 扩展模式:分成N集、拆分成N集、分割成N集
  14925. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  14926. // 数量模式:N集、共N集、总共N集
  14927. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  14928. // 制作模式:制作N集、生成N集、创建N集
  14929. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  14930. // 计划模式:计划N集、预计N集、打算N集
  14931. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  14932. // 需要模式:需要N集、要N集
  14933. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  14934. // 中文数字模式:改成三集、调整成五集等
  14935. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  14936. // 英文数字模式
  14937. '/(?: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',
  14938. ];
  14939. // 中文数字转阿拉伯数字的映射
  14940. $chineseNumbers = [
  14941. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  14942. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  14943. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  14944. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  14945. ];
  14946. // 逐个尝试匹配模式
  14947. foreach ($patterns as $pattern) {
  14948. if (preg_match($pattern, $prompt, $matches)) {
  14949. $number = trim($matches[1]);
  14950. // 如果是中文数字,转换为阿拉伯数字
  14951. if (isset($chineseNumbers[$number])) {
  14952. return $chineseNumbers[$number];
  14953. }
  14954. // 如果是阿拉伯数字,直接返回
  14955. if (is_numeric($number)) {
  14956. $episodeNum = intval($number);
  14957. // 合理性检查:集数应该在1-100之间
  14958. if ($episodeNum >= 1 && $episodeNum <= 100) {
  14959. return $episodeNum;
  14960. }
  14961. }
  14962. }
  14963. }
  14964. return null;
  14965. }
  14966. /**
  14967. * 调用火山引擎对话(Chat) API
  14968. *
  14969. * @param array $params 包含以下参数:
  14970. * - model: 模型ID(必填)
  14971. * - messages: 消息列表(必填)
  14972. * - stream: 是否流式输出(可选,默认false)
  14973. * - max_tokens: 最大输出token数(可选)
  14974. * - temperature: 采样温度(可选,默认1)
  14975. * - top_p: 核采样概率(可选,默认0.7)
  14976. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  14977. * - presence_penalty: 存在惩罚系数(可选,默认0)
  14978. * - stop: 停止词(可选)
  14979. * - tools: 工具列表(可选)
  14980. * @return array|Generator 非流式返回数组,流式返回生成器
  14981. */
  14982. public function volcEngineChatCompletion(array $params)
  14983. {
  14984. // 百度 GLM 已由 dispatchStreamByModel / dispatchChatOnlyByModel 统一分发,此处不再转发
  14985. $frontModel = getProp($params, 'model', '');
  14986. if (in_array($frontModel, $this->baidu_glm_text_models, true)) {
  14987. Utils::throwError('20003:百度GLM模型请使用统一分发方法dispatchStreamByModel/dispatchChatOnlyByModel调用');
  14988. }
  14989. $apiKey = env('VOLC_AI_API_KEY');
  14990. if (empty($apiKey)) {
  14991. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  14992. }
  14993. // 构建请求参数
  14994. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  14995. $requestData = [
  14996. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  14997. 'messages' => $params['messages'] ?? [],
  14998. ];
  14999. if (!in_array($originalModel, $this->valid_text_models)) {
  15000. Utils::throwError('20003:该模型不支持!');
  15001. }
  15002. // 添加可选参数
  15003. if (isset($params['stream'])) {
  15004. $requestData['stream'] = $params['stream'];
  15005. }
  15006. if (isset($params['stream_options'])) {
  15007. $requestData['stream_options'] = $params['stream_options'];
  15008. }
  15009. if (isset($params['max_tokens'])) {
  15010. $requestData['max_tokens'] = $params['max_tokens'];
  15011. }else if (isset($params['max_completion_tokens'])) {
  15012. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  15013. }else {
  15014. $requestData['max_completion_tokens'] = 100000;
  15015. }
  15016. if (isset($params['temperature'])) {
  15017. $requestData['temperature'] = $params['temperature'];
  15018. }
  15019. if (isset($params['top_p'])) {
  15020. $requestData['top_p'] = $params['top_p'];
  15021. }
  15022. if (isset($params['frequency_penalty'])) {
  15023. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  15024. }
  15025. if (isset($params['presence_penalty'])) {
  15026. $requestData['presence_penalty'] = $params['presence_penalty'];
  15027. }
  15028. if (isset($params['stop'])) {
  15029. $requestData['stop'] = $params['stop'];
  15030. }
  15031. if (isset($params['tools'])) {
  15032. $requestData['tools'] = $params['tools'];
  15033. }
  15034. if (isset($params['tool_choice'])) {
  15035. $requestData['tool_choice'] = $params['tool_choice'];
  15036. }
  15037. if (isset($params['response_format'])) {
  15038. $requestData['response_format'] = $params['response_format'];
  15039. }
  15040. if (isset($params['thinking'])) {
  15041. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  15042. if (is_array($params['thinking'])) {
  15043. $requestData['thinking'] = $params['thinking'];
  15044. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  15045. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15046. }
  15047. } else {
  15048. $requestData['thinking'] = ['type' => $params['thinking']];
  15049. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  15050. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15051. }
  15052. }
  15053. } else {
  15054. $requestData['thinking'] = ['type' => 'disabled'];
  15055. }
  15056. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  15057. $client = new Client(['verify' => false, 'timeout' => 1800]);
  15058. try {
  15059. // 判断是否为流式输出
  15060. $isStream = isset($params['stream']) && $params['stream'] === true;
  15061. if ($isStream) {
  15062. // 流式输出
  15063. // 流式请求默认声明返回 usage(未显式传参时)
  15064. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  15065. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  15066. } else {
  15067. // 非流式输出
  15068. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15069. 'headers' => [
  15070. 'Authorization' => 'Bearer ' . $apiKey,
  15071. 'Content-Type' => 'application/json',
  15072. ],
  15073. 'json' => $requestData
  15074. ]);
  15075. $responseData = json_decode($response->getBody(), true);
  15076. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  15077. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  15078. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  15079. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  15080. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  15081. }
  15082. return [
  15083. 'fullContent' => $fullContent,
  15084. 'fullReasoningContent' => $fullReasoningContent,
  15085. 'usage' => $usage
  15086. ];
  15087. }
  15088. } catch (\Exception $e) {
  15089. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  15090. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  15091. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  15092. }
  15093. }
  15094. /**
  15095. * 火山引擎对话API流式输出
  15096. *
  15097. * @param Client $client HTTP客户端
  15098. * @param string $apiKey API密钥
  15099. * @param array $requestData 请求数据
  15100. * @return Generator
  15101. */
  15102. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  15103. {
  15104. try {
  15105. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15106. 'headers' => [
  15107. 'Authorization' => 'Bearer ' . $apiKey,
  15108. 'Content-Type' => 'application/json',
  15109. ],
  15110. 'json' => $requestData,
  15111. 'stream' => true
  15112. ]);
  15113. $body = $response->getBody();
  15114. $buffer = '';
  15115. $fullContent = '';
  15116. $fullReasoningContent = '';
  15117. $usage = [];
  15118. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  15119. // 逐行读取流式响应
  15120. while (!$body->eof()) {
  15121. $chunk = $body->read(1024);
  15122. $buffer .= $chunk;
  15123. // 按行分割
  15124. $lines = explode("\n", $buffer);
  15125. $buffer = array_pop($lines);
  15126. foreach ($lines as $line) {
  15127. $line = trim($line);
  15128. if (empty($line)) {
  15129. continue;
  15130. }
  15131. // 检查是否是SSE数据行
  15132. if (strpos($line, 'data: ') !== 0) {
  15133. continue;
  15134. }
  15135. $data = substr($line, 6);
  15136. if ($data === '[DONE]') {
  15137. dLog('deepseek')->info('收到结束标记');
  15138. break 2;
  15139. }
  15140. try {
  15141. $json = json_decode($data, true);
  15142. if (json_last_error() !== JSON_ERROR_NONE) {
  15143. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  15144. continue;
  15145. }
  15146. if (isset($json['choices'][0]['delta'])) {
  15147. $delta = $json['choices'][0]['delta'];
  15148. // 处理思维链内容
  15149. if (isset($delta['reasoning_content'])) {
  15150. $fullReasoningContent .= $delta['reasoning_content'];
  15151. yield [
  15152. 'type' => 'reasoning',
  15153. 'content' => $delta['reasoning_content'],
  15154. 'full_reasoning' => $fullReasoningContent
  15155. ];
  15156. }
  15157. // 处理回答内容
  15158. if (isset($delta['content'])) {
  15159. $fullContent .= $delta['content'];
  15160. yield [
  15161. 'type' => 'content',
  15162. 'content' => $delta['content'],
  15163. ];
  15164. }
  15165. }
  15166. // 获取使用统计信息
  15167. if (isset($json['usage'])) {
  15168. $usage = $json['usage'];
  15169. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  15170. }
  15171. } catch (\Exception $e) {
  15172. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  15173. continue;
  15174. }
  15175. }
  15176. }
  15177. dLog('deepseek')->info('流式读取完成', [
  15178. 'content_length' => strlen($fullContent),
  15179. 'reasoning_length' => strlen($fullReasoningContent)
  15180. ]);
  15181. yield [
  15182. 'type' => 'done',
  15183. 'full_content' => $fullContent,
  15184. 'full_reasoning' => $fullReasoningContent,
  15185. 'usage' => $usage
  15186. ];
  15187. } catch (\Exception $e) {
  15188. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  15189. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  15190. throw $e;
  15191. }
  15192. }
  15193. /**
  15194. * 检查并创建图片生成任务
  15195. *
  15196. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  15197. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  15198. * @param string $nameKey 资源名称字段('role' 或 'scene')
  15199. * @param string $art_style 美术风格
  15200. * @return array 更新后的资源列表
  15201. */
  15202. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  15203. {
  15204. // 确保参数为数组
  15205. $merged_items = is_array($merged_items) ? $merged_items : [];
  15206. $global_items = is_array($global_items) ? $global_items : [];
  15207. // 构建全局资源映射表,用于快速查找
  15208. $global_map = [];
  15209. foreach ($global_items as $item) {
  15210. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  15211. if ($itemKey === '') {
  15212. continue;
  15213. }
  15214. $global_map[$itemKey] = $item;
  15215. }
  15216. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  15217. foreach ($merged_items as &$item) {
  15218. $item_name = getProp($item, $nameKey);
  15219. $item_description = getProp($item, 'description');
  15220. // $item_url = getProp($item, 'url');
  15221. // // 如果已有图片URL,跳过
  15222. // if (!empty($item_url)) {
  15223. // continue;
  15224. // }
  15225. // 如果是旁白角色,跳过
  15226. if ($nameKey === 'role' && $item_name === '旁白') {
  15227. continue;
  15228. }
  15229. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  15230. if ($itemKey === '') {
  15231. continue;
  15232. }
  15233. $need_create_task = false;
  15234. // 条件1:在全局资源中找不到匹配的名称
  15235. if (!isset($global_map[$itemKey])) {
  15236. $need_create_task = true;
  15237. } else {
  15238. // 条件2:名称匹配但描述或 pic_prompt 不一致
  15239. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  15240. $current_description = trim((string)$item_description);
  15241. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  15242. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  15243. // 如果 description 或 pic_prompt 有变化,需要重新生成
  15244. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  15245. $need_create_task = true;
  15246. }
  15247. }
  15248. // 如果需要创建任务,调用图片生成服务
  15249. if ($need_create_task) {
  15250. try {
  15251. // 优先使用 pic_prompt,如果没有则使用 description
  15252. $pic_prompt = getProp($item, 'pic_prompt');
  15253. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  15254. // 添加美术风格前缀
  15255. if ($art_style) {
  15256. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  15257. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  15258. $description = "{$prefix}:{$description}";
  15259. }
  15260. $params = [
  15261. 'prompt' => $description,
  15262. 'ref_img_urls' => []
  15263. ];
  15264. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  15265. $task_id = $task->id;
  15266. if ($task_id) {
  15267. $item['task_id'] = $task_id;
  15268. $item['task_status'] = 'processing';
  15269. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15270. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  15271. }
  15272. } catch (\Exception $e) {
  15273. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15274. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  15275. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  15276. // 不抛出异常,继续处理其他资源
  15277. }
  15278. }
  15279. }
  15280. return $merged_items;
  15281. }
  15282. /**
  15283. * 同步新出现的主体和场景到全局
  15284. *
  15285. * @param int $anime_id 动漫ID
  15286. * @param array $merged_roles 合并后的角色列表
  15287. * @param array $merged_scenes 合并后的场景列表
  15288. * @param array $global_roles 全局角色列表
  15289. * @param array $global_scenes 全局场景列表
  15290. * @return void
  15291. */
  15292. private function syncNewResourcesToGlobal(
  15293. int $anime_id,
  15294. array $merged_roles,
  15295. array $merged_scenes,
  15296. array $global_roles,
  15297. array $global_scenes
  15298. ): void {
  15299. // 构建全局角色映射表
  15300. $global_role_map = [];
  15301. foreach ($global_roles as $role) {
  15302. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  15303. if ($roleKey !== '') {
  15304. $global_role_map[$roleKey] = $role;
  15305. }
  15306. }
  15307. // 构建全局场景映射表
  15308. $global_scene_map = [];
  15309. foreach ($global_scenes as $scene) {
  15310. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  15311. if ($sceneKey !== '') {
  15312. $global_scene_map[$sceneKey] = $scene;
  15313. }
  15314. }
  15315. $need_update = false;
  15316. $new_global_roles = $global_roles;
  15317. $new_global_scenes = $global_scenes;
  15318. // 检查并添加新角色到全局
  15319. foreach ($merged_roles as $role) {
  15320. $role_name = getProp($role, 'role');
  15321. // 跳过旁白
  15322. if ($role_name === '旁白') {
  15323. continue;
  15324. }
  15325. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  15326. if ($roleKey === '') {
  15327. continue;
  15328. }
  15329. // 如果全局中不存在该角色,添加到全局
  15330. if (!isset($global_role_map[$roleKey])) {
  15331. $new_global_roles[] = [
  15332. 'role' => $role_name,
  15333. 'description' => getProp($role, 'description', ''),
  15334. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  15335. 'voice_name' => getProp($role, 'voice_name', ''),
  15336. 'voice_type' => getProp($role, 'voice_type', ''),
  15337. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  15338. 'url' => getProp($role, 'url', ''),
  15339. 'task_id' => getProp($role, 'task_id', ''),
  15340. 'task_status' => getProp($role, 'task_status', ''),
  15341. ];
  15342. $global_role_map[$roleKey] = true; // 标记已添加
  15343. $need_update = true;
  15344. dLog('deepseek')->info("新角色同步到全局", [
  15345. 'anime_id' => $anime_id,
  15346. 'role' => $role_name,
  15347. 'task_id' => getProp($role, 'task_id', ''),
  15348. ]);
  15349. }
  15350. // else {
  15351. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15352. // $global_role = $global_role_map[$roleKey];
  15353. // if (is_array($global_role)) {
  15354. // $updated = false;
  15355. // $update_fields = [];
  15356. // // 检查描述是否更新
  15357. // $current_description = trim((string)getProp($role, 'description'));
  15358. // $global_description = trim((string)getProp($global_role, 'description'));
  15359. // if ($current_description !== '' && $current_description !== $global_description) {
  15360. // $updated = true;
  15361. // $update_fields[] = 'description';
  15362. // }
  15363. // // 检查pic_prompt是否更新
  15364. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  15365. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  15366. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15367. // $updated = true;
  15368. // $update_fields[] = 'pic_prompt';
  15369. // }
  15370. // // 检查图片任务信息是否更新
  15371. // $current_task_id = getProp($role, 'task_id');
  15372. // $global_task_id = getProp($global_role, 'task_id');
  15373. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15374. // $updated = true;
  15375. // $update_fields[] = 'task_id';
  15376. // }
  15377. // // 如果有更新,同步到全局
  15378. // if ($updated) {
  15379. // foreach ($new_global_roles as &$global_role_item) {
  15380. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  15381. // if ($global_role_key === $roleKey) {
  15382. // if (in_array('description', $update_fields)) {
  15383. // $global_role_item['description'] = $current_description;
  15384. // }
  15385. // if (in_array('pic_prompt', $update_fields)) {
  15386. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  15387. // }
  15388. // if (in_array('task_id', $update_fields)) {
  15389. // $global_role_item['task_id'] = $current_task_id;
  15390. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  15391. // $global_role_item['url'] = getProp($role, 'url', '');
  15392. // }
  15393. // break;
  15394. // }
  15395. // }
  15396. // $need_update = true;
  15397. // dLog('deepseek')->info("角色信息更新到全局", [
  15398. // 'anime_id' => $anime_id,
  15399. // 'role' => $role_name,
  15400. // 'update_fields' => implode(',', $update_fields),
  15401. // ]);
  15402. // }
  15403. // }
  15404. // }
  15405. }
  15406. // 检查并添加新场景到全局
  15407. foreach ($merged_scenes as $scene) {
  15408. $scene_name = getProp($scene, 'scene');
  15409. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  15410. if ($sceneKey === '') {
  15411. continue;
  15412. }
  15413. // 如果全局中不存在该场景,添加到全局
  15414. if (!isset($global_scene_map[$sceneKey])) {
  15415. $new_global_scenes[] = [
  15416. 'scene' => $scene_name,
  15417. 'description' => getProp($scene, 'description', ''),
  15418. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  15419. 'url' => getProp($scene, 'url', ''),
  15420. 'task_id' => getProp($scene, 'task_id', ''),
  15421. 'task_status' => getProp($scene, 'task_status', ''),
  15422. ];
  15423. $global_scene_map[$sceneKey] = true; // 标记已添加
  15424. $need_update = true;
  15425. dLog('deepseek')->info("新场景同步到全局", [
  15426. 'anime_id' => $anime_id,
  15427. 'scene' => $scene_name,
  15428. 'task_id' => getProp($scene, 'task_id', ''),
  15429. ]);
  15430. }
  15431. // else {
  15432. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15433. // $global_scene = $global_scene_map[$sceneKey];
  15434. // if (is_array($global_scene)) {
  15435. // $updated = false;
  15436. // $update_fields = [];
  15437. // // 检查描述是否更新
  15438. // $current_description = trim((string)getProp($scene, 'description'));
  15439. // $global_description = trim((string)getProp($global_scene, 'description'));
  15440. // if ($current_description !== '' && $current_description !== $global_description) {
  15441. // $updated = true;
  15442. // $update_fields[] = 'description';
  15443. // }
  15444. // // 检查pic_prompt是否更新
  15445. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  15446. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  15447. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15448. // $updated = true;
  15449. // $update_fields[] = 'pic_prompt';
  15450. // }
  15451. // // 检查图片任务信息是否更新
  15452. // $current_task_id = getProp($scene, 'task_id');
  15453. // $global_task_id = getProp($global_scene, 'task_id');
  15454. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15455. // $updated = true;
  15456. // $update_fields[] = 'task_id';
  15457. // }
  15458. // // 如果有更新,同步到全局
  15459. // if ($updated) {
  15460. // foreach ($new_global_scenes as &$global_scene_item) {
  15461. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  15462. // if ($global_scene_key === $sceneKey) {
  15463. // if (in_array('description', $update_fields)) {
  15464. // $global_scene_item['description'] = $current_description;
  15465. // }
  15466. // if (in_array('pic_prompt', $update_fields)) {
  15467. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  15468. // }
  15469. // if (in_array('task_id', $update_fields)) {
  15470. // $global_scene_item['task_id'] = $current_task_id;
  15471. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  15472. // $global_scene_item['url'] = getProp($scene, 'url', '');
  15473. // }
  15474. // break;
  15475. // }
  15476. // }
  15477. // $need_update = true;
  15478. // dLog('deepseek')->info("场景信息更新到全局", [
  15479. // 'anime_id' => $anime_id,
  15480. // 'scene' => $scene_name,
  15481. // 'update_fields' => implode(',', $update_fields),
  15482. // ]);
  15483. // }
  15484. // }
  15485. // }
  15486. }
  15487. // 如果有新增或更新,更新数据库
  15488. if ($need_update) {
  15489. $update_data = [
  15490. 'roles' => json_encode($new_global_roles, 256),
  15491. 'scenes' => json_encode($new_global_scenes, 256),
  15492. 'updated_at' => date('Y-m-d H:i:s'),
  15493. ];
  15494. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  15495. if ($result !== false) {
  15496. dLog('deepseek')->info("全局角色和场景更新成功", [
  15497. 'anime_id' => $anime_id,
  15498. 'roles_count' => count($new_global_roles),
  15499. 'scenes_count' => count($new_global_scenes),
  15500. ]);
  15501. } else {
  15502. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  15503. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  15504. }
  15505. }
  15506. }
  15507. }