DeepSeekService.php 856 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Models\MpTaskCenter;
  11. use App\Models\MpUserPointsDetail;
  12. use App\Services\AIGeneration\AIImageGenerationService;
  13. use App\Services\PointsService;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. use Smalot\PdfParser\Parser as PdfParser;
  20. use TCPDF;
  21. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  22. use Predis\Command\Traits\Get\Get;
  23. class DeepSeekService
  24. {
  25. private $url;
  26. private $api_key;
  27. private $sys_message;
  28. private $headers;
  29. private $valid_text_models;
  30. private $gpt_text_models;
  31. private $gemini_text_models;
  32. protected $aiImageGenerationService;
  33. protected $pointsService;
  34. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  35. $this->aiImageGenerationService = $aiImageGenerationService;
  36. $this->pointsService = $pointsService;
  37. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  38. $this->api_key = env('DEEPSEEK_API_KEY');
  39. $this->headers = [
  40. 'Authorization' => 'Bearer '.$this->api_key,
  41. 'Content-Type' => 'application/json; charset=UTF-8'
  42. ];
  43. // 火山引擎模型列表
  44. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  45. // GPT文本模型列表
  46. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  47. // Gemini文本模型列表
  48. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  49. $this->sys_message = [
  50. 'role' => 'system',
  51. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  52. 强制要求:\n
  53. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  54. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  55. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  56. 普通要求:\n
  57. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  58. 2.<分集剧本>的要求如下:
  59.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  60.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  61.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  62.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  63. \n\n
  64. 示例如下:\n
  65. ###剧本名:西昆仑
  66. ###故事梗概
  67. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  68. ###剧本亮点
  69. 亮点1:绝境奇药,生死一线
  70. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  71. 亮点2:结拜兄妹,化解尴尬
  72. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  73. 亮点3:纤发夺命,情愫暗涌
  74. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  75. ###人物关系
  76. 阿雪与梁萧之间存在兄妹之情。
  77. ###核心矛盾
  78. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  79. ###主体列表
  80. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  81. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  82. 阴阳球:天地异宝,能化生精气,救人于危难。
  83. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  84. ###美术风格
  85. 基础画风风格词:厚涂古风
  86. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  87. ###场景列表
  88. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  89. ###分集剧本
  90. ##分集01
  91. 第1集: 第一集的标题
  92. 场景描述:地点、时间、场景
  93. 运镜:固定近距离
  94. 出场角色:男主、女主
  95. 台词内容:
  96. 女主: 女主对话
  97. 男主:男主对话
  98. 女主: 女主对话
  99. 男主: 男主对话
  100. ##分集02
  101. 第2集: 第二集的标题
  102. 场景描述:地点、时间、场景
  103. 运镜:固定近距离
  104. 出场角色:男主、女主
  105. 台词内容:
  106. 女主: 女主对话
  107. 男主:男主对话
  108. 女主: 女主对话
  109. 男主: 男主对话"
  110. ];
  111. }
  112. /**
  113. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  114. *
  115. * @param array $data 请求参数
  116. * @return \Generator 返回生成器,用于流式输出
  117. */
  118. public function generateText($data) {
  119. // 获取请求参数
  120. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  121. $messages = getProp($data, 'messages', []);
  122. $systemPrompt = getProp($data, 'system_prompt', '');
  123. $prompt = getProp($data, 'prompt', '');
  124. $images = getProp($data, 'images', []); // 支持多张图片
  125. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  126. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  127. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  128. $isGeminiModel = in_array($model, $this->gemini_text_models);
  129. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  130. Utils::throwError('20003:仅Gemini模型支持视频输入');
  131. }
  132. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  133. $uid = Site::getUid();
  134. $chargeModality = '';
  135. $chargePoints = 0;
  136. $hasImageMedia = !empty($images) || !empty($imageUrls)
  137. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  138. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  139. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  140. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  141. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  142. $pricingModel = $this->geminiMultimodalPricingModel($model);
  143. if ($pricingModel !== '') {
  144. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  145. if ($chargePoints > 0) {
  146. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  147. }
  148. }
  149. }
  150. // 如果没有提供messages,则根据system_prompt、content和images构建
  151. if (empty($messages)) {
  152. $messages = [];
  153. // 添加系统提示词
  154. if (!empty($systemPrompt)) {
  155. $messages[] = [
  156. 'role' => 'system',
  157. 'content' => $systemPrompt
  158. ];
  159. }
  160. // 构建用户消息内容(支持文本+图片)
  161. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  162. $userMessage = [
  163. 'role' => 'user',
  164. 'content' => []
  165. ];
  166. // 添加文本内容
  167. if (!empty($prompt)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'text',
  170. 'text' => $prompt
  171. ];
  172. }
  173. // 处理上传的图片文件
  174. if (!empty($images)) {
  175. if (!is_array($images)) {
  176. $images = [$images];
  177. }
  178. foreach ($images as $image) {
  179. $imageBase64 = $this->processImageToBase64($image);
  180. if ($imageBase64) {
  181. $userMessage['content'][] = [
  182. 'type' => 'image_url',
  183. 'image_url' => [
  184. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  185. ]
  186. ];
  187. }
  188. }
  189. }
  190. // 处理图片URL
  191. if (!empty($imageUrls)) {
  192. if (!is_array($imageUrls)) {
  193. $imageUrls = [$imageUrls];
  194. }
  195. foreach ($imageUrls as $url) {
  196. if (!empty($url)) {
  197. $userMessage['content'][] = [
  198. 'type' => 'image_url',
  199. 'image_url' => [
  200. 'url' => $url
  201. ]
  202. ];
  203. }
  204. }
  205. }
  206. // 处理上传的视频文件(仅 Gemini)
  207. if (!empty($videos) && $isGeminiModel) {
  208. if (!is_array($videos)) {
  209. $videos = [$videos];
  210. }
  211. foreach ($videos as $video) {
  212. $inlineData = $this->processMediaToInlineData($video);
  213. if ($inlineData) {
  214. $userMessage['content'][] = [
  215. 'type' => 'video',
  216. 'inline_data' => $inlineData
  217. ];
  218. }
  219. }
  220. }
  221. // 处理视频URL(仅 Gemini)
  222. if (!empty($videoUrls) && $isGeminiModel) {
  223. if (!is_array($videoUrls)) {
  224. $videoUrls = [$videoUrls];
  225. }
  226. foreach ($videoUrls as $url) {
  227. if (!empty($url)) {
  228. $userMessage['content'][] = [
  229. 'type' => 'video_url',
  230. 'video_url' => ['url' => $url]
  231. ];
  232. }
  233. }
  234. }
  235. // 如果只有文本内容,简化为字符串格式
  236. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  237. $userMessage['content'] = $userMessage['content'][0]['text'];
  238. }
  239. $messages[] = $userMessage;
  240. }
  241. }
  242. // 验证messages不为空
  243. if (empty($messages)) {
  244. Utils::throwError('20003:请提供有效的对话内容');
  245. }
  246. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  247. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  248. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  249. if ($model === 'deepseek-chat') {
  250. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  251. $model = 'deepseek-v4-flash';
  252. $thinkingMode = 'disabled';
  253. } elseif ($model === 'deepseek-reasoner') {
  254. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'enabled';
  257. }
  258. // 构建请求参数
  259. $post_data = [
  260. 'model' => $model,
  261. 'messages' => $messages,
  262. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  263. 'temperature' => getProp($data, 'temperature', 1),
  264. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  265. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  266. 'thinking' => ['type' => $thinkingMode],
  267. 'stream' => true // 启用流式输出
  268. ];
  269. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  270. // 添加可选参数
  271. if (isset($data['top_p'])) {
  272. $post_data['top_p'] = $data['top_p'];
  273. }
  274. if (isset($data['response_format'])) {
  275. $post_data['response_format'] = $data['response_format'];
  276. }
  277. // 根据模型类型选择调用方法
  278. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  279. // DeepSeek 官方模型使用 DeepSeek API
  280. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  281. } else if (in_array($model, $this->gpt_text_models)) {
  282. // GPT 模型使用 TokenRouter API
  283. $streamGenerator = $this->gpt54StreamResponse($post_data);
  284. } else if (in_array($model, $this->gemini_text_models)) {
  285. // Gemini 模型使用 Gemini API
  286. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  287. } else if (in_array($model, $this->valid_text_models)) {
  288. // 火山引擎支持的模型使用火山引擎 API
  289. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  290. } else {
  291. Utils::throwError('20003:不支持的模型: ' . $model);
  292. }
  293. if ($chargePoints > 0) {
  294. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  295. }
  296. // 纯文本(不扣积分):流式生成成功后仅记录 token 使用明细
  297. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  298. }
  299. /**
  300. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  301. *
  302. * @param \Generator $generator
  303. * @param int $uid
  304. * @param string $model
  305. * @return \Generator
  306. */
  307. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  308. {
  309. $recorded = false;
  310. foreach ($generator as $chunk) {
  311. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  312. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  313. 'model' => $model,
  314. 'source' => $source,
  315. ], $model);
  316. $recorded = true;
  317. }
  318. yield $chunk;
  319. }
  320. }
  321. /**
  322. * 流式生成成功后再按 Gemini 多模态规则扣费
  323. *
  324. * @param \Generator $generator
  325. * @param int $uid
  326. * @param string $model
  327. * @param int $points
  328. * @param string $modality
  329. * @return \Generator
  330. */
  331. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  332. {
  333. $charged = false;
  334. foreach ($generator as $chunk) {
  335. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  336. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  337. if ($fullContent !== '') {
  338. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  339. $charged = true;
  340. }
  341. }
  342. yield $chunk;
  343. }
  344. }
  345. /**
  346. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  347. *
  348. * @param int $uid
  349. * @param string $model
  350. * @param int $points
  351. * @param string $modality
  352. * @param mixed $usage
  353. * @return void
  354. */
  355. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  356. {
  357. $result = $this->pointsService->recordChatCharge(
  358. $uid,
  359. $points,
  360. $this->pointsService->getTokensFromUsage($usage),
  361. [
  362. 'model' => $model,
  363. 'modality' => $modality,
  364. 'source' => 'generateText',
  365. ],
  366. '',
  367. $model
  368. );
  369. if (empty($result['charged'])) {
  370. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  371. }
  372. }
  373. /**
  374. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  375. *
  376. * @param string $model
  377. * @return string
  378. */
  379. private function geminiMultimodalPricingModel(string $model): string
  380. {
  381. $map = [
  382. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  383. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  384. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  385. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  386. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  387. ];
  388. return $map[$model] ?? '';
  389. }
  390. /**
  391. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  392. *
  393. * @param array $messages
  394. * @param array $mediaTypes
  395. * @return bool
  396. */
  397. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  398. {
  399. foreach ($messages as $message) {
  400. $content = getProp($message, 'content', '');
  401. if (!is_array($content)) {
  402. continue;
  403. }
  404. foreach ($content as $part) {
  405. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  406. return true;
  407. }
  408. }
  409. }
  410. return false;
  411. }
  412. public function createGenerateText($data) {
  413. $file = getProp($data, 'file');
  414. $episode_num = getProp($data, 'episode_num');
  415. $uid = Site::getUid();
  416. $cpid = Site::getCpid();
  417. if (!$file) {
  418. Utils::throwError('20003:请上传文件');
  419. }
  420. // 提取文件内容
  421. $content = $this->extractFileContent($file);
  422. if (!$content) {
  423. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  424. }
  425. // 拆分章节并校验章节总数、标题连续性
  426. if ($episode_num) {
  427. $this->validateGenerateTextChapters($content, (int)$episode_num);
  428. }
  429. // 获取原始文件名(不含扩展名)作为script_name
  430. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  431. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  432. // 字节安全剥离,不依赖服务器locale设置
  433. $originalName = $file->getClientOriginalName();
  434. $extension = $file->getClientOriginalExtension();
  435. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  436. ? substr($originalName, 0, -strlen($extension) - 1)
  437. : $originalName;
  438. if ($script_name === '') {
  439. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  440. }
  441. // 如果同一用户的剧本名存在则提示
  442. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  443. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  444. }
  445. // 插入数据到mp_scripts表
  446. $script_id = DB::table('mp_scripts')->insertGetId([
  447. 'script_name' => $script_name,
  448. 'user_id' => $uid,
  449. 'cpid' => $cpid,
  450. 'content' => $content,
  451. 'created_at' => date('Y-m-d H:i:s'),
  452. 'updated_at' => date('Y-m-d H:i:s')
  453. ]);
  454. return [
  455. 'script_id' => $script_id,
  456. 'script_name' => $script_name
  457. ];
  458. }
  459. /**
  460. * AI对话调用成功后的积分扣费(返回结果前调用)
  461. *
  462. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  463. *
  464. * @param int $uid
  465. * @param int $tokens
  466. * @param array $chargeInfo
  467. * @return void
  468. */
  469. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  470. {
  471. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  472. $model = (string)getProp($chargeInfo, 'model', '');
  473. $result = $this->pointsService->recordChatCharge(
  474. $uid,
  475. $this->pointsService->getChatChargePoints($model),
  476. $tokens,
  477. $chargeInfo,
  478. '',
  479. $model !== '' ? $model : 'deepseek'
  480. );
  481. if (empty($result['charged'])) {
  482. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  483. }
  484. }
  485. /**
  486. * 安全获取当前登录用户ID
  487. *
  488. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  489. *
  490. * @return int
  491. */
  492. private function getCurrentUid(): int
  493. {
  494. try {
  495. return (int)Site::getUid();
  496. } catch (\Throwable $e) {
  497. return 0;
  498. }
  499. }
  500. /**
  501. * 记录文生文 token 使用明细(仅记录,不扣积分)
  502. *
  503. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  504. *
  505. * @param int $uid 用户ID(0 时跳过)
  506. * @param int $tokens 消耗 token 数
  507. * @param array $chargeInfo 计费/来源信息(model、source 等)
  508. * @param string $apiType API 类型/模型标识
  509. * @return void
  510. */
  511. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  512. {
  513. try {
  514. $this->pointsService->recordTokenOnlyDetail(
  515. $uid,
  516. $tokens,
  517. $chargeInfo,
  518. MpUserPointsDetail::TYPE_CHAT,
  519. $apiType,
  520. ''
  521. );
  522. } catch (\Throwable $e) {
  523. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  524. 'uid' => $uid,
  525. 'source' => $chargeInfo['source'] ?? '',
  526. ]);
  527. }
  528. }
  529. /**
  530. * 拆分剧本内容并校验章节总数与标题连续性
  531. *
  532. * @param string $content
  533. * @param int $episodeNum
  534. * @return void
  535. */
  536. private function validateGenerateTextChapters($content, $episodeNum)
  537. {
  538. $chapters = splitContent($content);
  539. if (count($chapters) !== $episodeNum) {
  540. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  541. }
  542. if (empty($chapters)) {
  543. return;
  544. }
  545. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  546. $numbers = [];
  547. $unparsedIndex = null;
  548. foreach ($chapters as $index => $chapter) {
  549. $num = $this->parseChapterNumber($chapter['title']);
  550. if ($num === null) {
  551. $unparsedIndex = $index;
  552. break;
  553. }
  554. $numbers[] = $num;
  555. }
  556. if ($unparsedIndex === null) {
  557. $expected = 1;
  558. foreach ($numbers as $index => $num) {
  559. if ($num !== $expected) {
  560. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  561. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  562. }
  563. $expected++;
  564. }
  565. return;
  566. }
  567. // 标题格式无法用正则确认时,交给模型分析
  568. $titles = array_column($chapters, 'title');
  569. $aiResult = $this->validateChapterSequenceByAI($titles);
  570. if ($aiResult['valid'] === false) {
  571. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  572. if (isset($chapters[$badIndex - 1])) {
  573. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  574. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  575. }
  576. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  577. }
  578. if ($aiResult['valid'] === null) {
  579. if (isset($chapters[$unparsedIndex])) {
  580. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  581. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  582. }
  583. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  584. }
  585. }
  586. /**
  587. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  588. *
  589. * @param string $title
  590. * @return int|null
  591. */
  592. private function parseChapterNumber($title)
  593. {
  594. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  595. return null;
  596. }
  597. return $this->convertChineseNumber($match[1]);
  598. }
  599. /**
  600. * 中文数字转阿拉伯数字(支持到千)
  601. *
  602. * @param string $numStr
  603. * @return int
  604. */
  605. private function convertChineseNumber($numStr)
  606. {
  607. if (preg_match('/^\d+$/', $numStr)) {
  608. return (int)$numStr;
  609. }
  610. $map = [
  611. '零' => 0,
  612. '一' => 1,
  613. '二' => 2,
  614. '两' => 2,
  615. '三' => 3,
  616. '四' => 4,
  617. '五' => 5,
  618. '六' => 6,
  619. '七' => 7,
  620. '八' => 8,
  621. '九' => 9
  622. ];
  623. $total = 0;
  624. $section = 0;
  625. $length = mb_strlen($numStr);
  626. for ($i = 0; $i < $length; $i++) {
  627. $char = mb_substr($numStr, $i, 1);
  628. if (isset($map[$char])) {
  629. $section = $map[$char];
  630. } elseif ($char === '十') {
  631. $total += $section === 0 ? 10 : $section * 10;
  632. $section = 0;
  633. } elseif ($char === '百') {
  634. $total += $section === 0 ? 100 : $section * 100;
  635. $section = 0;
  636. } elseif ($char === '千') {
  637. $total += $section === 0 ? 1000 : $section * 1000;
  638. $section = 0;
  639. }
  640. }
  641. return $total + $section;
  642. }
  643. /**
  644. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  645. *
  646. * @param array $titles
  647. * @return array{valid: bool|null, invalid_index: int|null}
  648. */
  649. private function validateChapterSequenceByAI($titles)
  650. {
  651. $titleLines = [];
  652. foreach (array_slice($titles, 0, 200) as $index => $title) {
  653. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  654. }
  655. $result = [
  656. 'valid' => null,
  657. 'invalid_index' => null
  658. ];
  659. $post_data = [
  660. 'model' => 'deepseek-v4-flash',
  661. 'messages' => [
  662. [
  663. 'role' => 'system',
  664. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  665. ],
  666. [
  667. 'role' => 'user',
  668. 'content' => implode("\n", $titleLines),
  669. ],
  670. ],
  671. 'temperature' => 0,
  672. 'frequency_penalty' => 0,
  673. 'presence_penalty' => 0,
  674. 'stream' => false,
  675. ];
  676. try {
  677. $result = $this->chatOnly($post_data, 8);
  678. $content = trim((string)($result['fullContent'] ?? ''));
  679. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  680. $result['valid'] = strtolower($match[1]) === 'true';
  681. }
  682. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  683. $result['invalid_index'] = (int)$match[1];
  684. }
  685. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  686. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  687. 'model' => 'deepseek-v4-flash',
  688. 'source' => 'validateChapterSequenceByAI',
  689. ], 'deepseek-v4-flash');
  690. } catch (\Exception $e) {
  691. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  692. }
  693. return $result;
  694. }
  695. /**
  696. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  697. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  698. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  699. *
  700. * @param array $data 请求参数
  701. * @return \Generator
  702. */
  703. public function newGenerateTextStream($data) {
  704. $model = getProp($data, 'model', 'deepseek-v4-pro');
  705. $messages = getProp($data, 'messages', []);
  706. $systemPrompt = getProp($data, 'system_prompt', '');
  707. $prompt = getProp($data, 'prompt', '');
  708. $images = getProp($data, 'images', []);
  709. $imageUrls = getProp($data, 'image_urls', []);
  710. $responseFormat = getProp($data, 'response_format', 'text');
  711. $templateId = getProp($data, 'template_id', 0);
  712. $script_id = getProp($data, 'script_id', 0);
  713. $sequence = getProp($data, 'sequence', 0);
  714. $generateTaskId = 0;
  715. $uid = Site::getUid();
  716. if ($script_id > 0) {
  717. $existingTask = DB::table('mp_script_generate_tasks')
  718. ->where('uid', $uid)
  719. ->where('script_id', $script_id)
  720. ->orderByDesc('id')
  721. ->first();
  722. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  723. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  724. }
  725. }
  726. // 如果提供了script_id,从数据库获取剧本内容作为原文
  727. $originalContent = '';
  728. $hasValidScript = false;
  729. if ($script_id > 0) {
  730. $script = DB::table('mp_scripts')
  731. ->where('id', $script_id)
  732. ->where('is_deleted', 0)
  733. ->first();
  734. if (!$script) {
  735. Utils::throwError('20003:剧本不存在或已删除');
  736. }
  737. $originalContent = $script->content ?? '';
  738. if (empty($originalContent)) {
  739. Utils::throwError('20003:剧本内容为空');
  740. }
  741. $hasValidScript = true;
  742. if (!empty($prompt)) {
  743. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  744. } else {
  745. $prompt = "原文内容:\n" . $originalContent;
  746. }
  747. }
  748. // 如果提供了template_id,从数据库获取template_prompt
  749. if ($templateId > 0) {
  750. $template = DB::table('mp_prompt_templates')
  751. ->where('id', $templateId)
  752. ->where('is_deleted', 0)
  753. ->first();
  754. if (!$template) {
  755. Utils::throwError('20003:模板不存在或已删除');
  756. }
  757. $templatePrompt = $template->template_prompt ?? '';
  758. if (!empty($templatePrompt)) {
  759. if (!empty($prompt)) {
  760. $prompt = $templatePrompt . "\n\n" . $prompt;
  761. } else {
  762. $prompt = $templatePrompt;
  763. }
  764. }
  765. }
  766. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  767. if (empty($messages)) {
  768. $messages = [];
  769. if (!empty($systemPrompt)) {
  770. $messages[] = [
  771. 'role' => 'system',
  772. 'content' => $systemPrompt
  773. ];
  774. }
  775. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  776. $userMessage = [
  777. 'role' => 'user',
  778. 'content' => []
  779. ];
  780. if (!empty($prompt)) {
  781. $userMessage['content'][] = [
  782. 'type' => 'text',
  783. 'text' => $prompt
  784. ];
  785. }
  786. if (!empty($images)) {
  787. if (!is_array($images)) {
  788. $images = [$images];
  789. }
  790. foreach ($images as $image) {
  791. $imageBase64 = $this->processImageToBase64($image);
  792. if ($imageBase64) {
  793. $userMessage['content'][] = [
  794. 'type' => 'image_url',
  795. 'image_url' => [
  796. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  797. ]
  798. ];
  799. }
  800. }
  801. }
  802. if (!empty($imageUrls)) {
  803. if (!is_array($imageUrls)) {
  804. $imageUrls = [$imageUrls];
  805. }
  806. foreach ($imageUrls as $url) {
  807. if (!empty($url)) {
  808. $userMessage['content'][] = [
  809. 'type' => 'image_url',
  810. 'image_url' => [
  811. 'url' => $url
  812. ]
  813. ];
  814. }
  815. }
  816. }
  817. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  818. $userMessage['content'] = $userMessage['content'][0]['text'];
  819. }
  820. $messages[] = $userMessage;
  821. }
  822. }
  823. if (empty($messages)) {
  824. Utils::throwError('20003:请提供有效的对话内容');
  825. }
  826. // 模型兼容性处理
  827. $thinkingMode = getProp($data, 'thinking', 'disabled');
  828. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  829. if ($model === 'deepseek-chat') {
  830. $model = 'deepseek-v4-flash';
  831. $thinkingMode = 'disabled';
  832. } elseif ($model === 'deepseek-reasoner') {
  833. $model = 'deepseek-v4-flash';
  834. $thinkingMode = 'enabled';
  835. }
  836. // 构建请求参数(流式)
  837. $post_data = [
  838. 'model' => $model,
  839. 'messages' => $messages,
  840. 'temperature' => getProp($data, 'temperature', 1),
  841. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  842. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  843. 'thinking' => ['type' => $thinkingMode],
  844. 'stream' => true
  845. ];
  846. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  847. if (isset($data['top_p'])) {
  848. $post_data['top_p'] = $data['top_p'];
  849. }
  850. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  851. if ($responseFormat === 'json') {
  852. $hasJsonKeyword = false;
  853. foreach ($post_data['messages'] as $message) {
  854. if (isset($message['content'])) {
  855. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  856. if (stripos($content, 'json') !== false) {
  857. $hasJsonKeyword = true;
  858. break;
  859. }
  860. }
  861. }
  862. if (!$hasJsonKeyword) {
  863. $lastMessageIndex = count($post_data['messages']) - 1;
  864. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  865. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  866. if (is_string($lastContent)) {
  867. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  868. } elseif (is_array($lastContent)) {
  869. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  870. if ($contentPart['type'] === 'text') {
  871. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  872. break;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. $post_data['response_format'] = ['type' => 'json_object'];
  879. }
  880. // 如果提供了script_id,创建剧本资产生成任务
  881. if ($script_id > 0) {
  882. $uid = Site::getUid();
  883. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  884. 'uid' => $uid,
  885. 'script_id' => $script_id,
  886. 'sequence' => $sequence,
  887. 'status' => 'processing',
  888. 'prompt' => getProp($data, 'prompt', ''),
  889. 'started_at' => date('Y-m-d H:i:s'),
  890. 'created_at' => date('Y-m-d H:i:s'),
  891. 'updated_at' => date('Y-m-d H:i:s')
  892. ]);
  893. }
  894. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  895. if ($hasValidScript) {
  896. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  897. }
  898. // 根据模型类型选择流式调用方法
  899. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  900. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  901. } elseif (in_array($model, $this->gpt_text_models)) {
  902. $streamGenerator = $this->gpt54StreamResponse($post_data);
  903. } elseif (in_array($model, $this->gemini_text_models)) {
  904. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  905. } elseif (in_array($model, $this->valid_text_models)) {
  906. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  907. } else {
  908. Utils::throwError('20003:不支持的模型: ' . $model);
  909. }
  910. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  911. return $this->wrapNewGenerateTextStream($streamGenerator, [
  912. 'uid' => $uid,
  913. 'model' => $model,
  914. 'generate_task_id' => $generateTaskId,
  915. 'has_valid_script' => $hasValidScript,
  916. 'script_id' => $script_id,
  917. 'sequence' => $sequence,
  918. 'original_prompt' => getProp($data, 'prompt', ''),
  919. 'response_format' => $responseFormat,
  920. ]);
  921. }
  922. /**
  923. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  924. *
  925. * @param \Generator $generator
  926. * @param array $ctx
  927. * @return \Generator
  928. */
  929. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  930. {
  931. $fullContent = '';
  932. $usage = [];
  933. $finished = false;
  934. try {
  935. foreach ($generator as $chunk) {
  936. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  937. $fullContent .= (string)getProp($chunk, 'content', '');
  938. }
  939. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  940. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  941. $usage = getProp($chunk, 'usage', []);
  942. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  943. if (($ctx['response_format'] ?? 'text') === 'json') {
  944. $fullContent = $this->extractJsonContent($fullContent);
  945. }
  946. $finished = true;
  947. }
  948. yield $chunk;
  949. }
  950. if ($finished) {
  951. if (!empty($ctx['generate_task_id'])) {
  952. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  953. 'status' => 'success',
  954. 'result' => $fullContent,
  955. 'completed_at' => date('Y-m-d H:i:s'),
  956. 'updated_at' => date('Y-m-d H:i:s'),
  957. ]);
  958. }
  959. if ($ctx['has_valid_script'] && $fullContent !== '') {
  960. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  961. 'model' => $ctx['model'],
  962. 'script_id' => $ctx['script_id'],
  963. 'sequence' => $ctx['sequence'],
  964. 'source' => 'newGenerateText',
  965. ]);
  966. }
  967. if (!empty($ctx['script_id'])) {
  968. $now = now();
  969. DB::table('mp_script_records')->insert([
  970. [
  971. 'uid' => $ctx['uid'],
  972. 'script_id' => $ctx['script_id'],
  973. 'sequence' => $ctx['sequence'],
  974. 'role' => 'user',
  975. 'content' => $ctx['original_prompt'],
  976. 'created_at' => $now,
  977. 'updated_at' => $now,
  978. ],
  979. [
  980. 'uid' => $ctx['uid'],
  981. 'script_id' => $ctx['script_id'],
  982. 'sequence' => $ctx['sequence'],
  983. 'role' => 'assistant',
  984. 'content' => $fullContent,
  985. 'created_at' => $now,
  986. 'updated_at' => $now,
  987. ],
  988. ]);
  989. }
  990. }
  991. } catch (\Throwable $e) {
  992. if (!empty($ctx['generate_task_id'])) {
  993. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  994. 'status' => 'failed',
  995. 'error_message' => $e->getMessage(),
  996. 'completed_at' => date('Y-m-d H:i:s'),
  997. 'updated_at' => date('Y-m-d H:i:s'),
  998. ]);
  999. }
  1000. yield [
  1001. 'type' => 'error',
  1002. 'message' => $e->getMessage(),
  1003. ];
  1004. }
  1005. }
  1006. /**
  1007. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1008. *
  1009. * @param string $content
  1010. * @return string
  1011. */
  1012. private function extractJsonContent(string $content): string
  1013. {
  1014. $content = trim($content);
  1015. if ($content === '') {
  1016. return $content;
  1017. }
  1018. // 剥离 ```json ... ``` 代码块
  1019. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1020. $content = trim($m[1]);
  1021. }
  1022. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1023. $first = strpos($content, '{');
  1024. $last = strrpos($content, '}');
  1025. if ($first !== false && $last !== false && $last > $first) {
  1026. $content = substr($content, $first, $last - $first + 1);
  1027. }
  1028. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1029. json_decode($content, true);
  1030. if (json_last_error() !== JSON_ERROR_NONE) {
  1031. return trim($content);
  1032. }
  1033. return $content;
  1034. }
  1035. /**
  1036. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1037. *
  1038. * @param array $data 请求参数
  1039. * @return array 返回结果数组
  1040. */
  1041. public function newGenerateText($data) {
  1042. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1043. if ((int)getProp($data, 'stream', 0) === 1) {
  1044. return $this->newGenerateTextStream($data);
  1045. }
  1046. // 获取请求参数
  1047. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1048. $messages = getProp($data, 'messages', []);
  1049. $systemPrompt = getProp($data, 'system_prompt', '');
  1050. $prompt = getProp($data, 'prompt', '');
  1051. $images = getProp($data, 'images', []); // 支持多张图片
  1052. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1053. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1054. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1055. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1056. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1057. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1058. $generateTaskId = 0;
  1059. $uid = Site::getUid();
  1060. if ($script_id > 0) {
  1061. $existingTask = DB::table('mp_script_generate_tasks')
  1062. ->where('uid', $uid)
  1063. ->where('script_id', $script_id)
  1064. ->orderByDesc('id')
  1065. ->first();
  1066. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1067. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1068. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1069. }
  1070. }
  1071. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1072. $originalContent = '';
  1073. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1074. if ($script_id > 0) {
  1075. $script = DB::table('mp_scripts')
  1076. ->where('id', $script_id)
  1077. ->where('is_deleted', 0)
  1078. ->first();
  1079. if (!$script) {
  1080. Utils::throwError('20003:剧本不存在或已删除');
  1081. }
  1082. $originalContent = $script->content ?? '';
  1083. if (empty($originalContent)) {
  1084. Utils::throwError('20003:剧本内容为空');
  1085. }
  1086. $hasValidScript = true;
  1087. // 将剧本内容添加到提示词前面
  1088. if (!empty($originalContent)) {
  1089. if (!empty($prompt)) {
  1090. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1091. } else {
  1092. $prompt = "原文内容:\n" . $originalContent;
  1093. }
  1094. }
  1095. }
  1096. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1097. if ($templateId > 0) {
  1098. $template = DB::table('mp_prompt_templates')
  1099. ->where('id', $templateId)
  1100. ->where('is_deleted', 0)
  1101. ->first();
  1102. if (!$template) {
  1103. Utils::throwError('20003:模板不存在或已删除');
  1104. }
  1105. $templatePrompt = $template->template_prompt ?? '';
  1106. // 将模板提示词和用户输入的prompt组合
  1107. // 模板为准,用户输入作为补充要求
  1108. if (!empty($templatePrompt)) {
  1109. if (!empty($prompt)) {
  1110. $prompt = $templatePrompt . "\n\n" . $prompt;
  1111. } else {
  1112. $prompt = $templatePrompt;
  1113. }
  1114. }
  1115. }
  1116. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1117. if (empty($messages)) {
  1118. $messages = [];
  1119. // 添加系统提示词
  1120. if (!empty($systemPrompt)) {
  1121. $messages[] = [
  1122. 'role' => 'system',
  1123. 'content' => $systemPrompt
  1124. ];
  1125. }
  1126. // 构建用户消息内容(支持文本+图片)
  1127. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1128. $userMessage = [
  1129. 'role' => 'user',
  1130. 'content' => []
  1131. ];
  1132. // 添加文本内容
  1133. if (!empty($prompt)) {
  1134. $userMessage['content'][] = [
  1135. 'type' => 'text',
  1136. 'text' => $prompt
  1137. ];
  1138. }
  1139. // 处理上传的图片文件
  1140. if (!empty($images)) {
  1141. if (!is_array($images)) {
  1142. $images = [$images];
  1143. }
  1144. foreach ($images as $image) {
  1145. $imageBase64 = $this->processImageToBase64($image);
  1146. if ($imageBase64) {
  1147. $userMessage['content'][] = [
  1148. 'type' => 'image_url',
  1149. 'image_url' => [
  1150. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1151. ]
  1152. ];
  1153. }
  1154. }
  1155. }
  1156. // 处理图片URL
  1157. if (!empty($imageUrls)) {
  1158. if (!is_array($imageUrls)) {
  1159. $imageUrls = [$imageUrls];
  1160. }
  1161. foreach ($imageUrls as $url) {
  1162. if (!empty($url)) {
  1163. $userMessage['content'][] = [
  1164. 'type' => 'image_url',
  1165. 'image_url' => [
  1166. 'url' => $url
  1167. ]
  1168. ];
  1169. }
  1170. }
  1171. }
  1172. // 如果只有文本内容,简化为字符串格式
  1173. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1174. $userMessage['content'] = $userMessage['content'][0]['text'];
  1175. }
  1176. $messages[] = $userMessage;
  1177. }
  1178. }
  1179. // 验证messages不为空
  1180. if (empty($messages)) {
  1181. Utils::throwError('20003:请提供有效的对话内容');
  1182. }
  1183. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1184. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1185. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1186. if ($model === 'deepseek-chat') {
  1187. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1188. $model = 'deepseek-v4-flash';
  1189. $thinkingMode = 'disabled';
  1190. } elseif ($model === 'deepseek-reasoner') {
  1191. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1192. $model = 'deepseek-v4-flash';
  1193. $thinkingMode = 'enabled';
  1194. }
  1195. // 构建请求参数(非流式)
  1196. $post_data = [
  1197. 'model' => $model,
  1198. 'messages' => $messages,
  1199. 'temperature' => getProp($data, 'temperature', 1),
  1200. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1201. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1202. 'thinking' => ['type' => $thinkingMode],
  1203. 'stream' => false // 非流式输出
  1204. ];
  1205. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1206. // 添加可选参数
  1207. if (isset($data['top_p'])) {
  1208. $post_data['top_p'] = $data['top_p'];
  1209. }
  1210. // 新增: 根据response_format设置响应格式
  1211. if ($responseFormat === 'json') {
  1212. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1213. $hasJsonKeyword = false;
  1214. foreach ($post_data['messages'] as $message) {
  1215. if (isset($message['content'])) {
  1216. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1217. if (stripos($content, 'json') !== false) {
  1218. $hasJsonKeyword = true;
  1219. break;
  1220. }
  1221. }
  1222. }
  1223. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1224. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1225. if (!$hasJsonKeyword) {
  1226. $lastMessageIndex = count($post_data['messages']) - 1;
  1227. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1228. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1229. // 如果content是字符串,直接追加
  1230. if (is_string($lastContent)) {
  1231. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1232. }
  1233. // 如果content是数组(包含文本和图片),在文本部分追加
  1234. else if (is_array($lastContent)) {
  1235. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1236. if ($contentPart['type'] === 'text') {
  1237. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1238. break;
  1239. }
  1240. }
  1241. }
  1242. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1243. }
  1244. }
  1245. // 设置response_format参数(所有支持的模型)
  1246. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1247. // DeepSeek模型
  1248. $post_data['response_format'] = ['type' => 'json_object'];
  1249. } else if (in_array($model, $this->gpt_text_models)) {
  1250. // GPT模型
  1251. $post_data['response_format'] = ['type' => 'json_object'];
  1252. } else if (in_array($model, $this->valid_text_models)) {
  1253. // 火山引擎模型
  1254. $post_data['response_format'] = ['type' => 'json_object'];
  1255. }
  1256. }
  1257. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1258. if ($script_id > 0) {
  1259. $uid = Site::getUid();
  1260. // 创建新的生成任务
  1261. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1262. 'uid' => $uid,
  1263. 'script_id' => $script_id,
  1264. 'sequence' => $sequence,
  1265. 'status' => 'processing',
  1266. 'prompt' => getProp($data, 'prompt', ''),
  1267. 'started_at' => date('Y-m-d H:i:s'),
  1268. 'created_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s')
  1270. ]);
  1271. }
  1272. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1273. if ($hasValidScript) {
  1274. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1275. }
  1276. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  1277. try {
  1278. $aiResult = null;
  1279. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1280. // DeepSeek 官方模型使用现有的 chatOnly 方法
  1281. $result = $this->chatOnly($post_data);
  1282. // 记录实际使用的模型
  1283. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  1284. $aiResult = [
  1285. 'content' => $result['fullContent'],
  1286. 'reasoning_content' => $result['fullReasoningContent'],
  1287. 'usage' => $result['usage'],
  1288. 'model' => $model,
  1289. 'finish_reason' => 'stop'
  1290. ];
  1291. } else if (in_array($model, $this->gpt_text_models)) {
  1292. // GPT 模型使用现有的 gpt54ChatOnly 方法
  1293. $result = $this->gpt54ChatOnly($post_data);
  1294. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  1295. $aiResult = [
  1296. 'content' => $result['fullContent'],
  1297. 'reasoning_content' => '',
  1298. 'usage' => $result['usage'],
  1299. 'model' => $model,
  1300. 'finish_reason' => 'stop'
  1301. ];
  1302. } else if (in_array($model, $this->gemini_text_models)) {
  1303. // Gemini 模型使用 Gemini API(非流式)
  1304. $result = $this->geminiChatOnly($post_data, $model);
  1305. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  1306. $aiResult = [
  1307. 'content' => $result['fullContent'],
  1308. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  1309. 'usage' => $result['usage'],
  1310. 'model' => $model,
  1311. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1312. ];
  1313. } else if (in_array($model, $this->valid_text_models)) {
  1314. // 火山引擎支持的模型使用火山引擎 API(非流式)
  1315. $post_data['stream'] = false;
  1316. $result = $this->volcEngineChatCompletion($post_data);
  1317. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  1318. 'requested_model' => $model,
  1319. 'result_keys' => array_keys($result),
  1320. 'has_fullContent' => isset($result['fullContent']),
  1321. 'has_content' => isset($result['content'])
  1322. ]);
  1323. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  1324. $aiResult = [
  1325. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1326. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1327. 'usage' => $result['usage'] ?? [],
  1328. 'model' => $model,
  1329. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1330. ];
  1331. } else {
  1332. Utils::throwError('20003:不支持的模型: ' . $model);
  1333. }
  1334. } catch (\Exception $e) {
  1335. // 生成失败,更新任务状态
  1336. if ($generateTaskId) {
  1337. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1338. 'status' => 'failed',
  1339. 'error_message' => $e->getMessage(),
  1340. 'completed_at' => date('Y-m-d H:i:s'),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. }
  1344. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1345. }
  1346. // 生成成功,更新任务状态
  1347. if ($generateTaskId && $aiResult) {
  1348. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1349. 'status' => 'success',
  1350. 'result' => getProp($aiResult, 'content', ''),
  1351. 'completed_at' => date('Y-m-d H:i:s'),
  1352. 'updated_at' => date('Y-m-d H:i:s')
  1353. ]);
  1354. $aiResult['generate_task_id'] = $generateTaskId;
  1355. }
  1356. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1357. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1358. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1359. 'model' => $model,
  1360. 'script_id' => $script_id,
  1361. 'sequence' => $sequence,
  1362. 'source' => 'newGenerateText',
  1363. ]);
  1364. }
  1365. // 新增: 如果提供了script_id,保存对话记录
  1366. if ($script_id > 0 && $aiResult) {
  1367. try {
  1368. $uid = Site::getUid();
  1369. $now = now();
  1370. // 获取用户原始的prompt(不包含剧本内容)
  1371. $originalPrompt = getProp($data, 'prompt', '');
  1372. $recordsToInsert = [
  1373. [
  1374. 'uid' => $uid,
  1375. 'script_id' => $script_id,
  1376. 'sequence' => $sequence,
  1377. 'role' => 'user',
  1378. 'content' => $originalPrompt,
  1379. 'created_at' => $now,
  1380. 'updated_at' => $now,
  1381. ],
  1382. [
  1383. 'uid' => $uid,
  1384. 'script_id' => $script_id,
  1385. 'sequence' => $sequence,
  1386. 'role' => 'assistant',
  1387. 'content' => $aiResult['content'],
  1388. 'created_at' => $now,
  1389. 'updated_at' => $now,
  1390. ]
  1391. ];
  1392. DB::table('mp_script_records')->insert($recordsToInsert);
  1393. // 获取刚插入的记录ID(假设按插入顺序返回)
  1394. $insertedRecords = DB::table('mp_script_records')
  1395. ->where('uid', $uid)
  1396. ->where('script_id', $script_id)
  1397. ->where('sequence', $sequence)
  1398. ->orderBy('id', 'desc')
  1399. ->limit(2)
  1400. ->get()
  1401. ->map(function ($record) {
  1402. return [
  1403. 'rid' => $record->id,
  1404. 'script_id' => $record->script_id,
  1405. 'sequence' => $record->sequence,
  1406. 'role' => $record->role,
  1407. 'content' => $record->content,
  1408. 'created_at' => $record->created_at,
  1409. ];
  1410. })
  1411. ->reverse()
  1412. ->values()
  1413. ->toArray();
  1414. // 将记录信息添加到返回结果中
  1415. $aiResult['records'] = $insertedRecords;
  1416. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1417. } catch (\Exception $e) {
  1418. // 记录错误但不影响主流程
  1419. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1420. }
  1421. }
  1422. return $aiResult;
  1423. }
  1424. /**
  1425. * 通用 Gemini 文生文方法(支持流式和非流式)
  1426. *
  1427. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1428. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1429. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1430. * system_prompt 系统提示词(可选)
  1431. * prompt 用户提示词(可选)
  1432. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1433. * image_urls 图片/视频URL列表(可选,同上)
  1434. * temperature 温度(可选,默认 1)
  1435. * top_p 核采样(可选)
  1436. * max_tokens 最大输出 token(可选,默认 8192)
  1437. * response_format text/json(可选)
  1438. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1439. * thinking_budget 思考预算(可选,默认 20)
  1440. * stream 是否流式(可选,默认 false)
  1441. *
  1442. * @param array $data 请求参数
  1443. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1444. */
  1445. public function geminiGenerateText($data) {
  1446. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1447. $isStream = (bool)getProp($data, 'stream', false);
  1448. if (!in_array($model, $this->gemini_text_models)) {
  1449. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1450. }
  1451. $requestData = $this->buildGeminiRequestBody($data, $model);
  1452. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1453. if ($isStream) {
  1454. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1455. return $this->wrapGenerateTextTokenRecord(
  1456. $this->geminiStreamResponse($requestData, $model),
  1457. $this->getCurrentUid(),
  1458. $model,
  1459. 'geminiGenerateText'
  1460. );
  1461. }
  1462. // 非流式:成功后记录 token 使用明细(不扣积分)
  1463. $result = $this->geminiChatOnly($requestData, $model);
  1464. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1465. 'model' => $model,
  1466. 'source' => 'geminiGenerateText',
  1467. ], $model);
  1468. return $result;
  1469. }
  1470. /**
  1471. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1472. */
  1473. private function geminiMediaMaxBytes() {
  1474. return 14 * 1024 * 1024;
  1475. }
  1476. /**
  1477. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1478. */
  1479. private function buildGeminiRequestBody($data, $model) {
  1480. $messages = getProp($data, 'messages', []);
  1481. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1482. if (empty($messages)) {
  1483. $systemPrompt = getProp($data, 'system_prompt', '');
  1484. $prompt = getProp($data, 'prompt', '');
  1485. $images = getProp($data, 'images', []);
  1486. $imageUrls = getProp($data, 'image_urls', []);
  1487. $messages = [];
  1488. if (!empty($systemPrompt)) {
  1489. $messages[] = [
  1490. 'role' => 'system',
  1491. 'content' => $systemPrompt
  1492. ];
  1493. }
  1494. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1495. $userMessage = ['role' => 'user', 'content' => []];
  1496. if (!empty($prompt)) {
  1497. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1498. }
  1499. if (!empty($images)) {
  1500. if (!is_array($images)) {
  1501. $images = [$images];
  1502. }
  1503. foreach ($images as $image) {
  1504. $inlineData = $this->processMediaToInlineData($image);
  1505. if ($inlineData) {
  1506. $userMessage['content'][] = [
  1507. 'type' => 'image',
  1508. 'inline_data' => $inlineData
  1509. ];
  1510. }
  1511. }
  1512. }
  1513. if (!empty($imageUrls)) {
  1514. if (!is_array($imageUrls)) {
  1515. $imageUrls = [$imageUrls];
  1516. }
  1517. foreach ($imageUrls as $url) {
  1518. if (!empty($url)) {
  1519. $inlineData = $this->processMediaToInlineData($url);
  1520. if ($inlineData) {
  1521. $userMessage['content'][] = [
  1522. 'type' => 'image',
  1523. 'inline_data' => $inlineData
  1524. ];
  1525. }
  1526. }
  1527. }
  1528. }
  1529. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1530. $userMessage['content'] = $userMessage['content'][0]['text'];
  1531. }
  1532. $messages[] = $userMessage;
  1533. }
  1534. }
  1535. if (empty($messages)) {
  1536. Utils::throwError('20003:请提供有效的对话内容');
  1537. }
  1538. // 转换为 Gemini contents 格式
  1539. $systemInstruction = '';
  1540. $contents = [];
  1541. foreach ($messages as $message) {
  1542. $role = getProp($message, 'role', 'user');
  1543. $content = getProp($message, 'content', '');
  1544. if ($role === 'system') {
  1545. if (is_array($content)) {
  1546. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1547. } else {
  1548. $systemInstruction = (string)$content;
  1549. }
  1550. continue;
  1551. }
  1552. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1553. $parts = [];
  1554. if (is_array($content)) {
  1555. foreach ($content as $part) {
  1556. $partType = getProp($part, 'type', 'text');
  1557. if ($partType === 'text') {
  1558. $text = (string)getProp($part, 'text', '');
  1559. if ($text !== '') {
  1560. $parts[] = ['text' => $text];
  1561. }
  1562. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1563. if (in_array($partType, ['image_url', 'video_url'])) {
  1564. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1565. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1566. } elseif (isset($part['inline_data'])) {
  1567. // 已处理过的 inline_data 直接使用
  1568. $parts[] = ['inline_data' => $part['inline_data']];
  1569. continue;
  1570. } else {
  1571. $url = '';
  1572. }
  1573. $inlineData = $this->processMediaToInlineData($url);
  1574. if ($inlineData) {
  1575. $parts[] = ['inline_data' => $inlineData];
  1576. }
  1577. }
  1578. }
  1579. } else {
  1580. $text = (string)$content;
  1581. if ($text !== '') {
  1582. $parts[] = ['text' => $text];
  1583. }
  1584. }
  1585. if (!empty($parts)) {
  1586. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1587. }
  1588. }
  1589. if (empty($contents)) {
  1590. Utils::throwError('20003:请提供有效的对话内容');
  1591. }
  1592. // 构建生成配置
  1593. $generationConfig = [];
  1594. if (getProp($data, 'temperature', null) !== null) {
  1595. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1596. }
  1597. if (getProp($data, 'top_p', null) !== null) {
  1598. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1599. }
  1600. if (getProp($data, 'frequency_penalty', null) !== null) {
  1601. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1602. }
  1603. if (getProp($data, 'presence_penalty', null) !== null) {
  1604. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1605. }
  1606. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1607. if ($maxOutputTokens <= 0) {
  1608. $maxOutputTokens = 8192;
  1609. }
  1610. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1611. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1612. $maxOutputTokens = 32768;
  1613. }
  1614. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1615. // response_format 映射:text -> text/plain,json -> application/json
  1616. $responseFormat = getProp($data, 'response_format', 'text');
  1617. if (is_array($responseFormat)) {
  1618. $responseFormat = getProp($responseFormat, 'type', 'text');
  1619. }
  1620. if (in_array($responseFormat, ['json', 'json_object'])) {
  1621. $generationConfig['responseMimeType'] = 'application/json';
  1622. } else {
  1623. $generationConfig['responseMimeType'] = 'text/plain';
  1624. }
  1625. $requestData = [
  1626. 'contents' => $contents,
  1627. 'generationConfig' => $generationConfig,
  1628. ];
  1629. if ($systemInstruction !== '') {
  1630. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1631. }
  1632. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1633. $thinkingMode = getProp($data, 'thinking', null);
  1634. if (is_array($thinkingMode)) {
  1635. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1636. }
  1637. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1638. if ($thinkingMode === null) {
  1639. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1640. }
  1641. if ($thinkingMode === 'enabled') {
  1642. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1643. if ($thinkingBudget <= 0) {
  1644. $thinkingBudget = 20;
  1645. }
  1646. $requestData['generationConfig']['thinkingConfig'] = [
  1647. 'thinkingBudget' => $thinkingBudget
  1648. ];
  1649. } elseif ($defaultThinking) {
  1650. // 该模型仅支持思考模式,传 0 会返回 400
  1651. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1652. } else {
  1653. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1654. }
  1655. return $requestData;
  1656. }
  1657. /**
  1658. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1659. *
  1660. * 模型名 -> env 变量名映射:
  1661. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1662. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1663. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1664. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1665. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1666. */
  1667. private function getGeminiApiKey($model) {
  1668. $map = [
  1669. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1670. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1671. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1672. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1673. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1674. ];
  1675. if (isset($map[$model])) {
  1676. $key = env($map[$model]);
  1677. if (!empty($key)) {
  1678. return $key;
  1679. }
  1680. }
  1681. return env('GEMINI_API_KEY', '');
  1682. }
  1683. /**
  1684. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1685. */
  1686. private function geminiChatOnly($requestData, $model) {
  1687. $apiKey = $this->getGeminiApiKey($model);
  1688. if (empty($apiKey)) {
  1689. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1690. }
  1691. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1692. if (isset($requestData['messages'])) {
  1693. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1694. }
  1695. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1696. . '/models/' . $model . ':generateContent';
  1697. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1698. $headers = [
  1699. 'Authorization' => 'Bearer ' . $apiKey,
  1700. 'Content-Type' => 'application/json'
  1701. ];
  1702. $maxRetries = $this->gptRetryTimes();
  1703. $interval = $this->gptRetryInterval();
  1704. $attempt = 0;
  1705. while (true) {
  1706. try {
  1707. $response = $client->post($url, [
  1708. 'json' => $requestData,
  1709. 'headers' => $headers
  1710. ]);
  1711. $responseArr = json_decode($response->getBody()->getContents(), true);
  1712. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1713. $fullContent = $this->extractGeminiContent($responseArr);
  1714. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1715. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1716. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1717. ? $responseArr['candidates'][0]['finishReason']
  1718. : '';
  1719. return [
  1720. 'fullContent' => $fullContent,
  1721. 'fullReasoningContent' => $fullReasoningContent,
  1722. 'usage' => $usage,
  1723. 'finish_reason' => $finishReason
  1724. ];
  1725. } catch (\Exception $e) {
  1726. $retryable = true;
  1727. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1728. $status = $e->getResponse()->getStatusCode();
  1729. $retryable = $status >= 500 || $status == 429;
  1730. }
  1731. if (!$retryable || $attempt >= $maxRetries) {
  1732. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1733. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1734. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1735. }
  1736. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1737. 'retry' => $attempt + 1,
  1738. 'max_retries' => $maxRetries,
  1739. 'error' => $e->getMessage()
  1740. ]);
  1741. sleep($interval);
  1742. $attempt++;
  1743. }
  1744. }
  1745. }
  1746. /**
  1747. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1748. */
  1749. private function geminiStreamResponse($requestData, $model) {
  1750. $apiKey = $this->getGeminiApiKey($model);
  1751. if (empty($apiKey)) {
  1752. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1753. }
  1754. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1755. if (isset($requestData['messages'])) {
  1756. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1757. }
  1758. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1759. . '/models/' . $model . ':generateContent?alt=sse';
  1760. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1761. $headers = [
  1762. 'Authorization' => 'Bearer ' . $apiKey,
  1763. 'Content-Type' => 'application/json'
  1764. ];
  1765. try {
  1766. $response = $client->post($url, [
  1767. 'json' => $requestData,
  1768. 'headers' => $headers,
  1769. 'stream' => true
  1770. ]);
  1771. $body = $response->getBody();
  1772. $fullContent = '';
  1773. $fullReasoningContent = '';
  1774. $usage = [];
  1775. $buffer = '';
  1776. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1777. while (!$body->eof()) {
  1778. $chunk = $body->read(1024);
  1779. $buffer .= $chunk;
  1780. $lines = explode("\n", $buffer);
  1781. $buffer = array_pop($lines);
  1782. foreach ($lines as $line) {
  1783. $line = trim($line);
  1784. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1785. continue;
  1786. }
  1787. $data = substr($line, 6);
  1788. if ($data === '[DONE]') {
  1789. break 2;
  1790. }
  1791. try {
  1792. $json = json_decode($data, true);
  1793. if (json_last_error() !== JSON_ERROR_NONE) {
  1794. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1795. continue;
  1796. }
  1797. // 思考内容(thoughts)
  1798. $thoughts = $this->extractGeminiThoughts($json);
  1799. if ($thoughts !== '') {
  1800. $fullReasoningContent .= $thoughts;
  1801. yield [
  1802. 'type' => 'reasoning',
  1803. 'content' => $thoughts,
  1804. 'full_reasoning' => $fullReasoningContent
  1805. ];
  1806. }
  1807. // 回答内容
  1808. $partText = $this->extractGeminiContent($json);
  1809. if ($partText !== '') {
  1810. $fullContent .= $partText;
  1811. yield [
  1812. 'type' => 'content',
  1813. 'content' => $partText,
  1814. ];
  1815. }
  1816. // 使用统计
  1817. if (isset($json['usageMetadata'])) {
  1818. $usage = $json['usageMetadata'];
  1819. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1820. }
  1821. } catch (\Exception $e) {
  1822. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1823. continue;
  1824. }
  1825. }
  1826. }
  1827. dLog('deepseek')->info('Gemini流式读取完成', [
  1828. 'content_length' => strlen($fullContent),
  1829. 'reasoning_length' => strlen($fullReasoningContent)
  1830. ]);
  1831. yield [
  1832. 'type' => 'done',
  1833. 'full_content' => $fullContent,
  1834. 'full_reasoning' => $fullReasoningContent,
  1835. 'usage' => $usage
  1836. ];
  1837. } catch (\Exception $e) {
  1838. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1839. yield [
  1840. 'type' => 'error',
  1841. 'msg' => $e->getMessage(),
  1842. 'code' => $e->getCode()
  1843. ];
  1844. }
  1845. }
  1846. /**
  1847. * 从 Gemini 响应中提取回答文本
  1848. */
  1849. private function extractGeminiContent($responseArr) {
  1850. $text = '';
  1851. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1852. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1853. if (isset($part['text'])) {
  1854. $text .= $part['text'];
  1855. }
  1856. }
  1857. }
  1858. return $text;
  1859. }
  1860. /**
  1861. * 从 Gemini 响应中提取思考内容
  1862. */
  1863. private function extractGeminiReasoningContent($responseArr) {
  1864. $reasoning = '';
  1865. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1866. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1867. if (isset($thought['text'])) {
  1868. $reasoning .= $thought['text'];
  1869. }
  1870. }
  1871. }
  1872. return $reasoning;
  1873. }
  1874. /**
  1875. * 从 Gemini 流式响应中提取本次增量思考内容
  1876. */
  1877. private function extractGeminiThoughts($responseArr) {
  1878. $thoughts = '';
  1879. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1880. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1881. if (isset($thought['text'])) {
  1882. $thoughts .= $thought['text'];
  1883. }
  1884. }
  1885. }
  1886. return $thoughts;
  1887. }
  1888. /**
  1889. * 提取消息数组中的纯文本
  1890. */
  1891. private function extractGeminiTextFromParts($parts) {
  1892. $text = '';
  1893. if (is_array($parts)) {
  1894. foreach ($parts as $part) {
  1895. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1896. $text .= (string)getProp($part, 'text', '');
  1897. }
  1898. }
  1899. }
  1900. return $text;
  1901. }
  1902. /**
  1903. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1904. *
  1905. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1906. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1907. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1908. *
  1909. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1910. * @return array|null ['mime_type' => string, 'data' => string]
  1911. */
  1912. private function processMediaToInlineData($media) {
  1913. if (empty($media)) {
  1914. return null;
  1915. }
  1916. $localPath = null;
  1917. $isTempFile = false;
  1918. try {
  1919. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1920. if (is_string($media) && strpos($media, 'data:') === 0) {
  1921. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1922. return [
  1923. 'mime_type' => $matches[1],
  1924. 'data' => $matches[2]
  1925. ];
  1926. }
  1927. return null;
  1928. }
  1929. // 2. 获取本地文件路径
  1930. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1931. $localPath = $this->downloadMediaToTemp($media);
  1932. $isTempFile = true;
  1933. } elseif (is_string($media)) {
  1934. $localPath = $media;
  1935. } else {
  1936. // Laravel UploadedFile 对象
  1937. $localPath = $media->getRealPath();
  1938. }
  1939. if (!$localPath || !file_exists($localPath)) {
  1940. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1941. return null;
  1942. }
  1943. $fileSize = filesize($localPath);
  1944. $maxBytes = $this->geminiMediaMaxBytes();
  1945. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1946. $mimeType = $this->detectMediaMime($localPath);
  1947. $isVideo = strpos($mimeType, 'video/') === 0;
  1948. $needCompress = $fileSize > $maxBytes;
  1949. $duration = 0;
  1950. if ($isVideo) {
  1951. $duration = $this->getMediaDuration($localPath);
  1952. if ($duration > 300) {
  1953. $needCompress = true;
  1954. }
  1955. }
  1956. $finalPath = $localPath;
  1957. $compressedPath = null;
  1958. if ($needCompress && $this->ffmpegAvailable()) {
  1959. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1960. if ($compressed && file_exists($compressed)) {
  1961. $compressedPath = $compressed;
  1962. if (filesize($compressed) < $fileSize || $isVideo) {
  1963. $finalPath = $compressed;
  1964. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1965. } else {
  1966. @unlink($compressed);
  1967. $compressedPath = null;
  1968. }
  1969. }
  1970. }
  1971. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1972. $finalSize = filesize($finalPath);
  1973. if ($finalSize > $maxBytes) {
  1974. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1975. 'path' => $localPath,
  1976. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1977. 'limit_mb' => 14
  1978. ]);
  1979. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1980. }
  1981. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1982. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1983. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1984. }
  1985. $data = base64_encode(file_get_contents($finalPath));
  1986. return [
  1987. 'mime_type' => $mimeType,
  1988. 'data' => $data
  1989. ];
  1990. } catch (\App\Exceptions\ApiException $e) {
  1991. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1992. throw $e;
  1993. } catch (\Exception $e) {
  1994. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1995. return null;
  1996. } finally {
  1997. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1998. @unlink($compressedPath);
  1999. }
  2000. if ($isTempFile && $localPath && file_exists($localPath)) {
  2001. @unlink($localPath);
  2002. }
  2003. }
  2004. }
  2005. /**
  2006. * 下载远程多媒体到临时目录
  2007. *
  2008. * @return string|null 本地临时文件路径
  2009. */
  2010. private function downloadMediaToTemp($url) {
  2011. try {
  2012. $tempDir = storage_path('app/temp/gemini');
  2013. if (!is_dir($tempDir)) {
  2014. mkdir($tempDir, 0775, true);
  2015. }
  2016. $extension = 'tmp';
  2017. $pathInfo = parse_url($url, PHP_URL_PATH);
  2018. if ($pathInfo) {
  2019. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2020. if ($ext && strlen($ext) <= 10) {
  2021. $extension = strtolower($ext);
  2022. }
  2023. }
  2024. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2025. $client = new Client(['timeout' => 300, 'verify' => false]);
  2026. $response = $client->get($url, ['sink' => $tmpFile]);
  2027. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2028. @unlink($tmpFile);
  2029. return null;
  2030. }
  2031. return $tmpFile;
  2032. } catch (\Exception $e) {
  2033. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2034. return null;
  2035. }
  2036. }
  2037. /**
  2038. * 检测多媒体文件 MIME 类型
  2039. */
  2040. private function detectMediaMime($filePath) {
  2041. $imageInfo = @getimagesize($filePath);
  2042. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2043. return $imageInfo['mime'];
  2044. }
  2045. // 视频按扩展名粗略判断
  2046. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2047. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2048. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2049. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2050. if (isset($videoExts[$ext])) {
  2051. return $videoExts[$ext];
  2052. }
  2053. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2054. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2055. if (isset($imageExts[$ext])) {
  2056. return $imageExts[$ext];
  2057. }
  2058. return 'application/octet-stream';
  2059. }
  2060. /**
  2061. * 获取多媒体时长(秒),非视频或失败返回 0
  2062. */
  2063. private function getMediaDuration($filePath) {
  2064. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2065. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2066. $output = trim((string)shell_exec($cmd));
  2067. $duration = (float)$output;
  2068. return $duration > 0 ? $duration : 0;
  2069. }
  2070. /**
  2071. * 检查 ffmpeg 是否可用
  2072. */
  2073. private function ffmpegAvailable() {
  2074. static $available = null;
  2075. if ($available !== null) {
  2076. return $available;
  2077. }
  2078. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2079. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2080. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2081. $available = false;
  2082. return $available;
  2083. }
  2084. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2085. $output = shell_exec($cmd);
  2086. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2087. return $available;
  2088. }
  2089. /**
  2090. * 使用 ffmpeg 压缩多媒体文件
  2091. *
  2092. * @param string $inputFile 输入文件路径
  2093. * @param bool $isVideo 是否为视频
  2094. * @param float $duration 视频时长(秒),非视频传 0
  2095. * @return string|null 压缩后的文件路径,失败返回 null
  2096. */
  2097. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2098. try {
  2099. $tempDir = storage_path('app/temp/gemini');
  2100. if (!is_dir($tempDir)) {
  2101. mkdir($tempDir, 0775, true);
  2102. }
  2103. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2104. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2105. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2106. if ($isVideo) {
  2107. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2108. $speedFactor = 1.0;
  2109. if ($duration > 300) {
  2110. $speedFactor = $duration / 300;
  2111. }
  2112. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2113. $finalDuration = $duration / max(1.0, $speedFactor);
  2114. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2115. $targetBitrate = max(300, min(6000, $targetBitrate));
  2116. $filters = [];
  2117. $filters[] = 'scale=min(1280,iw):-2';
  2118. $filters[] = 'fps=24';
  2119. if ($speedFactor > 1.0) {
  2120. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2121. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2122. $fullCount = (int)ceil($speedFactor / 2.0);
  2123. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2124. if ($lastTempo < 0.5) {
  2125. $fullCount++;
  2126. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2127. }
  2128. for ($i = 0; $i < $fullCount; $i++) {
  2129. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2130. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2131. }
  2132. }
  2133. $filterStr = implode(',', $filters);
  2134. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2135. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2136. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2137. } else {
  2138. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2139. $imageInfo = @getimagesize($inputFile);
  2140. $scaleW = 2048;
  2141. $scaleH = 2048;
  2142. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2143. if ($imageInfo[0] >= $imageInfo[1]) {
  2144. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2145. $scaleW = 2048;
  2146. } else {
  2147. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2148. $scaleH = 2048;
  2149. }
  2150. }
  2151. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2152. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2153. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2154. }
  2155. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2156. $output = shell_exec($cmd);
  2157. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2158. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2159. 'input' => $inputFile,
  2160. 'output' => $output
  2161. ]);
  2162. @unlink($outputFile);
  2163. return null;
  2164. }
  2165. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2166. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2167. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2168. ]);
  2169. return $outputFile;
  2170. } catch (\Exception $e) {
  2171. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2172. return null;
  2173. }
  2174. }
  2175. /**
  2176. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2177. *
  2178. * @param array $data
  2179. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2180. */
  2181. public function getScriptGenerateTasks($data) {
  2182. $uid = Site::getUid();
  2183. return DB::table('mp_script_generate_tasks as t')
  2184. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2185. ->where('t.uid', $uid)
  2186. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2187. ->orderByDesc('t.id')
  2188. ->paginate(15);
  2189. }
  2190. public function saveScriptChatHistory($data) {
  2191. $uid = Site::getUid();
  2192. $rid = getProp($data, 'rid');
  2193. $script_id = getProp($data, 'script_id');
  2194. $sequence = getProp($data, 'sequence', 0);
  2195. $content = getProp($data, 'content');
  2196. if (!$rid) {
  2197. Utils::throwError('20003:请选择对话记录ID');
  2198. }
  2199. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2200. if (!$record) {
  2201. Utils::throwError('20003:对话记录不存在');
  2202. }
  2203. if (!$script_id) {
  2204. Utils::throwError('20003:请选择剧本');
  2205. }
  2206. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2207. if (!$script) {
  2208. Utils::throwError('20003:剧本不存在');
  2209. }
  2210. // 批量插入数据
  2211. return DB::table('mp_script_records')->where('id', $rid)->update([
  2212. 'content' => $content,
  2213. 'updated_at' => date('Y-m-d H:i:s')
  2214. ]);
  2215. }
  2216. /**
  2217. * 获取剧本的历史对话记录
  2218. *
  2219. * @param array $data 请求参数
  2220. * @return array 返回历史记录数组
  2221. */
  2222. public function getScriptChatHistory($data) {
  2223. $uid = Site::getUid();
  2224. $script_id = getProp($data, 'script_id');
  2225. $rid = getProp($data, 'rid');
  2226. $sequence = getProp($data, 'sequence', null);
  2227. if (!$script_id) {
  2228. Utils::throwError('20003:请提供剧本ID');
  2229. }
  2230. // 验证剧本是否存在
  2231. $script = DB::table('mp_scripts')
  2232. ->where('id', $script_id)
  2233. ->where('is_deleted', 0)
  2234. ->first();
  2235. if (!$script) {
  2236. Utils::throwError('20003:剧本不存在');
  2237. }
  2238. // 构建查询
  2239. $query = DB::table('mp_script_records')
  2240. ->where('script_id', $script_id);
  2241. // ->where('uid', $uid);
  2242. // 如果提供了 sequence,则过滤指定剧集
  2243. if ($sequence !== null) {
  2244. $query->where('sequence', $sequence);
  2245. }
  2246. // 记录ID筛选
  2247. if ($rid) {
  2248. $query->where('id', $rid);
  2249. }
  2250. // 查询记录并按 id 正序排序
  2251. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2252. ->orderBy('created_at', 'asc')
  2253. ->orderBy('id', 'asc')
  2254. ->get()
  2255. ->map(function ($record) {
  2256. return [
  2257. 'rid' => $record->id,
  2258. 'script_id' => $record->script_id,
  2259. 'sequence' => $record->sequence,
  2260. 'role' => $record->role,
  2261. 'content' => $record->content,
  2262. 'products' => $record->products ? json_decode($record->products) : [],
  2263. 'created_at' => $record->created_at,
  2264. ];
  2265. })
  2266. ->toArray();
  2267. return $records;
  2268. }
  2269. /**
  2270. * 处理图片转换为base64
  2271. *
  2272. * @param mixed $image 图片文件对象或文件路径
  2273. * @return string|null base64编码的图片数据
  2274. */
  2275. private function processImageToBase64($image) {
  2276. try {
  2277. // 获取文件路径
  2278. if (is_string($image)) {
  2279. $filePath = $image;
  2280. } else {
  2281. // Laravel UploadedFile 对象
  2282. $filePath = $image->getRealPath();
  2283. }
  2284. if (!file_exists($filePath)) {
  2285. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2286. return null;
  2287. }
  2288. // 验证是否为图片文件
  2289. $imageInfo = @getimagesize($filePath);
  2290. if ($imageInfo === false) {
  2291. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2292. return null;
  2293. }
  2294. // 读取图片并转换为base64
  2295. $imageData = file_get_contents($filePath);
  2296. $base64Image = base64_encode($imageData);
  2297. dLog('deepseek')->info('图片转换成功', [
  2298. 'size' => strlen($imageData),
  2299. 'type' => $imageInfo['mime']
  2300. ]);
  2301. return $base64Image;
  2302. } catch (\Exception $e) {
  2303. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2304. return null;
  2305. }
  2306. }
  2307. private function getArtStylePromptMappings($art_style='')
  2308. {
  2309. $arr = [
  2310. '唯美真人风格' => [
  2311. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2312. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2313. ],
  2314. '真人古风风格' => [
  2315. 'aliases' => ['真人古风风格', '真人古风'],
  2316. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2317. ],
  2318. '日系动漫风格' => [
  2319. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2320. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2321. ],
  2322. '国漫风格' => [
  2323. 'aliases' => ['国漫风格', '国漫'],
  2324. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2325. ],
  2326. 'Q版卡通风格' => [
  2327. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2328. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2329. ],
  2330. '简约扁平风格' => [
  2331. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2332. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2333. ],
  2334. '武侠风格' => [
  2335. 'aliases' => ['武侠风格', '武侠'],
  2336. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2337. ],
  2338. '古风仙侠风格' => [
  2339. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2340. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2341. ],
  2342. '新中式水墨风格' => [
  2343. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2344. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2345. ],
  2346. '写实插画风格' => [
  2347. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2348. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2349. ],
  2350. '3D卡通风格' => [
  2351. 'aliases' => ['3D卡通风格', '3D卡通'],
  2352. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2353. ],
  2354. '条漫风格' => [
  2355. 'aliases' => ['条漫风格', '条漫'],
  2356. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2357. ],
  2358. '赛博朋克风格' => [
  2359. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2360. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2361. ],
  2362. '暗黑悬疑风格' => [
  2363. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2364. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2365. ],
  2366. '治愈清新风格' => [
  2367. 'aliases' => ['治愈清新风格', '治愈清新'],
  2368. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2369. ],
  2370. '3D真人风格' => [
  2371. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2372. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2373. ],
  2374. ];
  2375. if($art_style) {
  2376. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2377. }
  2378. return $arr;
  2379. $arr = [
  2380. '唯美真人风格' => [
  2381. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2382. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2383. 2. 色彩色调
  2384. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2385. 3. 画质精度
  2386. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2387. 4. 画面观感
  2388. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2389. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2390. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2391. ],
  2392. '真人古风风格' => [
  2393. 'aliases' => ['真人古风风格', '真人古风'],
  2394. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2395. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2396. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2397. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2398. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2399. ],
  2400. '日系动漫风格' => [
  2401. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2402. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2403. 正向提示词(中文)
  2404. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2405. 必须遵守规则
  2406. • 全程保持日系动漫风格,不混入其他画风
  2407. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2408. • 画面适配所选画面比例,构图居中,主体突出
  2409. • 线条干净、色彩统一,不杂乱、不突兀
  2410. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2411. ],
  2412. '国漫风格' => [
  2413. 'aliases' => ['国漫风格', '国漫'],
  2414. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2415. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2416. 必须遵守规则
  2417. • 严格保持国漫画风,不串风格、不混画风
  2418. • 角色形象统一,不随意改变五官、身材、服饰
  2419. • 画面构图稳定,适合漫剧叙事展示
  2420. • 色调统一,不出现脏色、杂色
  2421. 禁止/避免词汇
  2422. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2423. ],
  2424. 'Q版卡通风格' => [
  2425. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2426. 'prompt' => "风格说明
  2427. 头大身小,造型可爱圆润,简约干净
  2428. 正向提示词(中文)
  2429. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2430. 必须遵守规则
  2431. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2432. • 角色造型统一,表情可爱,不诡异
  2433. • 画面简洁清爽,无多余复杂元素
  2434. • 色彩明亮柔和,不刺眼
  2435. 禁止/避免词汇
  2436. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2437. ],
  2438. '简约扁平风格' => [
  2439. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2440. 'prompt' => "风格说明
  2441. 色块简洁、无复杂渐变,现代极简风
  2442. 正向提示词(中文)
  2443. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2444. 必须遵守规则
  2445. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2446. • 构图简洁,主体突出,无多余装饰
  2447. • 色彩统一、干净,不杂乱
  2448. 禁止/避免词汇
  2449. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2450. ],
  2451. '武侠风格' => [
  2452. 'aliases' => ['武侠风格', '武侠'],
  2453. 'prompt' => "风格说明
  2454. 江湖气息,线条硬朗,动作感强
  2455. 正向提示词(中文)
  2456. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2457. 必须遵守规则
  2458. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2459. • 角色形象、服饰、身材比例统一
  2460. • 画面动作自然,不扭曲、不畸形
  2461. 禁止/避免词汇
  2462. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2463. ],
  2464. '古风仙侠风格' => [
  2465. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2466. 'prompt' => "风格说明
  2467. 飘逸汉服、云雾仙气、唯美空灵
  2468. 正向提示词(中文)
  2469. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2470. 必须遵守规则
  2471. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2472. • 角色服饰、发型、形象前后一致
  2473. • 场景仙气飘逸,色调清雅统一
  2474. • 画面唯美柔和,不阴暗、不诡异
  2475. 禁止/避免词汇
  2476. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2477. ],
  2478. '新中式水墨风格' => [
  2479. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2480. 'prompt' => "风格说明
  2481. 淡墨渲染,毛笔笔触,留白意境
  2482. 正向提示词(中文)
  2483. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2484. 必须遵守规则
  2485. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2486. • 色调淡雅统一,不浓艳杂乱
  2487. • 画面干净有意境,不堆砌元素
  2488. 禁止/避免词汇
  2489. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2490. ],
  2491. '写实插画风格' => [
  2492. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2493. 'prompt' => "风格说明
  2494. 接近真人比例,光影真实,质感细腻
  2495. 正向提示词(中文)
  2496. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2497. 必须遵守规则
  2498. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2499. • 角色五官、身材、服饰高度统一
  2500. • 画面清晰、光影自然、不扭曲
  2501. 禁止/避免词汇
  2502. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2503. ],
  2504. '3D卡通风格' => [
  2505. 'aliases' => ['3D卡通风格', '3D卡通'],
  2506. 'prompt' => "风格说明
  2507. 3D建模质感,柔和渲染,圆润可爱
  2508. 正向提示词(中文)
  2509. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2510. 必须遵守规则
  2511. • 保持3D卡通统一质感,不出现2D杂乱线条
  2512. • 角色模型、比例、形象前后一致
  2513. • 画面干净,不模糊、不穿模
  2514. 禁止/避免词汇
  2515. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2516. ],
  2517. '条漫风格' => [
  2518. 'aliases' => ['条漫风格', '条漫'],
  2519. 'prompt' => "风格说明
  2520. 纵向分镜,上下滑动阅读,轻量化
  2521. 正向提示词(中文)
  2522. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2523. 必须遵守规则
  2524. • 保持条漫纵向阅读逻辑,构图简洁
  2525. • 画风统一,不混写实、3D、水墨
  2526. • 画面干净,不杂乱
  2527. 禁止/避免词汇
  2528. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2529. ],
  2530. '赛博朋克风格' => [
  2531. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2532. 'prompt' => "风格说明
  2533. 霓虹灯光、未来都市、暗色调、科技机械
  2534. 正向提示词(中文)
  2535. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2536. 必须遵守规则
  2537. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2538. • 色调以暗调+霓虹为主,色彩统一
  2539. • 画面科技感强,不杂乱
  2540. 禁止/避免词汇
  2541. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2542. ],
  2543. '暗黑悬疑风格' => [
  2544. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2545. 'prompt' => "风格说明
  2546. 低饱和、冷色调、阴影重、神秘压抑
  2547. 正向提示词(中文)
  2548. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2549. 必须遵守规则
  2550. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2551. • 画面氛围压抑神秘,但不低俗、不血腥
  2552. • 角色形象统一,不崩坏
  2553. 禁止/避免词汇
  2554. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2555. ],
  2556. '治愈清新风格' => [
  2557. 'aliases' => ['治愈清新风格', '治愈清新'],
  2558. 'prompt' => "风格说明
  2559. 马卡龙色系、柔光、温暖干净
  2560. 正向提示词(中文)
  2561. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2562. 必须遵守规则
  2563. • 保持治愈清新统一色调,不阴暗、不诡异
  2564. • 画面柔和干净,无杂乱元素
  2565. • 角色形象柔和可爱,不狰狞
  2566. 禁止/避免词汇
  2567. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2568. ],
  2569. ];
  2570. return $arr;
  2571. }
  2572. public function getArtStylePromptByInput($inputArtStyle): string
  2573. {
  2574. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2575. if ($normalizedInput === '') {
  2576. return '';
  2577. }
  2578. return $this->getArtStylePromptMappings($normalizedInput);
  2579. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2580. // foreach ($mapping['aliases'] as $alias) {
  2581. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2582. // if ($normalizedAlias === '') {
  2583. // continue;
  2584. // }
  2585. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2586. // return $mapping['prompt'];
  2587. // }
  2588. // }
  2589. // }
  2590. return '';
  2591. }
  2592. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2593. $stylePrefixes = [
  2594. '唯美真人风格' => [
  2595. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2596. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2597. ],
  2598. '真人古风风格' => [
  2599. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2600. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2601. ],
  2602. '日系动漫风格' => [
  2603. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2604. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2605. ],
  2606. '国漫风格' => [
  2607. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2608. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2609. ],
  2610. 'Q版卡通风格' => [
  2611. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2612. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2613. ],
  2614. '简约扁平风格' => [
  2615. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2616. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2617. ],
  2618. '武侠风格' => [
  2619. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2620. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2621. ],
  2622. '古风仙侠风格' => [
  2623. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2624. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2625. ],
  2626. '新中式水墨风格' => [
  2627. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2628. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2629. ],
  2630. '写实插画风格' => [
  2631. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2632. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2633. ],
  2634. '3D卡通风格' => [
  2635. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2636. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2637. ],
  2638. '条漫风格' => [
  2639. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2640. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2641. ],
  2642. '赛博朋克风格' => [
  2643. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2644. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2645. ],
  2646. '暗黑悬疑风格' => [
  2647. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2648. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2649. ],
  2650. '治愈清新风格' => [
  2651. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2652. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2653. ]
  2654. ];
  2655. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2656. }
  2657. private function normalizeArtStyleInput($value): string
  2658. {
  2659. $value = trim((string)$value);
  2660. if ($value === '') {
  2661. return '';
  2662. }
  2663. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2664. return mb_strtolower($value, 'UTF-8');
  2665. }
  2666. private function replaceArtStyleSection(string $content, string $artStyle): string
  2667. {
  2668. if ($content === '' || $artStyle === '') {
  2669. return $content;
  2670. }
  2671. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2672. if (!preg_match($pattern, $content)) {
  2673. return $content;
  2674. }
  2675. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2676. }
  2677. /**
  2678. * DeepSeek流式输出处理方法
  2679. *
  2680. * @param array $post_data DeepSeek API请求参数
  2681. * @return \Generator 返回生成器,用于流式输出
  2682. */
  2683. private function unwrapJsonWrappedContent($content) {
  2684. $trimmed = ltrim((string)$content);
  2685. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2686. return $content;
  2687. }
  2688. $decoded = json_decode($trimmed, true);
  2689. if (!is_array($decoded)) {
  2690. return $content;
  2691. }
  2692. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2693. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2694. return $decoded[$key];
  2695. }
  2696. }
  2697. return $content;
  2698. }
  2699. private function deepSeekStreamResponse($post_data) {
  2700. // 设置最大输出tokens
  2701. $post_data['max_tokens'] = 300000;
  2702. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2703. $post_data['stream_options'] = ['include_usage' => true];
  2704. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2705. $response = $client->post($this->url, [
  2706. 'json' => $post_data,
  2707. 'headers' => $this->headers,
  2708. 'stream' => true // 启用流式响应
  2709. ]);
  2710. $body = $response->getBody();
  2711. $fullContent = '';
  2712. $fullReasoningContent = '';
  2713. $usage = [];
  2714. $buffer = '';
  2715. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2716. // 逐行读取流式响应
  2717. while (!$body->eof()) {
  2718. $chunk = $body->read(1024); // 每次读取 1KB
  2719. $buffer .= $chunk;
  2720. // 按行分割
  2721. $lines = explode("\n", $buffer);
  2722. // 保留最后一个不完整的行
  2723. $buffer = array_pop($lines);
  2724. foreach ($lines as $line) {
  2725. $line = trim($line);
  2726. // 跳过空行
  2727. if (empty($line)) {
  2728. continue;
  2729. }
  2730. // 检查是否是 SSE 数据行
  2731. if (strpos($line, 'data: ') !== 0) {
  2732. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2733. continue;
  2734. }
  2735. $data = substr($line, 6); // 移除 "data: " 前缀
  2736. if ($data === '[DONE]') {
  2737. dLog('deepseek')->info('收到结束标记');
  2738. break 2; // 跳出两层循环
  2739. }
  2740. try {
  2741. $json = json_decode($data, true);
  2742. if (json_last_error() !== JSON_ERROR_NONE) {
  2743. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2744. continue;
  2745. }
  2746. if (isset($json['choices'][0]['delta'])) {
  2747. $delta = $json['choices'][0]['delta'];
  2748. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2749. if (isset($delta['reasoning_content'])) {
  2750. $fullReasoningContent .= $delta['reasoning_content'];
  2751. yield [
  2752. 'type' => 'reasoning',
  2753. 'content' => $delta['reasoning_content'],
  2754. 'full_reasoning' => $fullReasoningContent
  2755. ];
  2756. }
  2757. // 处理最终回答内容
  2758. if (isset($delta['content'])) {
  2759. $fullContent .= $delta['content'];
  2760. yield [
  2761. 'type' => 'content',
  2762. 'content' => $delta['content'],
  2763. ];
  2764. }
  2765. }
  2766. // 获取使用统计信息
  2767. if (isset($json['usage'])) {
  2768. $usage = $json['usage'];
  2769. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2770. }
  2771. } catch (\Exception $e) {
  2772. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2773. continue;
  2774. }
  2775. }
  2776. }
  2777. dLog('deepseek')->info('流式读取完成', [
  2778. 'content_length' => strlen($fullContent),
  2779. 'reasoning_length' => strlen($fullReasoningContent)
  2780. ]);
  2781. yield [
  2782. 'type' => 'done',
  2783. 'full_content' => $fullContent,
  2784. 'full_reasoning' => $fullReasoningContent,
  2785. 'usage' => $usage
  2786. ];
  2787. }
  2788. /**
  2789. * GPT 重试次数(env 可配置,默认 5 次)
  2790. */
  2791. private function gptRetryTimes()
  2792. {
  2793. return (int)env('GPT_RETRY_TIMES', 5);
  2794. }
  2795. /**
  2796. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2797. */
  2798. private function gptRetryInterval()
  2799. {
  2800. return (int)env('GPT_RETRY_INTERVAL', 10);
  2801. }
  2802. /**
  2803. * 判断 GPT 请求异常是否可重试
  2804. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2805. */
  2806. private function isGptRetryableException(\Exception $e)
  2807. {
  2808. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2809. return false;
  2810. }
  2811. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2812. $status = $e->getResponse()->getStatusCode();
  2813. return $status >= 500 || $status == 429;
  2814. }
  2815. return true;
  2816. }
  2817. /**
  2818. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2819. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2820. */
  2821. private function checkGptServiceAvailable($apiKey = null)
  2822. {
  2823. if ($apiKey === null) {
  2824. $apiKey = env('GPT_54_API_KEY');
  2825. }
  2826. if (empty($apiKey)) {
  2827. return false;
  2828. }
  2829. try {
  2830. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2831. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2832. 'headers' => [
  2833. 'Authorization' => 'Bearer ' . $apiKey,
  2834. 'Content-Type' => 'application/json'
  2835. ]
  2836. ]);
  2837. $status = $response->getStatusCode();
  2838. return $status < 500 && $status != 429;
  2839. } catch (\Exception $e) {
  2840. return false;
  2841. }
  2842. }
  2843. /**
  2844. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2845. * 全部失败抛出友好错误
  2846. */
  2847. private function ensureGptServiceAvailable($apiKey = null)
  2848. {
  2849. $maxRetries = $this->gptRetryTimes();
  2850. $interval = $this->gptRetryInterval();
  2851. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2852. if ($this->checkGptServiceAvailable($apiKey)) {
  2853. return;
  2854. }
  2855. if ($attempt < $maxRetries) {
  2856. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2857. 'retry' => $attempt + 1,
  2858. 'max_retries' => $maxRetries
  2859. ]);
  2860. sleep($interval);
  2861. }
  2862. }
  2863. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2864. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2865. 'max_retries' => $maxRetries,
  2866. 'interval' => $interval
  2867. ]);
  2868. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2869. }
  2870. /**
  2871. * GPT 流式输出处理方法
  2872. *
  2873. * @param array $post_data GPT API请求参数
  2874. * @return \Generator 返回生成器,用于流式输出
  2875. */
  2876. private function gpt54StreamResponse($post_data) {
  2877. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  2878. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  2879. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  2880. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  2881. $usedLunaFallback = false;
  2882. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  2883. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  2884. if (empty($apiKey)) {
  2885. Utils::throwError('20003:GPT API Key未配置');
  2886. }
  2887. // 先探活,服务不可用时自动重试
  2888. $this->ensureGptServiceAvailable($apiKey);
  2889. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  2890. // 移除 thinking 参数,GPT-5.4 不支持
  2891. if (isset($post_data['thinking'])) {
  2892. unset($post_data['thinking']);
  2893. }
  2894. if (isset($post_data['reasoning_effort'])) {
  2895. unset($post_data['reasoning_effort']);
  2896. }
  2897. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  2898. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  2899. $post_data['max_completion_tokens'] = 100000;
  2900. $post_data['max_tokens'] = 100000;
  2901. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2902. $post_data['stream_options'] = ['include_usage' => true];
  2903. $maxRetries = $this->gptRetryTimes();
  2904. $interval = $this->gptRetryInterval();
  2905. $attempt = 0;
  2906. while (true) {
  2907. $fullContent = '';
  2908. $usage = [];
  2909. $buffer = '';
  2910. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  2911. $isJsonRequest = isset($post_data['response_format'])
  2912. && is_array($post_data['response_format'])
  2913. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  2914. $suspectJsonWrap = false;
  2915. $pendingContent = '';
  2916. $requestStartedAt = microtime(true);
  2917. $headers = [
  2918. 'Authorization' => 'Bearer ' . $apiKey,
  2919. 'Content-Type' => 'application/json',
  2920. 'Accept' => 'text/event-stream'
  2921. ];
  2922. try {
  2923. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2924. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2925. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2926. 'json' => $post_data,
  2927. 'headers' => $headers,
  2928. 'stream' => true // 启用流式响应
  2929. ]);
  2930. $body = $response->getBody();
  2931. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2932. // 逐行读取流式响应
  2933. while (!$body->eof()) {
  2934. // 长时间没有任何内容返回时,切换备用 Key 重试
  2935. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  2936. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  2937. }
  2938. $chunk = $body->read(1024); // 每次读取 1KB
  2939. $buffer .= $chunk;
  2940. // 按行分割
  2941. $lines = explode("\n", $buffer);
  2942. // 保留最后一个不完整的行
  2943. $buffer = array_pop($lines);
  2944. foreach ($lines as $line) {
  2945. $line = trim($line);
  2946. // 跳过空行
  2947. if (empty($line)) {
  2948. continue;
  2949. }
  2950. // 检查是否是 SSE 数据行
  2951. if (strpos($line, 'data: ') !== 0) {
  2952. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2953. continue;
  2954. }
  2955. $data = substr($line, 6); // 移除 "data: " 前缀
  2956. if ($data === '[DONE]') {
  2957. dLog('deepseek')->info('收到结束标记');
  2958. break 2; // 跳出 foreach 和流读取循环
  2959. }
  2960. try {
  2961. $json = json_decode($data, true);
  2962. if (json_last_error() !== JSON_ERROR_NONE) {
  2963. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2964. continue;
  2965. }
  2966. if (isset($json['choices'][0]['delta'])) {
  2967. $delta = $json['choices'][0]['delta'];
  2968. // 处理回答内容
  2969. if (isset($delta['content'])) {
  2970. $fullContent .= $delta['content'];
  2971. $trimmed = ltrim($fullContent);
  2972. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2973. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2974. $suspectJsonWrap = true;
  2975. }
  2976. if (!$suspectJsonWrap) {
  2977. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2978. $chunkSize = 256;
  2979. $chunkLength = mb_strlen($delta['content']);
  2980. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2981. yield [
  2982. 'type' => 'content',
  2983. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2984. ];
  2985. }
  2986. } else {
  2987. $pendingContent .= $delta['content'];
  2988. }
  2989. }
  2990. }
  2991. // 获取使用统计信息
  2992. if (isset($json['usage'])) {
  2993. $usage = $json['usage'];
  2994. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2995. }
  2996. } catch (\Exception $e) {
  2997. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2998. continue;
  2999. }
  3000. }
  3001. }
  3002. dLog('deepseek')->info('流式读取完成', [
  3003. 'content_length' => strlen($fullContent)
  3004. ]);
  3005. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3006. if ($suspectJsonWrap) {
  3007. $decoded = json_decode(trim($fullContent), true);
  3008. $unwrapped = null;
  3009. if (is_array($decoded)) {
  3010. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3011. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3012. $unwrapped = $decoded[$key];
  3013. break;
  3014. }
  3015. }
  3016. }
  3017. if ($unwrapped !== null) {
  3018. $fullContent = $unwrapped;
  3019. $chunkSize = 256;
  3020. $contentLength = mb_strlen($fullContent);
  3021. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3022. yield [
  3023. 'type' => 'content',
  3024. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3025. ];
  3026. }
  3027. } elseif ($pendingContent !== '') {
  3028. // 误判:补发暂缓内容,避免内容丢失
  3029. yield [
  3030. 'type' => 'content',
  3031. 'content' => $pendingContent,
  3032. ];
  3033. }
  3034. }
  3035. yield [
  3036. 'type' => 'done',
  3037. 'full_content' => $fullContent,
  3038. 'full_reasoning' => '',
  3039. 'usage' => $usage
  3040. ];
  3041. return;
  3042. } catch (\Exception $e) {
  3043. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3044. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3045. $usedLunaFallback = true;
  3046. $apiKey = $lunaApiKey;
  3047. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3048. continue;
  3049. }
  3050. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3051. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3052. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3053. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3054. throw $e;
  3055. }
  3056. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3057. 'retry' => $attempt + 1,
  3058. 'max_retries' => $maxRetries,
  3059. 'error' => $e->getMessage()
  3060. ]);
  3061. sleep($interval);
  3062. $attempt++;
  3063. }
  3064. }
  3065. }
  3066. // 与推理模型对话
  3067. public function chatWithReasoner($data) {
  3068. $content = getProp($data, 'content');
  3069. $model = getProp($data, 'model', 'r1');
  3070. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3071. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3072. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3073. if ($model == 'r1') {
  3074. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3075. $thinkingMode = 'disabled';
  3076. } else {
  3077. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3078. $thinkingMode = 'disabled';
  3079. }
  3080. // 获取可选情感(根据音色可支持情感选)
  3081. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3082. $emotion_list = [];
  3083. foreach ($timbre_emotion as $emotion) {
  3084. $tmp = explode(',', $emotion);
  3085. $emotion_list = array_merge($emotion_list, $tmp);
  3086. }
  3087. $emotion_list = array_unique($emotion_list);
  3088. $emotion_str = implode('、', $emotion_list);
  3089. // // 获取可选情感
  3090. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3091. // $emotion_str = implode('、', $emotion_list);
  3092. // 是否启用情感
  3093. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3094. if ($enable_emotion) {
  3095. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3096. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3097. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3098. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3099. }else {
  3100. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3101. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3102. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3103. }
  3104. $messages = [
  3105. [
  3106. 'role' => 'system',
  3107. 'content' => $sys_content
  3108. ],
  3109. [
  3110. 'role' => 'user',
  3111. 'content' => $content
  3112. ]
  3113. ];
  3114. $post_data = [
  3115. 'model' => $model,
  3116. 'messages' => $messages,
  3117. // 'max_tokens' => 8192,
  3118. 'temperature' => 1,
  3119. 'frequency_penalty' => 0,
  3120. 'presence_penalty' => 0,
  3121. 'thinking' => ['type' => $thinkingMode],
  3122. 'response_format' => [
  3123. 'type' => 'text'
  3124. ],
  3125. 'stream' => false
  3126. ];
  3127. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3128. // 根据模型类型选择调用方法
  3129. $fullContent = '';
  3130. $usage = [];
  3131. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3132. // DeepSeek 官方模型使用 DeepSeek API
  3133. $chatResult = $this->chatOnly($post_data);
  3134. } else if (in_array($model, $this->gpt_text_models)) {
  3135. // GPT-5.4 模型使用 TokenRouter API
  3136. $chatResult = $this->gpt54ChatOnly($post_data);
  3137. } else {
  3138. // 其他模型使用火山引擎API
  3139. $chatResult = $this->volcEngineChatCompletion($post_data);
  3140. }
  3141. if (is_array($chatResult)) {
  3142. $fullContent = $chatResult['fullContent'];
  3143. $usage = $chatResult['usage'];
  3144. }
  3145. // 处理获取到的剧本数据
  3146. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3147. $result = [
  3148. 'origin_content' => $fullContent,
  3149. 'roles' => getProp($script_content, 'roles'),
  3150. 'words' => getProp($script_content, 'words'),
  3151. ];
  3152. // 仅记录 token 使用明细(不扣积分)
  3153. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3154. 'model' => $model,
  3155. 'source' => 'chatWithReasoner',
  3156. ], $model);
  3157. return $result;
  3158. }
  3159. public function resetParagraphAudio($data) {
  3160. $bid = getProp($data, 'bid');
  3161. $cid = getProp($data, 'cid');
  3162. $version_id = getProp($data, 'version_id');
  3163. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3164. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3165. 'generate_status' => '待制作',
  3166. 'updated_at' => date('Y-m-d H:i:s')
  3167. ]);
  3168. }
  3169. public function saveParagraphAudio($data) {
  3170. $bid = getProp($data, 'bid');
  3171. $cid = getProp($data, 'cid');
  3172. $version_id = getProp($data, 'version_id');
  3173. $sequence = getProp($data, 'sequence');
  3174. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3175. // 获取所有情感
  3176. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3177. $emotion_list = array_flip($emotion_list);
  3178. // 获取音色支持情感
  3179. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3180. $timbre_emotion = explode(',', $timbre_emotion);
  3181. $emotion = getProp($data, 'emotion');
  3182. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3183. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3184. $list = [
  3185. 'bid' => $bid,
  3186. 'cid' => $cid,
  3187. 'version_id' => $version_id,
  3188. 'sequence' => $sequence,
  3189. 'role' => getProp($data, 'role'),
  3190. 'gender' => getProp($data, 'gender'),
  3191. 'text' => trim(getProp($data, 'text')),
  3192. 'emotion' => $emotion,
  3193. 'emotion_type' => $emotion_type,
  3194. 'voice_type' => getProp($data, 'voice_type'),
  3195. 'voice_name' => getProp($data, 'voice_name'),
  3196. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3197. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3198. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3199. 'pitch' => getProp($data, 'pitch', 0),
  3200. // 'paragraph_audio_url' => '',
  3201. 'generate_status' => '制作中',
  3202. 'error_msg' => '',
  3203. 'updated_at' => date('Y-m-d H:i:s')
  3204. ];
  3205. $continue = false;
  3206. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3207. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3208. $list['generate_status'] = '制作成功';
  3209. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3210. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3211. $continue = true;
  3212. }
  3213. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3214. if ($id) {
  3215. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3216. }else {
  3217. $list['created_at'] = date('Y-m-d H:i:s');
  3218. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3219. $boolen = $id ? true : false;
  3220. }
  3221. // 如果更新成功则加入查询队列
  3222. if ($boolen) {
  3223. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3224. Redis::sadd($redis_key, $id);
  3225. }
  3226. if ($boolen && !$continue) {
  3227. $boolen = false;
  3228. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3229. // 根据ID通过API通知合成音频
  3230. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3231. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3232. $response = $result->getBody()->getContents();
  3233. $response_arr = json_decode($response, true);
  3234. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3235. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3236. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3237. Utils::throwError('20003:通知火山生成段落音频失败');
  3238. }
  3239. $boolen = true;
  3240. }
  3241. return $boolen;
  3242. }
  3243. public function insertAudioEffect($data) {
  3244. $audio_id = getProp($data, 'audio_id');
  3245. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3246. $bid = getProp($chapter_audio, 'bid');
  3247. $version_id = getProp($chapter_audio, 'version_id');
  3248. $cid = getProp($chapter_audio, 'cid');
  3249. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3250. $audio_effect_json = getProp($data, 'audio_effect_json');
  3251. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3252. try {
  3253. DB::beginTransaction();
  3254. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3255. if (!$count) {
  3256. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3257. }else {
  3258. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3259. }
  3260. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3261. 'audio_effect_status' => '添加中',
  3262. 'audio_effect_json' => $audio_effect_json,
  3263. 'updated_at' => date('Y-m-d H:i:s')
  3264. ]);
  3265. if (!$boolen1) {
  3266. DB::rollBack();
  3267. Utils::throwError('20003:更新生成数据失败');
  3268. }
  3269. $id = DB::table('mp_audio_tasks')->insertGetId([
  3270. 'audio_id' => $audio_id,
  3271. 'generate_status' => '执行中',
  3272. 'generate_json' => json_encode([], 256),
  3273. 'bid' => $bid,
  3274. 'book_name' => getProp($chapter_audio, 'book_name'),
  3275. 'version_id' => $version_id,
  3276. 'version_name' => getProp($chapter_audio, 'version_name'),
  3277. 'cid' => $cid,
  3278. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3279. 'task_name' => $task_name,
  3280. 'created_at' => date('Y-m-d H:i:s'),
  3281. 'updated_at' => date('Y-m-d H:i:s')
  3282. ]);
  3283. if (!$id) {
  3284. DB::rollBack();
  3285. Utils::throwError('20003:创建任务失败');
  3286. }
  3287. }catch (\Exception $e) {
  3288. DB::rollBack();
  3289. Utils::throwError('20003:'.$e->getMessage());
  3290. }
  3291. DB::commit();
  3292. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3293. // 根据ID通过API通知合成音频
  3294. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3295. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3296. $response = $result->getBody()->getContents();
  3297. $response_arr = json_decode($response, true);
  3298. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3299. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3300. Log::info('通知火山插入音效失败: '.$error_msg);
  3301. Utils::throwError('20003:通知火山插入音效失败');
  3302. }
  3303. return true;
  3304. }
  3305. public function insertBgm($data) {
  3306. $audio_id = getProp($data, 'audio_id');
  3307. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3308. $bid = getProp($chapter_audio, 'bid');
  3309. $version_id = getProp($chapter_audio, 'version_id');
  3310. $cid = getProp($chapter_audio, 'cid');
  3311. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3312. $bgm_json = getProp($data, 'bgm_json');
  3313. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3314. if (!$bgm_json) {
  3315. $bgm_json = getProp($data, 'audio_effect_json');
  3316. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3317. }
  3318. try {
  3319. DB::beginTransaction();
  3320. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3321. if (!$count) {
  3322. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3323. }else {
  3324. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3325. }
  3326. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3327. 'bgm_status' => '添加中',
  3328. 'bgm_json' => $bgm_json,
  3329. 'updated_at' => date('Y-m-d H:i:s')
  3330. ]);
  3331. if (!$boolen1) {
  3332. DB::rollBack();
  3333. Utils::throwError('20003:更新生成数据失败');
  3334. }
  3335. $id = DB::table('mp_audio_tasks')->insertGetId([
  3336. 'audio_id' => $audio_id,
  3337. 'generate_status' => '执行中',
  3338. 'generate_json' => json_encode([], 256),
  3339. 'bid' => $bid,
  3340. 'book_name' => getProp($chapter_audio, 'book_name'),
  3341. 'version_id' => $version_id,
  3342. 'version_name' => getProp($chapter_audio, 'version_name'),
  3343. 'cid' => $cid,
  3344. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3345. 'task_name' => $task_name,
  3346. 'created_at' => date('Y-m-d H:i:s'),
  3347. 'updated_at' => date('Y-m-d H:i:s')
  3348. ]);
  3349. if (!$id) {
  3350. DB::rollBack();
  3351. Utils::throwError('20003:创建任务失败');
  3352. }
  3353. }catch (\Exception $e) {
  3354. DB::rollBack();
  3355. Utils::throwError('20003:'.$e->getMessage());
  3356. }
  3357. DB::commit();
  3358. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3359. // 根据ID通过API通知合成音频
  3360. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3361. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3362. $response = $result->getBody()->getContents();
  3363. $response_arr = json_decode($response, true);
  3364. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3365. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3366. Log::info('通知火山插入bgm失败: '.$error_msg);
  3367. Utils::throwError('20003:通知火山插入bgm失败');
  3368. }
  3369. return true;
  3370. }
  3371. public function getParagraphAudios($data) {
  3372. $bid = getProp($data, 'bid');
  3373. $cid = getProp($data, 'cid');
  3374. $version_id = getProp($data, 'version_id');
  3375. $sequence = getProp($data, 'sequence');
  3376. // 获取已生成的音频
  3377. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3378. if ($sequence) $query->where('sequence', $sequence);
  3379. $paragraph_audios = $query->orderBy('sequence')->get();
  3380. $result = [];
  3381. foreach($paragraph_audios as $item) {
  3382. $result[] = [
  3383. 'sequence' => getProp($item, 'sequence'),
  3384. 'role' => getProp($item, 'role'),
  3385. 'gender' => getProp($item, 'gender'),
  3386. 'text' => trim(getProp($item, 'text')),
  3387. 'emotion' => getProp($item, 'emotion'),
  3388. 'emotion_type' => getProp($item, 'emotion_type'),
  3389. 'voice_type' => getProp($item, 'voice_type'),
  3390. 'voice_name' => getProp($item, 'voice_name'),
  3391. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3392. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3393. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3394. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3395. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3396. ];
  3397. }
  3398. return $result;
  3399. }
  3400. // 新增合成任务
  3401. public function addGenerateTask($data) {
  3402. $bid = getProp($data, 'bid');
  3403. $cid = getProp($data, 'cid');
  3404. $version_id = getProp($data, 'version_id');
  3405. $generate_json = getProp($data, 'generate_json');
  3406. // 获取已生成的音频
  3407. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3408. $paragraph_list = [];
  3409. foreach($paragraph_audios as $item) {
  3410. $paragraph_list[getProp($item, 'sequence')] = [
  3411. 'role' => getProp($item, 'role'),
  3412. 'gender' => getProp($item, 'gender'),
  3413. 'text' => trim(getProp($item, 'text')),
  3414. 'emotion' => getProp($item, 'emotion'),
  3415. 'emotion_type' => getProp($item, 'emotion_type'),
  3416. 'voice_type' => getProp($item, 'voice_type'),
  3417. 'voice_name' => getProp($item, 'voice_name'),
  3418. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3419. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3420. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3421. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3422. ];
  3423. }
  3424. // 更新角色-音色信息
  3425. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3426. $existed_role_info = json_decode($existed_role_info, true);
  3427. if (!$existed_role_info) $existed_role_info = [];
  3428. // 获取情感信息
  3429. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3430. $emotion_list = array_flip($emotion_list);
  3431. // 获取音色对应情感组
  3432. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3433. $timbre_emotion_list = [];
  3434. foreach($timbre_emotions as $item) {
  3435. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3436. }
  3437. // 构造生成音频的json
  3438. $words = json_decode($generate_json, true);
  3439. // 最终合成前的参数组
  3440. $mp_chapter_paragraph_audios = [];
  3441. $sequence = 1;
  3442. $complete_paragraph_sequences = [];
  3443. foreach($words as &$word) {
  3444. if (!isset($word['text']) || !isset($word['emotion']) || !isset($word['voice_type']) || !isset($word['voice_name']) || !isset($word['speed_ratio']) || !isset($word['loudness_ratio']) || !isset($word['emotion_scale'])) Utils::throwError('20003:参数格式有误');
  3445. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3446. $role = getProp($word, 'role');
  3447. $word['gender'] = (int)$word['gender'];
  3448. // 判断音色对应情感是否支持,不支持则调整为中性
  3449. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3450. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3451. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3452. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3453. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3454. }else {
  3455. $word['emotion'] = '中性';
  3456. $word['emotion_type'] = 'neutral';
  3457. }
  3458. $existed_role_info[$role] = [
  3459. 'timbre_type' => $word['voice_type'],
  3460. 'timbre_name' => $word['voice_name'],
  3461. 'emotion' => $word['emotion'],
  3462. 'emotion_type' => $word['emotion_type'],
  3463. 'speed_ratio' => $word['speed_ratio'],
  3464. 'loudness_ratio'=> $word['loudness_ratio'],
  3465. 'emotion_scale' => $word['emotion_scale'],
  3466. 'pitch' => $word['pitch']
  3467. ];
  3468. $word['paragraph_audio_url'] = '';
  3469. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3470. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3471. // 如果音频存在并且参数都未改变则使用已生成的音频
  3472. if (getProp($paragraph, 'paragraph_audio_url')) {
  3473. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3474. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3475. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3476. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3477. // {
  3478. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3479. // }
  3480. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3481. }
  3482. $tmp = $word;
  3483. // 组装章节分句音频数据
  3484. // $tmp['sequence'] = getProp($word, 'sequence');
  3485. // $tmp['text'] = getProp($word, 'text');
  3486. // $tmp['emotion'] = getProp($word, 'emotion');
  3487. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3488. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3489. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3490. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3491. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3492. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3493. $tmp['bid'] = $bid;
  3494. $tmp['version_id'] = $version_id;
  3495. $tmp['cid'] = $cid;
  3496. $tmp['sequence'] = $sequence;
  3497. $tmp['created_at'] = date('Y-m-d H:i:s');
  3498. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3499. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3500. $mp_chapter_paragraph_audios[] = $tmp;
  3501. $complete_paragraph_sequences[] = $sequence;
  3502. $sequence++;
  3503. }
  3504. $generate_json = json_encode($words, 256);
  3505. // 判断是否有未生成字幕的段落
  3506. $no_subtitle_sequences = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->whereIn('sequence', $complete_paragraph_sequences)->whereNull('subtitle_info')->pluck('sequence')->toArray();
  3507. if ($no_subtitle_sequences) {
  3508. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3509. }
  3510. try {
  3511. DB::beginTransaction();
  3512. $role_info = json_encode($existed_role_info, 256);
  3513. $boolen = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->update(['role_info' => $role_info, 'updated_at' => date('Y-m-d H:i:s')]);
  3514. if (!$boolen) {
  3515. DB::rollBack();
  3516. Utils::throwError('20003:更新角色信息失败');
  3517. }
  3518. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3519. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3520. if (!$count) {
  3521. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3522. }else {
  3523. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3524. }
  3525. $boolen1 = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->update(['generate_status'=>'制作中', 'generate_json' => $generate_json, 'updated_at' => date('Y-m-d H:i:s')]);
  3526. if (!$boolen1) {
  3527. DB::rollBack();
  3528. Utils::throwError('20003:更新生成数据失败');
  3529. }
  3530. $id = DB::table('mp_audio_tasks')->insertGetId([
  3531. 'audio_id' => getProp($chapter_audio, 'id'),
  3532. 'generate_status' => '执行中',
  3533. 'generate_json' => $generate_json,
  3534. 'bid' => $bid,
  3535. 'book_name' => getProp($chapter_audio, 'book_name'),
  3536. 'version_id' => $version_id,
  3537. 'version_name' => getProp($chapter_audio, 'version_name'),
  3538. 'cid' => $cid,
  3539. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3540. 'task_name' => $task_name,
  3541. 'created_at' => date('Y-m-d H:i:s'),
  3542. 'updated_at' => date('Y-m-d H:i:s')
  3543. ]);
  3544. if (!$id) {
  3545. DB::rollBack();
  3546. Utils::throwError('20003:创建任务失败');
  3547. }
  3548. // 删除不在段落序号范围内的其他数据
  3549. if ($complete_paragraph_sequences) {
  3550. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3551. }
  3552. // // 删除章节分句音频数据并重新插入
  3553. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3554. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3555. // if (!$boolen3) {
  3556. // DB::rollBack();
  3557. // Utils::throwError('20003:更新章节分句音频失败');
  3558. // }
  3559. } catch (\Exception $e) {
  3560. DB::rollBack();
  3561. Utils::throwError('20003:'.$e->getMessage());
  3562. }
  3563. DB::commit();
  3564. // 通知火山生成音频
  3565. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3566. // 根据ID通过API通知合成音频
  3567. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3568. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3569. $response = $result->getBody()->getContents();
  3570. $response_arr = json_decode($response, true);
  3571. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3572. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3573. Log::info('通知火山生成音频失败: '.$error_msg);
  3574. Utils::throwError('20003:通知火山生成音频失败');
  3575. }
  3576. return true;
  3577. }
  3578. public function timbreList($data) {
  3579. $gender = getProp($data, 'gender');
  3580. $timbre_name = getProp($data, 'voice_name');
  3581. $category_id = getProp($data, 'category_id');
  3582. $age_stage = getProp($data, 'age_stage');
  3583. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'age_stage', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  3584. if ($gender) {
  3585. $query->where('gender', $gender);
  3586. }
  3587. if ($timbre_name) {
  3588. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3589. }
  3590. if ($category_id) {
  3591. $query->where(function ($query) use ($category_id) {
  3592. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3593. });
  3594. }
  3595. if ($age_stage) {
  3596. $query->where('age_stage', $age_stage);
  3597. }
  3598. $list = $query->get()->map(function ($value) {
  3599. $value = (array)$value;
  3600. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3601. return $value;
  3602. })->toArray();
  3603. return $list;
  3604. }
  3605. // 生成火山临时token
  3606. public function setStsToken() {
  3607. // ************* 配置参数 *************
  3608. $method = 'GET';
  3609. $service = 'sts';
  3610. $host = 'open.volcengineapi.com';
  3611. $region = env('VOLC_REGION');
  3612. $endpoint = 'https://open.volcengineapi.com';
  3613. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3614. $access_key = env('VOLC_AK');
  3615. $secret_key = env('VOLC_SK');
  3616. // 获取缓存中的token,如果没有则请求接口
  3617. $token = Redis::get('volc_sts_token');
  3618. if (!$token) {
  3619. // 查询参数
  3620. $query_parameters = [
  3621. 'Action' => 'AssumeRole',
  3622. 'RoleSessionName' => 'user@zw',
  3623. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3624. 'Version' => '2018-01-01'
  3625. ];
  3626. // 生成URL编码的查询字符串
  3627. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3628. // 获取签名头信息
  3629. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3630. // 构建完整URL
  3631. $request_url = $endpoint . '?' . $request_parameters;
  3632. $client = new Client(['verify' => false]);
  3633. $response = $client->get($request_url, ['headers' => $headers]);
  3634. $response_arr = json_decode($response->getBody()->getContents(), true);
  3635. $result = [
  3636. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3637. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3638. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3639. 'Region' => env('VOLC_REGION'),
  3640. 'Endpoint' => env('VOLC_END_POINT'),
  3641. 'Bucket' => env('VOLC_BUCKET'),
  3642. ];
  3643. // 缓存token
  3644. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3645. return $result;
  3646. } else {
  3647. return json_decode($token, true);
  3648. }
  3649. // $response = $response['Response'];
  3650. // $access_key = $response['Credentials']['AccessKeyId'];
  3651. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3652. // $security_token = $response['Credentials']['SecurityToken'];
  3653. // $expiration = $response['Credentials']['Expiration'];
  3654. // dd($response_arr);
  3655. }
  3656. public function emotionGroups($data) {
  3657. $id = getProp($data, 'group_id');
  3658. $group_name = getProp($data, 'group_name');
  3659. $voice_type = getProp($data, 'voice_type');
  3660. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3661. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3662. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3663. if ($group_name) {
  3664. $query->where('group_name', 'like', "%{$group_name}%");
  3665. }
  3666. if ($id) {
  3667. $query->where('id', $id);
  3668. }
  3669. if ($voice_type) {
  3670. $query->where('voice_type', $voice_type);
  3671. }
  3672. return $query->orderBy('id')->get()->map(function ($value) {
  3673. return (array)$value;
  3674. })->toArray();
  3675. }
  3676. private function sign($key, $msg) {
  3677. return hash_hmac('sha256', $msg, $key, true);
  3678. }
  3679. // 生成签名密钥
  3680. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3681. $kDate = $this->sign($key, $dateStamp);
  3682. $kRegion = $this->sign($kDate, $regionName);
  3683. $kService = $this->sign($kRegion, $serviceName);
  3684. $kSigning = $this->sign($kService, 'request');
  3685. return $kSigning;
  3686. }
  3687. // 获取签名头信息
  3688. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3689. $contenttype = 'application/x-www-form-urlencoded';
  3690. $accept = 'application/json';
  3691. // 获取当前UTC时间
  3692. $t = new DateTime('now', new DateTimeZone('UTC'));
  3693. $xdate = $t->format('Ymd\THis\Z');
  3694. $datestamp = $t->format('Ymd');
  3695. // 1. 拼接规范请求串
  3696. $canonical_uri = '/';
  3697. $canonical_querystring = $request_parameters;
  3698. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3699. $signed_headers = 'content-type;host;x-date';
  3700. // 空请求体的SHA256哈希
  3701. $payload_hash = hash('sha256', '');
  3702. $canonical_request = implode("\n", [
  3703. $method,
  3704. $canonical_uri,
  3705. $canonical_querystring,
  3706. $canonical_headers,
  3707. $signed_headers,
  3708. $payload_hash
  3709. ]);
  3710. // 2. 拼接待签名字符串
  3711. $algorithm = 'HMAC-SHA256';
  3712. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3713. $hashed_canonical_request = hash('sha256', $canonical_request);
  3714. $string_to_sign = implode("\n", [
  3715. $algorithm,
  3716. $xdate,
  3717. $credential_scope,
  3718. $hashed_canonical_request
  3719. ]);
  3720. // 3. 计算签名
  3721. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3722. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3723. // 4. 添加签名到请求头
  3724. $authorization_header = sprintf(
  3725. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3726. $algorithm,
  3727. $access_key,
  3728. $credential_scope,
  3729. $signed_headers,
  3730. $signature
  3731. );
  3732. return [
  3733. 'Accept' => $accept,
  3734. 'Content-Type' => $contenttype,
  3735. 'X-Date' => $xdate,
  3736. 'Authorization' => $authorization_header
  3737. ];
  3738. }
  3739. // 文字合成语音(火山引擎)
  3740. public function tts($data) {
  3741. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3742. $headers = [
  3743. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3744. 'Content-Type' => 'application/json; charset=UTF-8'
  3745. ];
  3746. $post_data = [
  3747. 'app' => [
  3748. 'appid' => env('VOLC_APPID'),
  3749. 'token' => env('VOLC_TOKEN'),
  3750. 'cluster' => 'volcano_tts'
  3751. ],
  3752. 'user' => [
  3753. 'uid' => 'mp_audio'
  3754. ],
  3755. // 'audio' => [
  3756. // 'voice_type' =>
  3757. // ],
  3758. ];
  3759. }
  3760. public function scriptList($data) {
  3761. $uid = Site::getUid();
  3762. $script_id = getProp($data, 'script_id');
  3763. $script_name = getProp($data, 'script_name');
  3764. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3765. if ($script_id) {
  3766. $query->where('id', $script_id);
  3767. }
  3768. if ($script_name) {
  3769. $query->where('script_name', 'like', "%{$script_name}%");
  3770. }
  3771. return $query->orderBy('created_at', 'desc')->paginate(12);
  3772. }
  3773. public function scripts($data) {
  3774. $uid = Site::getUid();
  3775. $script_id = getProp($data, 'script_id');
  3776. $script_name = getProp($data, 'script_name');
  3777. $is_products = getProp($data, 'is_products');
  3778. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3779. if ($script_id) {
  3780. $query->where('id', $script_id);
  3781. }
  3782. if ($is_products !== '') {
  3783. $query->where('is_products', $is_products);
  3784. }
  3785. if ($script_name) {
  3786. $query->where('script_name', 'like', "%{$script_name}%");
  3787. }
  3788. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3789. return (array)$value;
  3790. })->toArray();
  3791. }
  3792. public function scriptInfo($data) {
  3793. $uid = Site::getUid();
  3794. $script_id = getProp($data, 'script_id');
  3795. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3796. // ->selectRaw('id as script_id, script_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_sequence, end_episode_sequence, episode_num, remark, created_at')->first();
  3797. ->selectRaw('id as script_id, script_name')->first();
  3798. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3799. $script = (array)$script;
  3800. // 获取分集组信息
  3801. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3802. ->selectRaw('id as group_id, script_id, group_name, start_episode_number, end_episode_number, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, episode_content')
  3803. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3804. $value = (array)$value;
  3805. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3806. return (array)$value;
  3807. })->toArray();
  3808. $script['group'] = $groups;
  3809. return $script;
  3810. }
  3811. public function createScript($data) {
  3812. $script_name = getProp($data, 'script_name');
  3813. $uid = Site::getUid(); // 获取当前用户ID
  3814. $cpid = Site::getCpid(); // 获取当前公司组ID
  3815. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3816. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3817. $script_name .= '_'.date('YmdHis');
  3818. }
  3819. return DB::table('mp_scripts')->insertGetId([
  3820. 'script_name' => $script_name,
  3821. 'user_id' => $uid,
  3822. 'cpid' => $cpid,
  3823. 'created_at' => date('Y-m-d H:i:s'),
  3824. 'updated_at' => date('Y-m-d H:i:s')
  3825. ]);
  3826. }
  3827. public function editScript($data) {
  3828. $script_id = getProp($data, 'script_id');
  3829. $script_name = getProp($data, 'script_name');
  3830. $uid = Site::getUid(); // 获取当前用户ID
  3831. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3832. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3833. if ($id && (int)$id !== (int)$script_id) {
  3834. $script_name .= '_'.date('YmdHis');
  3835. }
  3836. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3837. 'script_name' => $script_name,
  3838. 'updated_at' => date('Y-m-d H:i:s')
  3839. ]);
  3840. }
  3841. public function delScript($data) {
  3842. $script_id = getProp($data, 'script_id');
  3843. $uid = Site::getUid(); // 获取当前用户ID
  3844. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3845. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3846. 'is_deleted' => 1,
  3847. 'updated_at' => date('Y-m-d H:i:s')
  3848. ]);
  3849. }
  3850. public function createEpisode($data) {
  3851. $script_id = getProp($data, 'script_id');
  3852. $group_name = getProp($data, 'group_name');
  3853. $remark = getProp($data, 'remark');
  3854. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3855. $uid = Site::getUid(); // 获取当前用户ID
  3856. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3857. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3858. $group_name .= '_'.date('YmdHis');
  3859. }
  3860. return DB::table('mp_script_episode_group')->insertGetId([
  3861. 'script_id' => $script_id,
  3862. 'group_name' => $group_name,
  3863. 'user_id' => $uid,
  3864. 'remark' => $remark,
  3865. 'created_at' => date('Y-m-d H:i:s'),
  3866. 'updated_at' => date('Y-m-d H:i:s')
  3867. ]);
  3868. }
  3869. public function editEpisode($data) {
  3870. $group_id = getProp($data, 'group_id');
  3871. $start_episode_number = getProp($data, 'start_episode_number');
  3872. $end_episode_number = getProp($data, 'end_episode_number');
  3873. $group_name = getProp($data, 'group_name');
  3874. $uid = Site::getUid(); // 获取当前用户ID
  3875. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3876. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3877. if ($id && (int)$id !== (int)$group_id) {
  3878. $group_name .= '_'.date('YmdHis');
  3879. }
  3880. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3881. 'group_name' => $group_name,
  3882. 'start_episode_number' => $start_episode_number,
  3883. 'end_episode_number' => $end_episode_number,
  3884. 'updated_at' => date('Y-m-d H:i:s')
  3885. ]);
  3886. }
  3887. public function delEpisode($data) {
  3888. $group_id = getProp($data, 'group_id');
  3889. $uid = Site::getUid(); // 获取当前用户ID
  3890. if (!$group_id) Utils::throwError('20003:请选择分集');
  3891. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3892. 'is_deleted' => 1,
  3893. 'updated_at' => date('Y-m-d H:i:s')
  3894. ]);
  3895. }
  3896. /**
  3897. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3898. *
  3899. * @param array $data 包含以下参数:
  3900. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3901. * - question: 用户问题(可选)
  3902. * - model: 使用的模型(r1 或 v3,默认 v3)
  3903. * @return \Generator 返回生成器,用于流式输出
  3904. */
  3905. public function generateEpisodes($data) {
  3906. $script_id = getProp($data, 'script_id');
  3907. $group_id = getProp($data, 'group_id');
  3908. // $file = getProp($data, 'file');
  3909. $file = '';
  3910. $content = getProp($data, 'content', '');
  3911. // $bid = getProp($data, 'bid', 0);
  3912. $bid = 0;
  3913. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3914. if (!$group) {
  3915. Utils::throwError('20003:剧本分集不存在');
  3916. }
  3917. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3918. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3919. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3920. $prompt = getProp($data, 'prompt');
  3921. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3922. $model = getProp($data, 'model');
  3923. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3924. Utils::throwError('20003:该模型不存在!');
  3925. }
  3926. // 检查是否存在重叠的剧集序号范围
  3927. $exists_groups = DB::table('mp_script_episode_group')
  3928. ->where('script_id', $script_id)
  3929. ->where('id', '<>', $group_id) // 排除当前组
  3930. ->where('is_deleted', 0)
  3931. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3932. // 检查新范围是否与现有范围重叠
  3933. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3934. // 新范围的开始在现有范围内
  3935. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3936. ->where('end_episode_number', '>=', $start_episode_sequence);
  3937. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3938. // 新范围的结束在现有范围内
  3939. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3940. ->where('end_episode_number', '>=', $end_episode_sequence);
  3941. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3942. // 新范围完全包含现有范围
  3943. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3944. ->where('end_episode_number', '<=', $end_episode_sequence);
  3945. });
  3946. })
  3947. ->select('start_episode_number', 'end_episode_number')
  3948. ->get();
  3949. if ($exists_groups->isNotEmpty()) {
  3950. $conflict_ranges = [];
  3951. foreach ($exists_groups as $group) {
  3952. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3953. }
  3954. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3955. }
  3956. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3957. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3958. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3959. if ($model === 'deepseek-chat') {
  3960. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3961. $model = 'deepseek-v4-flash';
  3962. $thinkingMode = 'disabled';
  3963. } elseif ($model === 'deepseek-reasoner') {
  3964. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3965. $model = 'deepseek-v4-flash';
  3966. $thinkingMode = 'enabled';
  3967. }
  3968. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3969. if (!$script) {
  3970. Utils::throwError('20003:剧本不存在');
  3971. }
  3972. $content = getProp($group, 'content');
  3973. if (!$file && !$content && !$bid) {
  3974. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3975. }
  3976. // 提取文件内容
  3977. if ($file) {
  3978. $content = $this->extractFileContent($file);
  3979. if (!$content) {
  3980. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3981. }
  3982. } elseif ($bid) {
  3983. $content = $this->getContentByBid($bid);
  3984. if (!$content) {
  3985. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3986. }
  3987. } elseif ($content) {
  3988. $content = filterContent($content);
  3989. } elseif ($prompt) {
  3990. $content = filterContent($prompt);
  3991. } else {
  3992. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3993. }
  3994. // 构建消息
  3995. $messages = [
  3996. $this->sys_message,
  3997. [
  3998. 'role' => 'user',
  3999. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4000. ]
  4001. ];
  4002. $post_data = [
  4003. 'model' => $model,
  4004. 'messages' => $messages,
  4005. // 'max_tokens' => 8192,
  4006. 'temperature' => 0.7,
  4007. 'frequency_penalty' => 0,
  4008. 'presence_penalty' => 0,
  4009. 'thinking' => ['type' => $thinkingMode],
  4010. 'response_format' => ['type' => 'text'],
  4011. 'stream' => true
  4012. ];
  4013. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4014. // 根据模型类型选择调用方法
  4015. $fullContent = '';
  4016. $fullReasoningContent = '';
  4017. $usage = [];
  4018. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4019. // DeepSeek 官方模型使用 DeepSeek API
  4020. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4021. } else if (in_array($model, $this->gpt_text_models)) {
  4022. // GPT-5.4 模型使用 TokenRouter API
  4023. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4024. } else if (in_array($model, $this->gemini_text_models)) {
  4025. // Gemini 模型使用 Gemini API
  4026. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4027. } else {
  4028. // 其他模型使用火山引擎API
  4029. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4030. }
  4031. // 处理流式输出
  4032. foreach ($streamGenerator as $chunk) {
  4033. if (isset($chunk['type'])) {
  4034. if ($chunk['type'] === 'done') {
  4035. // 最终结果
  4036. $fullContent = $chunk['full_content'];
  4037. $fullReasoningContent = $chunk['full_reasoning'];
  4038. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4039. } else {
  4040. // 逐块yield数据
  4041. yield $chunk;
  4042. }
  4043. }
  4044. }
  4045. dLog('deepseek')->info('完整内容: '.$fullContent);
  4046. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4047. // 处理完整内容并返回最终结果
  4048. $script_arr = [];
  4049. if ($fullContent) {
  4050. $script_arr = extractScriptContent($fullContent);
  4051. }
  4052. logDB('deepseek', 'info', '解析内容', $script_arr);
  4053. if (!$script_arr['episodes']) {
  4054. Utils::throwError('20003:未生成剧本相关信息');
  4055. // yield [
  4056. // 'type' => 'done',
  4057. // 'script' => $script_arr,
  4058. // 'msg' => '未生成剧本相关信息',
  4059. // 'answer' => $fullContent,
  4060. // 'reasoning' => $fullReasoningContent,
  4061. // 'usage' => $usage
  4062. // ];
  4063. // return ;
  4064. }
  4065. try {
  4066. DB::beginTransaction();
  4067. // // 返回前保存剧本内容
  4068. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4069. // 'content' => $content,
  4070. // 'updated_at' => date('Y-m-d H:i:s')
  4071. // ]);
  4072. // if (!$boolen) {
  4073. // Utils::throwError('20003:保存剧本内容失败');
  4074. // }
  4075. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4076. // 'start_episode_number' => $start_episode_sequence,
  4077. // 'end_episode_number' => $end_episode_sequence,
  4078. // 'updated_at' => date('Y-m-d H:i:s')
  4079. // ]);
  4080. // if (!$boolen1) {
  4081. // Utils::throwError('20003:保存分集失败');
  4082. // }
  4083. $episode_content = '';
  4084. $episodes = [];
  4085. foreach ($script_arr['episodes'] as $item) {
  4086. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4087. // $episodes[] = [
  4088. // 'script_id' => $script_id,
  4089. // 'episode_number' => $item['episode_number'],
  4090. // 'episode_name' => $item['episode_name'],
  4091. // 'episode_content' => $item['episode_content'],
  4092. // 'created_at' => date('Y-m-d H:i:s'),
  4093. // 'updated_at' => date('Y-m-d H:i:s'),
  4094. // ];
  4095. }
  4096. if ($episode_content) {
  4097. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4098. 'episode_content' => $episode_content,
  4099. 'updated_at' => date('Y-m-d H:i:s')
  4100. ]);
  4101. if (!$boolen2) {
  4102. Utils::throwError('20003:保存分集内容失败');
  4103. }
  4104. }else {
  4105. Utils::throwError('20003:分集剧本解析失败');
  4106. }
  4107. }catch (\Exception $e) {
  4108. DB::rollBack();
  4109. Utils::throwError('20003:'.$e->getMessage());
  4110. }
  4111. DB::commit();
  4112. // 仅记录 token 使用明细(不扣积分)
  4113. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4114. 'model' => $model,
  4115. 'script_id' => $script_id,
  4116. 'group_id' => $group_id,
  4117. 'source' => 'generateEpisodes',
  4118. ], $model);
  4119. yield [
  4120. 'type' => 'done',
  4121. 'script' => $script_arr,
  4122. 'episode_content' => $episode_content,
  4123. 'answer' => $fullContent,
  4124. 'reasoning' => $fullReasoningContent,
  4125. 'usage' => $usage
  4126. ];
  4127. }
  4128. public function chatWithFileStream($data) {
  4129. $script_id = getProp($data, 'script_id');
  4130. $group_id = getProp($data, 'group_id');
  4131. $file = getProp($data, 'file');
  4132. $content = getProp($data, 'content', '');
  4133. $bid = getProp($data, 'bid', 0);
  4134. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4135. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4136. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4137. $prompt = getProp($data, 'prompt');
  4138. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4139. if (!empty($prompt)) {
  4140. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4141. }
  4142. $question = getProp($data, 'question', $baseQuestion);
  4143. $model = getProp($data, 'model');
  4144. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4145. Utils::throwError('20003:该模型不存在!');
  4146. }
  4147. // 检查是否存在重叠的剧集序号范围
  4148. $exists_groups = DB::table('mp_script_episode_group')
  4149. ->where('script_id', $script_id)
  4150. ->where('id', '<>', $group_id)
  4151. ->where('is_deleted', 0)
  4152. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4153. // 检查新范围是否与现有范围重叠
  4154. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4155. // 新范围的开始在现有范围内
  4156. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4157. ->where('end_episode_number', '>=', $start_episode_sequence);
  4158. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4159. // 新范围的结束在现有范围内
  4160. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4161. ->where('end_episode_number', '>=', $end_episode_sequence);
  4162. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4163. // 新范围完全包含现有范围
  4164. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4165. ->where('end_episode_number', '<=', $end_episode_sequence);
  4166. });
  4167. })
  4168. ->select('start_episode_number', 'end_episode_number')
  4169. ->get();
  4170. if ($exists_groups->isNotEmpty()) {
  4171. $conflict_ranges = [];
  4172. foreach ($exists_groups as $group) {
  4173. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4174. }
  4175. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4176. }
  4177. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4178. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4179. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4180. if ($model === 'deepseek-chat') {
  4181. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4182. $model = 'deepseek-v4-flash';
  4183. $thinkingMode = 'disabled';
  4184. } elseif ($model === 'deepseek-reasoner') {
  4185. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4186. $model = 'deepseek-v4-flash';
  4187. $thinkingMode = 'enabled';
  4188. }
  4189. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4190. if (!$script) {
  4191. Utils::throwError('20003:剧本不存在');
  4192. }
  4193. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4194. if (!$group) {
  4195. Utils::throwError('20003:剧本分集不存在');
  4196. }
  4197. if (!$file && !$content && !$bid) {
  4198. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4199. }
  4200. // 提取文件内容
  4201. if ($file) {
  4202. $content = $this->extractFileContent($file);
  4203. if (!$content) {
  4204. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4205. }
  4206. } elseif ($bid) {
  4207. $content = $this->getContentByBid($bid);
  4208. if (!$content) {
  4209. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4210. }
  4211. } elseif ($content) {
  4212. $content = filterContent($content);
  4213. } elseif ($prompt) {
  4214. $content = filterContent($prompt);
  4215. } else {
  4216. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4217. }
  4218. // 构建消息
  4219. $messages = [
  4220. [
  4221. 'role' => 'system',
  4222. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4223. 强制要求:\n
  4224. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4225. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4226. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4227. 普通要求:\n
  4228. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4229. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4230. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4231. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4232. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4233. 示例如下:\n
  4234. ###剧本名:西昆仑
  4235. ###故事梗概
  4236. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4237. ###剧本亮点
  4238. 亮点1:绝境奇药,生死一线
  4239. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4240. 亮点2:结拜兄妹,化解尴尬
  4241. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4242. 亮点3:纤发夺命,情愫暗涌
  4243. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4244. ###人物关系
  4245. 阿雪与梁萧之间存在兄妹之情。
  4246. ###核心矛盾
  4247. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4248. ###主体列表
  4249. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4250. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4251. 阴阳球:天地异宝,能化生精气,救人于危难。
  4252. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4253. ###美术风格
  4254. 基础画风风格词:厚涂古风
  4255. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4256. ###场景列表
  4257. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4258. [
  4259. 'role' => 'user',
  4260. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4261. ]
  4262. ];
  4263. $post_data = [
  4264. 'model' => $model,
  4265. 'messages' => $messages,
  4266. // 'max_tokens' => 8192,
  4267. 'temperature' => 0.7,
  4268. 'frequency_penalty' => 0,
  4269. 'presence_penalty' => 0,
  4270. 'thinking' => ['type' => $thinkingMode],
  4271. 'response_format' => ['type' => 'text'],
  4272. 'stream' => true
  4273. ];
  4274. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4275. // 根据模型类型选择调用方法
  4276. $fullContent = '';
  4277. $fullReasoningContent = '';
  4278. $usage = [];
  4279. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4280. // DeepSeek 官方模型使用 DeepSeek API
  4281. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4282. } else if (in_array($model, $this->gpt_text_models)) {
  4283. // GPT-5.4 模型使用 TokenRouter API
  4284. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4285. } else if (in_array($model, $this->gemini_text_models)) {
  4286. // Gemini 模型使用 Gemini API
  4287. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4288. } else {
  4289. // 其他模型使用火山引擎API
  4290. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4291. }
  4292. // 处理流式输出
  4293. foreach ($streamGenerator as $chunk) {
  4294. if (isset($chunk['type'])) {
  4295. if ($chunk['type'] === 'done') {
  4296. // 最终结果
  4297. $fullContent = $chunk['full_content'];
  4298. $fullReasoningContent = $chunk['full_reasoning'];
  4299. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4300. } else {
  4301. // 逐块yield数据
  4302. yield $chunk;
  4303. }
  4304. }
  4305. }
  4306. dLog('deepseek')->info('完整内容: '.$fullContent);
  4307. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4308. // 处理完整内容并返回最终结果
  4309. $script_arr = [];
  4310. if ($fullContent) {
  4311. $script_arr = extractScriptContent($fullContent);
  4312. }
  4313. logDB('deepseek', 'info', '解析内容', $script_arr);
  4314. if (!$script_arr['roles']) {
  4315. Utils::throwError('20003:未生成剧本相关信息');
  4316. // yield [
  4317. // 'type' => 'done',
  4318. // 'script' => $script_arr,
  4319. // 'msg' => '未生成剧本相关信息',
  4320. // 'answer' => $fullContent,
  4321. // 'reasoning' => $fullReasoningContent,
  4322. // 'usage' => $usage
  4323. // ];
  4324. }
  4325. try {
  4326. DB::beginTransaction();
  4327. // // 返回前保存剧本内容
  4328. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4329. // 'content' => $content,
  4330. // 'status' => '解析完成',
  4331. // 'updated_at' => date('Y-m-d H:i:s')
  4332. // ]);
  4333. // if (!$boolen) {
  4334. // Utils::throwError('20003:保存剧本内容失败');
  4335. // }
  4336. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4337. 'start_episode_number' => $start_episode_sequence,
  4338. 'end_episode_number' => $end_episode_sequence,
  4339. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4340. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4341. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4342. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4343. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4344. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4345. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4346. 'status' => '解析完成',
  4347. 'content' => $content,
  4348. 'updated_at' => date('Y-m-d H:i:s')
  4349. ]);
  4350. if (!$boolen1) {
  4351. Utils::throwError('20003:保存分集失败');
  4352. }
  4353. // $episodes = [];
  4354. // foreach ($script_arr['episodes'] as $item) {
  4355. // $episodes[] = [
  4356. // 'script_id' => $script_id,
  4357. // 'episode_number' => $item['episode_number'],
  4358. // 'episode_name' => $item['episode_name'],
  4359. // 'episode_content' => $item['episode_content'],
  4360. // 'created_at' => date('Y-m-d H:i:s'),
  4361. // 'updated_at' => date('Y-m-d H:i:s'),
  4362. // ];
  4363. // }
  4364. // if ($episodes) {
  4365. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4366. // if (!$boolen2) {
  4367. // Utils::throwError('20003:保存分集内容失败');
  4368. // }
  4369. // }else {
  4370. // Utils::throwError('20003:分集剧本解析失败');
  4371. // }
  4372. }catch (\Exception $e) {
  4373. DB::rollBack();
  4374. Utils::throwError('20003:'.$e->getMessage());
  4375. }
  4376. DB::commit();
  4377. // 仅记录 token 使用明细(不扣积分)
  4378. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4379. 'model' => $model,
  4380. 'script_id' => $script_id,
  4381. 'group_id' => $group_id,
  4382. 'source' => 'chatWithFileStream',
  4383. ], $model);
  4384. yield [
  4385. 'type' => 'done',
  4386. 'script' => $script_arr,
  4387. 'answer' => $fullContent,
  4388. 'reasoning' => $fullReasoningContent,
  4389. 'usage' => $usage
  4390. ];
  4391. }
  4392. /**
  4393. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4394. *
  4395. * @param array $data 包含以下参数:
  4396. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4397. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4398. * - model: 使用的模型(r1 或 v3,默认 v3)
  4399. * @return array
  4400. */
  4401. public function chatWithFile($data) {
  4402. $script_id = getProp($data, 'script_id');
  4403. $file = getProp($data, 'file');
  4404. $content = getProp($data, 'content', '');
  4405. $bid = getProp($data, 'bid', 0);
  4406. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4407. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4408. $prompt = getProp($data, 'prompt');
  4409. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4410. if (!empty($prompt)) {
  4411. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4412. }
  4413. $question = getProp($data, 'question', $baseQuestion);
  4414. // 处理文本模型
  4415. $model = getProp($data, 'model');
  4416. if (!$model) {
  4417. // 用户没有输入,使用默认值
  4418. $model = 'doubao-seed-2-0-mini-260215';
  4419. }
  4420. // 验证模型是否在可用模型表中
  4421. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4422. $model = 'doubao-seed-2-0-mini-260215';
  4423. }
  4424. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4425. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4426. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4427. if ($model === 'deepseek-chat') {
  4428. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4429. $model = 'deepseek-v4-flash';
  4430. $thinkingMode = 'disabled';
  4431. } elseif ($model === 'deepseek-reasoner') {
  4432. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4433. $model = 'deepseek-v4-flash';
  4434. $thinkingMode = 'enabled';
  4435. }
  4436. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4437. if (!$script) {
  4438. Utils::throwError('20003:剧本不存在');
  4439. }
  4440. if (!$file && !$content && !$bid) {
  4441. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4442. }
  4443. // 提取文件内容
  4444. if ($file) {
  4445. $content = $this->extractFileContent($file);
  4446. if (!$content) {
  4447. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4448. }
  4449. } elseif ($bid) {
  4450. $content = $this->getContentByBid($bid);
  4451. if (!$content) {
  4452. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4453. }
  4454. } elseif ($content) {
  4455. $content = filterContent($content);
  4456. } elseif ($prompt) {
  4457. $content = filterContent($prompt);
  4458. } else {
  4459. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4460. }
  4461. // 构建消息
  4462. $messages = [
  4463. $this->sys_message,
  4464. [
  4465. 'role' => 'user',
  4466. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4467. ]
  4468. ];
  4469. $post_data = [
  4470. 'model' => $model,
  4471. 'messages' => $messages,
  4472. // 'max_tokens' => 8192,
  4473. 'temperature' => 0.7,
  4474. 'frequency_penalty' => 0,
  4475. 'presence_penalty' => 0,
  4476. 'thinking' => ['type' => $thinkingMode],
  4477. 'response_format' => ['type' => 'text'],
  4478. 'stream' => false
  4479. ];
  4480. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4481. // 根据模型类型选择调用方法
  4482. $fullContent = '';
  4483. $usage = [];
  4484. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4485. // DeepSeek 官方模型使用 DeepSeek API
  4486. $chatResult = $this->chatOnly($post_data);
  4487. } else if (in_array($model, $this->gpt_text_models)) {
  4488. // GPT-5.4 模型使用 TokenRouter API
  4489. $chatResult = $this->gpt54ChatOnly($post_data);
  4490. } else {
  4491. // 其他模型使用火山引擎API
  4492. $chatResult = $this->volcEngineChatCompletion($post_data);
  4493. }
  4494. if (is_array($chatResult)) {
  4495. $fullContent = $chatResult['fullContent'];
  4496. $usage = $chatResult['usage'];
  4497. }
  4498. $script_arr = [];
  4499. // 处理结果
  4500. if ($fullContent) {
  4501. $script_arr = extractScriptContent($fullContent);
  4502. }
  4503. // 返回前保存剧本内容
  4504. DB::table('mp_scripts')->where('id', $script_id)->update([
  4505. 'content' => $content,
  4506. 'updated_at' => date('Y-m-d H:i:s')
  4507. ]);
  4508. // 仅记录 token 使用明细(不扣积分)
  4509. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4510. 'model' => $model,
  4511. 'script_id' => $script_id,
  4512. 'source' => 'chatWithFile',
  4513. ], $model);
  4514. return [
  4515. 'script' => $script_arr,
  4516. 'answer' => $fullContent,
  4517. 'usage' => $usage
  4518. ];
  4519. }
  4520. public function getEpisodeContent($data) {
  4521. $group_id = getProp($data, 'group_id');
  4522. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4523. }
  4524. public function saveEpisodeContent($data) {
  4525. $script_id = getProp($data, 'script_id');
  4526. $group_id = getProp($data, 'group_id');
  4527. $start_episode_sequence = getProp($data, 'start_episode_number');
  4528. $end_episode_sequence = getProp($data, 'end_episode_number');
  4529. // 检查是否存在重叠的剧集序号范围
  4530. $exists_groups = DB::table('mp_script_episode_group')
  4531. ->where('script_id', $script_id)
  4532. ->where('id', '<>', $group_id) // 排除当前组
  4533. ->where('is_deleted', 0)
  4534. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4535. // 检查新范围是否与现有范围重叠
  4536. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4537. // 新范围的开始在现有范围内
  4538. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4539. ->where('end_episode_number', '>=', $start_episode_sequence);
  4540. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4541. // 新范围的结束在现有范围内
  4542. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4543. ->where('end_episode_number', '>=', $end_episode_sequence);
  4544. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4545. // 新范围完全包含现有范围
  4546. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4547. ->where('end_episode_number', '<=', $end_episode_sequence);
  4548. });
  4549. })
  4550. ->select('start_episode_number', 'end_episode_number')
  4551. ->get();
  4552. if ($exists_groups->isNotEmpty()) {
  4553. $conflict_ranges = [];
  4554. foreach ($exists_groups as $group) {
  4555. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4556. }
  4557. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4558. }
  4559. $episode_content = getProp($data, 'episode_content');
  4560. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4561. 'content' => $episode_content,
  4562. 'start_episode_number' => $start_episode_sequence,
  4563. 'end_episode_number' => $end_episode_sequence,
  4564. 'updated_at' => date('Y-m-d H:i:s')
  4565. ]);
  4566. $script_arr =getProp($data, 'script', []);
  4567. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4568. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4569. $script_id = getProp($data, 'script_id');
  4570. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4571. try {
  4572. DB::beginTransaction();
  4573. $update_data = [
  4574. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4575. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4576. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4577. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4578. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4579. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4580. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4581. 'status' => 3,
  4582. 'start_episode_sequence' => $start_episode_sequence,
  4583. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4584. 'episode_num' => count($script_arr['episodes']),
  4585. 'updated_at' => date('Y-m-d H:i:s')
  4586. ];
  4587. // 保存剧本内容
  4588. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4589. if (!$boolen) {
  4590. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4591. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4592. Utils::throwError('20003:剧本内容保存失败');
  4593. }
  4594. // 保存分集内容
  4595. // 删除历史分集内容
  4596. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4597. $episodes = [];
  4598. $sequence = 1;
  4599. foreach ($script_arr['episodes'] as $episode) {
  4600. $segment_number = 1;
  4601. foreach($episode['segments'] as $segment) {
  4602. $episodes[] = [
  4603. 'script_id' => $script_id,
  4604. 'episode_number' => $episode['episode_number'],
  4605. 'title' => $episode['title'],
  4606. // 'content' => $episode['content'],
  4607. 'content' => '',
  4608. 'segment_number' => $segment_number,
  4609. 'segment_content' => $segment['segment_content'],
  4610. 'sequence' => $sequence,
  4611. 'created_at' => date('Y-m-d H:i:s'),
  4612. 'updated_at' => date('Y-m-d H:i:s')
  4613. ];
  4614. $sequence++;
  4615. $segment_number++;
  4616. }
  4617. }
  4618. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4619. if (!$boolen2) {
  4620. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4621. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4622. Utils::throwError('20003:分集内容保存失败');
  4623. }
  4624. } catch (\Exception $e) {
  4625. DB::rollBack();
  4626. Utils::throwError('20003:'.$e->getMessage());
  4627. }
  4628. DB::commit();
  4629. return true;
  4630. }
  4631. public function getBookContent($data) {
  4632. $bid = getProp($data, 'bid');
  4633. $start_sequence = getProp($data, 'start_sequence');
  4634. $end_sequence = getProp($data, 'end_sequence');
  4635. $chapter_contents = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', 'cc.id')->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->whereBetween('c.sequence', [$start_sequence, $end_sequence])
  4636. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4637. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4638. return $return_content;
  4639. }
  4640. public function exportScript($data) {
  4641. $filename = getProp($data, 'filename');
  4642. $script_id = getProp($data, 'script_id');
  4643. $group_id = getProp($data, 'group_id');
  4644. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4645. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4646. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4647. $script = (array)$script;
  4648. // 获取分集组信息
  4649. if ($group_id) {
  4650. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4651. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4652. ->get()->map(function($value) {
  4653. return (array)$value;
  4654. })->toArray();
  4655. }else {
  4656. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4657. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4658. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4659. return (array)$value;
  4660. })->toArray();
  4661. }
  4662. if (!$groups) Utils::throwError('20003:分集不存在');
  4663. $script['group'] = $groups;
  4664. $export_type = getProp($data, 'export_type', 'txt');
  4665. // 生成文件名
  4666. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4667. // 根据导出类型生成不同格式的文件
  4668. switch ($export_type) {
  4669. case 'txt':
  4670. return $this->exportScriptAsTxt($script, $filename);
  4671. case 'pdf':
  4672. return $this->exportScriptAsPdf($script, $filename);
  4673. default:
  4674. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4675. }
  4676. }
  4677. /**
  4678. * 导出剧本为TXT格式
  4679. */
  4680. private function exportScriptAsTxt($script, $filename) {
  4681. // 构建TXT内容
  4682. $content = $this->buildScriptContent($script);
  4683. // 设置响应头,直接下载
  4684. header('Content-Type: text/plain; charset=utf-8');
  4685. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4686. header('Content-Length: ' . strlen($content));
  4687. // 输出内容并结束
  4688. echo $content;
  4689. exit();
  4690. }
  4691. /**
  4692. * 导出剧本为PDF格式
  4693. */
  4694. private function exportScriptAsPdf($script, $filename) {
  4695. // 使用HTML转PDF的方式来更好地支持中文
  4696. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4697. // 创建PDF实例
  4698. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4699. // 设置文档信息
  4700. $pdf->SetCreator('剧本导出系统');
  4701. $pdf->SetAuthor('系统');
  4702. $pdf->SetTitle($script['script_name']);
  4703. $pdf->SetSubject('剧本导出');
  4704. // 设置边距
  4705. $pdf->SetMargins(15, 15, 15);
  4706. $pdf->SetAutoPageBreak(TRUE, 15);
  4707. // 添加页面
  4708. $pdf->AddPage();
  4709. // 注册并使用 simsun.ttf 字体
  4710. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4711. // 使用HTML内容生成PDF
  4712. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4713. // 直接输出PDF文件供下载
  4714. header('Content-Type: application/pdf');
  4715. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4716. // 直接输出PDF内容
  4717. $pdf->Output($filename . '.pdf', 'D');
  4718. exit();
  4719. }
  4720. /**
  4721. * 构建用于PDF的HTML内容
  4722. */
  4723. private function buildScriptHtmlForPdf($script) {
  4724. $html = '<style>
  4725. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4726. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4727. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4728. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4729. .info { margin-bottom: 8px; }
  4730. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4731. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4732. .segment { margin-bottom: 10px; margin-left: 20px; }
  4733. .episode-content { white-space: pre-wrap; }
  4734. </style>';
  4735. // 标题
  4736. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4737. // 处理分组数据
  4738. if (!empty($script['group']) && is_array($script['group'])) {
  4739. $groups = (array)$script['group'];
  4740. foreach ($groups as $group) {
  4741. $html .= '<div class="group">';
  4742. // 分组标题
  4743. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4744. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4745. // 故事梗概
  4746. if (!empty($group['intro'])) {
  4747. $html .= '<h3>故事梗概</h3>';
  4748. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4749. }
  4750. // 剧本亮点
  4751. if (!empty($group['highlights'])) {
  4752. $html .= '<h3>剧本亮点</h3>';
  4753. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4754. }
  4755. // 人物关系
  4756. if (!empty($group['role_relationship'])) {
  4757. $html .= '<h3>人物关系</h3>';
  4758. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4759. }
  4760. // 核心矛盾
  4761. if (!empty($group['core_contradiction'])) {
  4762. $html .= '<h3>核心矛盾</h3>';
  4763. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4764. }
  4765. // 主体列表
  4766. if (!empty($group['roles']) && is_array($group['roles'])) {
  4767. $html .= '<h3>主体列表</h3>';
  4768. $html .= '<ul>';
  4769. foreach ($group['roles'] as $role) {
  4770. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4771. }
  4772. $html .= '</ul>';
  4773. }
  4774. // 美术风格
  4775. if (!empty($group['art_style'])) {
  4776. $html .= '<h3>美术风格</h3>';
  4777. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4778. }
  4779. // 场景列表
  4780. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4781. $html .= '<h3>场景列表</h3>';
  4782. $html .= '<ul>';
  4783. foreach ($group['scenes'] as $scene) {
  4784. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4785. }
  4786. $html .= '</ul>';
  4787. }
  4788. // 分集剧本
  4789. if (!empty($group['episode_content'])) {
  4790. $html .= '<h3>分集剧本</h3>';
  4791. // 去除零宽字符和其他不可见字符
  4792. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4793. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4794. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4795. }
  4796. $html .= '</div>';
  4797. }
  4798. }
  4799. return $html;
  4800. }
  4801. /**
  4802. * 构建PDF内容
  4803. */
  4804. private function buildPdfContent($pdf, $script) {
  4805. // 标题
  4806. $pdf->SetFont('dejavusans', 'B', 18);
  4807. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4808. $pdf->Ln(5);
  4809. // 基本信息
  4810. $pdf->SetFont('dejavusans', '', 12);
  4811. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4812. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4813. $pdf->Ln(5);
  4814. // 剧本简介
  4815. if (!empty($script['intro'])) {
  4816. $pdf->SetFont('dejavusans', 'B', 14);
  4817. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4818. $pdf->SetFont('dejavusans', '', 12);
  4819. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4820. $pdf->Ln(3);
  4821. }
  4822. // 亮点
  4823. if (!empty($script['highlights'])) {
  4824. $pdf->SetFont('dejavusans', 'B', 14);
  4825. $pdf->Cell(0, 10, '亮点', 0, 1);
  4826. $pdf->SetFont('dejavusans', '', 12);
  4827. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4828. $pdf->Ln(3);
  4829. }
  4830. // 核心矛盾
  4831. if (!empty($script['core_contradiction'])) {
  4832. $pdf->SetFont('dejavusans', 'B', 14);
  4833. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4834. $pdf->SetFont('dejavusans', '', 12);
  4835. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4836. $pdf->Ln(3);
  4837. }
  4838. // 艺术风格
  4839. if (!empty($script['art_style'])) {
  4840. $pdf->SetFont('dejavusans', 'B', 14);
  4841. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4842. $pdf->SetFont('dejavusans', '', 12);
  4843. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4844. $pdf->Ln(3);
  4845. }
  4846. // 备注
  4847. if (!empty($script['remark'])) {
  4848. $pdf->SetFont('dejavusans', 'B', 14);
  4849. $pdf->Cell(0, 10, '备注', 0, 1);
  4850. $pdf->SetFont('dejavusans', '', 12);
  4851. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4852. $pdf->Ln(3);
  4853. }
  4854. // 角色列表
  4855. if (!empty($script['roles']) && is_array($script['roles'])) {
  4856. $pdf->SetFont('dejavusans', 'B', 14);
  4857. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4858. $pdf->SetFont('dejavusans', '', 12);
  4859. foreach ($script['roles'] as $index => $role) {
  4860. if (is_array($role) || is_object($role)) {
  4861. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4862. } else {
  4863. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4864. }
  4865. }
  4866. $pdf->Ln(3);
  4867. }
  4868. // 角色关系
  4869. if (!empty($script['role_relationship'])) {
  4870. $pdf->SetFont('dejavusans', 'B', 14);
  4871. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4872. $pdf->SetFont('dejavusans', '', 12);
  4873. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4874. $pdf->Ln(3);
  4875. }
  4876. // 场景列表
  4877. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4878. $pdf->SetFont('dejavusans', 'B', 14);
  4879. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4880. $pdf->SetFont('dejavusans', '', 12);
  4881. foreach ($script['scenes'] as $index => $scene) {
  4882. if (is_array($scene) || is_object($scene)) {
  4883. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4884. } else {
  4885. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4886. }
  4887. }
  4888. $pdf->Ln(5);
  4889. }
  4890. // 分集内容
  4891. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4892. $pdf->SetFont('dejavusans', 'B', 16);
  4893. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4894. $pdf->Ln(3);
  4895. foreach ($script['episodes'] as $episode) {
  4896. // 检查是否需要新页面
  4897. if ($pdf->GetY() > 250) {
  4898. $pdf->AddPage();
  4899. }
  4900. $pdf->SetFont('dejavusans', 'B', 14);
  4901. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4902. if (!empty($episode['title'])) {
  4903. $episodeTitle .= ':' . $episode['title'];
  4904. }
  4905. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4906. // 处理分段内容
  4907. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4908. $pdf->SetFont('dejavusans', '', 12);
  4909. foreach ($episode['segments'] as $segment) {
  4910. if (!empty($segment['segment_content'])) {
  4911. // 如果有分段编号,显示分段标题
  4912. if (!empty($segment['segment_number'])) {
  4913. $pdf->SetFont('dejavusans', 'B', 12);
  4914. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4915. $pdf->SetFont('dejavusans', '', 12);
  4916. }
  4917. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4918. $pdf->Ln(2);
  4919. }
  4920. }
  4921. }
  4922. $pdf->Ln(5);
  4923. }
  4924. }
  4925. }
  4926. /**
  4927. * 构建剧本文本内容
  4928. */
  4929. private function buildScriptContent($script) {
  4930. $content = '';
  4931. $groups = $script['group'];
  4932. $groups = (array)$groups;
  4933. foreach ($groups as $group) {
  4934. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4935. // 剧本基本信息
  4936. if (!empty($group['intro'])) {
  4937. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4938. }
  4939. if (!empty($group['highlights'])) {
  4940. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4941. }
  4942. if (!empty($group['role_relationship'])) {
  4943. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4944. }
  4945. if (!empty($group['core_contradiction'])) {
  4946. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4947. }
  4948. if (!empty($group['roles']) && is_array($group['roles'])) {
  4949. $content .= "###主体列表\n";
  4950. foreach ($group['roles'] as $role) {
  4951. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4952. }
  4953. $content .= "\n\n";
  4954. }
  4955. if (!empty($group['art_style'])) {
  4956. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4957. }
  4958. // 场景信息
  4959. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4960. $content .= "###场景列表\n";
  4961. foreach ($group['scenes'] as $scene) {
  4962. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4963. }
  4964. $content .= "\n\n";
  4965. }
  4966. // 分集内容
  4967. if (!empty($group['episode_content'])) {
  4968. $content .= "###分集剧本\n";
  4969. $content .= $group['episode_content'];
  4970. // foreach ($script['episodes'] as $episode) {
  4971. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4972. // // if (!empty($episode['episode_name'])) {
  4973. // // $content .= ":" . $episode['episode_name'];
  4974. // // }
  4975. // // $content .= "\n";
  4976. // $content .= $episode['episode_content'] . "\n\n";
  4977. // }
  4978. }
  4979. }
  4980. return $content;
  4981. }
  4982. /**
  4983. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4984. *
  4985. * @param array $data 包含以下参数:
  4986. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4987. * - question: 用户问题(可选)
  4988. * - model: 使用的模型(r1 或 v3,默认 v3)
  4989. * @return \Generator 返回生成器,用于流式输出
  4990. */
  4991. public function addChat($data) {
  4992. $uid = Site::getUid();
  4993. $anime_id = getProp($data, 'anime_id');
  4994. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4995. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4996. if (!$anime) Utils::throwError('20003:对话不存在');
  4997. $file = getProp($data, 'file');
  4998. $content = getProp($data, 'content', '');
  4999. $bid = getProp($data, 'bid', 0);
  5000. $script_id = getProp($data, 'script_id', 0);
  5001. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5002. $prompt = getProp($data, 'prompt');
  5003. $user_anime_name = getProp($anime, 'anime_name');
  5004. // 处理文本模型
  5005. $model = getProp($data, 'model');
  5006. if (!$model) {
  5007. // 用户没有输入,从anime表获取
  5008. $model = getProp($anime, 'model');
  5009. if (!$model) {
  5010. // anime表也没有,使用默认值
  5011. $model = 'doubao-seed-2-0-mini-260215';
  5012. }
  5013. }
  5014. // 验证模型是否在可用模型表中
  5015. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5016. $model = 'doubao-seed-2-0-mini-260215';
  5017. }
  5018. $is_multi = getProp($anime, 'is_multi');
  5019. $is_single = (int)$is_multi !== 1;
  5020. // 积分余额预检(仅单剧集模式收费)
  5021. if ($is_single) {
  5022. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5023. }
  5024. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5025. if ($prompt) {
  5026. $question .= "本次修改要求如下:\n{$prompt}";
  5027. }
  5028. // if (!$file && !$content && !$bid) {
  5029. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5030. // }
  5031. // 提取文件内容
  5032. if ($file) {
  5033. $content = $this->extractFileContent($file);
  5034. if (!$content) {
  5035. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5036. }
  5037. } elseif ($script_id) {
  5038. $content = $this->getContentByScriptId($script_id);
  5039. if (!$content) {
  5040. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5041. }
  5042. } elseif ($bid) {
  5043. $content = $this->getContentByBid($bid);
  5044. if (!$content) {
  5045. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5046. }
  5047. } elseif ($content) {
  5048. $content = filterContent($content);
  5049. } else {
  5050. $content = getProp($anime, 'content');
  5051. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5052. $need_generate_content = true;
  5053. }
  5054. }
  5055. // 美术风格
  5056. $input_art_style = getProp($data, 'art_style');
  5057. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5058. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5059. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5060. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5061. 中年女:邻居阿姨
  5062. 老年男:幽默大爷
  5063. 老年女:婆婆
  5064. 萌娃:奶气萌娃";
  5065. // 判断是否需要生成原文内容
  5066. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5067. // 如果需要生成原文内容,添加额外的要求
  5068. $content_generation_requirement = $need_generate_content
  5069. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5070. : "";
  5071. // 美术风格
  5072. if (!$mappedArtStyle) {
  5073. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5074. }else {
  5075. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5076. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5077. }else {
  5078. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5079. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5080. }
  5081. }
  5082. $systemPrompt = $is_single
  5083. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5084. 强制要求:
  5085. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5086. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5087. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5088. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5089. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5090. 普通要求:
  5091. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5092. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5093. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5094. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5095. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5096. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5097. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5098. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5099. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5100. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5101. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5102. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5103. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5104. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5105. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5106. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5107. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5108. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5109. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5110. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5111. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5112. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5113. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5114. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5115. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5116. 5.{$mappedArtStyle_prompt}\n\n
  5117. 示例如下:\n
  5118. ###剧本名:西昆仑
  5119. ###故事梗概
  5120. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5121. ###剧本亮点
  5122. 亮点1:绝境奇药,生死一线
  5123. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5124. 亮点2:结拜兄妹,化解尴尬
  5125. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5126. 亮点3:纤发夺命,情愫暗涌
  5127. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5128. ###人物关系
  5129. 阿雪与梁萧之间存在兄妹之情。
  5130. ###核心矛盾
  5131. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5132. ###主体列表
  5133. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5134. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5135. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5136. 姿态:站立。}{{甜心小美}}
  5137. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5138. 全景,正面拍摄,青年女性,亚洲人。
  5139. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5140. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5141. 姿态:站立。}{{阳光青年}}
  5142. ###美术风格
  5143. 基础画风风格词:厚涂古风
  5144. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5145. ###场景列表
  5146. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5147. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5148. 无人物。}
  5149. ###分镜剧本
  5150. ##第1幕:徐家老旧厨房 白天 室内
  5151. 分镜1
  5152. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5153. 场景:徐家老旧厨房
  5154. 构图设计:全景,低角度仰视
  5155. 运镜调度:手持拍摄
  5156. 配音角色:旁白
  5157. 出镜角色:许芸-校服装、徐母
  5158. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5159. 画面类型:普通画面
  5160. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5161. 分镜2
  5162. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5163. 场景:徐家老旧厨房
  5164. 构图设计:近景,徐母面部特写
  5165. 运镜调度:固定镜头
  5166. 配音角色:徐母
  5167. 出镜角色:徐母
  5168. 台词内容:问我夜不归宿死哪儿去了。
  5169. 画面类型:对口型
  5170. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5171. ##第2幕:徐家简陋客厅 黄昏 室内
  5172. 分镜3
  5173. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5174. 场景:徐家简陋客厅
  5175. 构图设计:全景,景深虚化
  5176. 运镜调度:固定镜头
  5177. 配音角色:旁白
  5178. 出镜角色:无
  5179. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5180. 画面类型:普通画面
  5181. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5182. 分镜4
  5183. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5184. 场景:徐家简陋客厅
  5185. 构图设计:特写,火车票
  5186. 运镜调度:固定镜头
  5187. 配音角色:旁白
  5188. 出镜角色:无
  5189. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5190. 画面类型:普通画面
  5191. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5192. "
  5193. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5194. 强制要求:\n
  5195. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5196. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5197. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5198. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5199. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5200. 普通要求:\n
  5201. 1.剧本名(必须生成)必须与文档内容高度相关
  5202. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5203. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5204. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5205. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5206. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5207. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5208. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5209. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5210. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5211. 4.{$mappedArtStyle_prompt}\n\n
  5212. 示例如下:\n
  5213. ###剧本名:西昆仑
  5214. ###故事梗概
  5215. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5216. ###剧本亮点
  5217. 亮点1:绝境奇药,生死一线
  5218. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5219. 亮点2:结拜兄妹,化解尴尬
  5220. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5221. 亮点3:纤发夺命,情愫暗涌
  5222. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5223. ###人物关系
  5224. 阿雪与梁萧之间存在兄妹之情。
  5225. ###核心矛盾
  5226. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5227. ###主体列表
  5228. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5229. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5230. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5231. 姿态:站立。}{{甜心小美}}
  5232. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5233. 全景,正面拍摄,青年女性,亚洲人。
  5234. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5235. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5236. 姿态:站立。}{{阳光青年}}
  5237. ###美术风格
  5238. 基础画风风格词:厚涂古风
  5239. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5240. ###场景列表
  5241. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5242. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5243. 无人物。}";
  5244. // 构建消息
  5245. $messages = [
  5246. [
  5247. 'role' => 'system',
  5248. 'content' => $systemPrompt
  5249. ],
  5250. [
  5251. 'role' => 'user',
  5252. 'content' => "以下是文档内容:
  5253. {$content}
  5254. 用户问题:
  5255. {$question}"
  5256. ]
  5257. ];
  5258. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5259. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5260. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5261. if ($model === 'deepseek-chat') {
  5262. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5263. $model = 'deepseek-v4-flash';
  5264. $thinkingMode = 'disabled';
  5265. } elseif ($model === 'deepseek-reasoner') {
  5266. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5267. $model = 'deepseek-v4-flash';
  5268. $thinkingMode = 'enabled';
  5269. }
  5270. $post_data = [
  5271. 'model' => $model,
  5272. 'messages' => $messages,
  5273. // 'max_tokens' => 8192,
  5274. 'temperature' => 0.7,
  5275. 'frequency_penalty' => 0,
  5276. 'presence_penalty' => 0,
  5277. 'response_format' => ['type' => 'text'],
  5278. 'thinking' => ['type'=>$thinkingMode],
  5279. 'stream' => true // 启用流式输出
  5280. ];
  5281. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5282. // 根据模型类型选择调用方法
  5283. $fullContent = '';
  5284. $fullReasoningContent = '';
  5285. $usage = [];
  5286. try {
  5287. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5288. // DeepSeek 官方模型使用 DeepSeek API
  5289. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5290. } else if (in_array($model, $this->gpt_text_models)) {
  5291. // GPT-5.4 模型使用 TokenRouter API
  5292. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5293. } else if (in_array($model, $this->gemini_text_models)) {
  5294. // Gemini 模型使用 Gemini API
  5295. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5296. } else {
  5297. // 其他模型使用火山引擎API
  5298. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5299. }
  5300. // 验证返回值类型
  5301. if (!is_iterable($streamGenerator)) {
  5302. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5303. dLog('deepseek')->error('addChat流式生成器无效', [
  5304. 'generator_type' => $errorType,
  5305. 'model' => $model,
  5306. 'anime_id' => $anime_id
  5307. ]);
  5308. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5309. 'type' => $errorType,
  5310. 'model' => $model
  5311. ]);
  5312. yield [
  5313. 'type' => 'error',
  5314. 'script' => [],
  5315. 'episode' => [],
  5316. 'answer' => '',
  5317. 'reasoning' => '',
  5318. 'usage' => [],
  5319. 'error' => '接口返回数据异常,请重新请求'
  5320. ];
  5321. return;
  5322. }
  5323. // 处理流式输出
  5324. foreach ($streamGenerator as $chunk) {
  5325. if (isset($chunk['type'])) {
  5326. if ($chunk['type'] === 'done') {
  5327. // 最终结果
  5328. $fullContent = $chunk['full_content'];
  5329. $fullReasoningContent = $chunk['full_reasoning'];
  5330. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5331. } else {
  5332. // 逐块yield数据
  5333. yield $chunk;
  5334. }
  5335. }
  5336. }
  5337. } catch (\Exception $e) {
  5338. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5339. 'model' => $model,
  5340. 'anime_id' => $anime_id,
  5341. 'trace' => $e->getTraceAsString()
  5342. ]);
  5343. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5344. 'error' => $e->getMessage(),
  5345. 'model' => $model
  5346. ]);
  5347. yield [
  5348. 'type' => 'error',
  5349. 'script' => [],
  5350. 'episode' => [],
  5351. 'answer' => '',
  5352. 'reasoning' => '',
  5353. 'usage' => [],
  5354. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5355. ];
  5356. return;
  5357. }
  5358. dLog('deepseek')->info('完整内容: '.$fullContent);
  5359. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5360. // 处理完整内容并返回最终结果
  5361. $script_arr = [];
  5362. if ($fullContent) {
  5363. $script_arr = handleScriptContent($fullContent);
  5364. dLog('deepseek')->info('解析内容', $script_arr);
  5365. logDB('deepseek', 'info', '解析内容', $script_arr);
  5366. }
  5367. if (empty($script_arr['roles'])) {
  5368. // 未生成剧本相关内容,保存对话记录并返回提示
  5369. dLog('deepseek')->info('未生成剧本相关的内容');
  5370. try {
  5371. DB::beginTransaction();
  5372. $now = date('Y-m-d H:i:s');
  5373. // 保存对话记录
  5374. $records = [
  5375. [
  5376. 'uid' => $uid,
  5377. 'anime_id' => $anime_id,
  5378. 'sequence' => 0,
  5379. 'role' => 'user',
  5380. 'content' => $prompt,
  5381. 'created_at' => $now,
  5382. 'updated_at' => $now
  5383. ],
  5384. [
  5385. 'uid' => $uid,
  5386. 'anime_id' => $anime_id,
  5387. 'sequence' => 0,
  5388. 'role' => 'assistant',
  5389. // 'content' => $fullContent,
  5390. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5391. 'created_at' => $now,
  5392. 'updated_at' => $now
  5393. ]
  5394. ];
  5395. DB::table('mp_anime_records')->insert($records);
  5396. DB::commit();
  5397. } catch (\Exception $e) {
  5398. DB::rollBack();
  5399. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5400. }
  5401. yield [
  5402. 'type' => 'done',
  5403. 'script' => [],
  5404. 'episode' => [],
  5405. 'answer' => $fullContent,
  5406. 'reasoning' => $fullReasoningContent,
  5407. 'usage' => $usage,
  5408. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5409. ];
  5410. return;
  5411. }
  5412. // 如果需要生成原文内容,从script_arr中提取
  5413. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5414. $content = $script_arr['content'];
  5415. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5416. if (!$content) {
  5417. yield [
  5418. 'type' => 'done',
  5419. 'script' => [],
  5420. 'episode' => [],
  5421. 'answer' => $fullContent,
  5422. 'reasoning' => $fullReasoningContent,
  5423. 'usage' => $usage,
  5424. 'error' => '未生成剧本内容,请调整提示词再试'
  5425. ];
  5426. return;
  5427. }
  5428. }
  5429. // 替换美术风格
  5430. if ($mappedArtStyle !== '') {
  5431. $script_arr['art_style'] = $mappedArtStyle;
  5432. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5433. }
  5434. // 新建动漫
  5435. if ($user_anime_name == '新剧本策划') {
  5436. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5437. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5438. // if (!$anime_name) {
  5439. // // 未识别到剧本名,保存对话记录并返回提示
  5440. // dLog('deepseek')->info('未能识别到剧本名称');
  5441. // try {
  5442. // DB::beginTransaction();
  5443. // $now = date('Y-m-d H:i:s');
  5444. // // 保存对话记录
  5445. // $records = [
  5446. // [
  5447. // 'uid' => $uid,
  5448. // 'anime_id' => $anime_id,
  5449. // 'sequence' => 0,
  5450. // 'role' => 'user',
  5451. // 'content' => $prompt,
  5452. // 'created_at' => $now,
  5453. // 'updated_at' => $now
  5454. // ],
  5455. // [
  5456. // 'uid' => $uid,
  5457. // 'anime_id' => $anime_id,
  5458. // 'sequence' => 0,
  5459. // 'role' => 'assistant',
  5460. // 'content' => '未能生成剧本名称,请重试',
  5461. // 'created_at' => $now,
  5462. // 'updated_at' => $now
  5463. // ]
  5464. // ];
  5465. // DB::table('mp_anime_records')->insert($records);
  5466. // DB::commit();
  5467. // } catch (\Exception $e) {
  5468. // DB::rollBack();
  5469. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5470. // }
  5471. // yield [
  5472. // 'type' => 'done',
  5473. // 'script' => [],
  5474. // 'episode' => [],
  5475. // 'answer' => $fullContent,
  5476. // 'reasoning' => $fullReasoningContent,
  5477. // 'usage' => $usage,
  5478. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5479. // ];
  5480. // return;
  5481. // }
  5482. // 确认对话名称唯一性
  5483. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5484. $anime_name = $anime_name . '_' . date('YmdHis');
  5485. }
  5486. }else {
  5487. $anime_name = $user_anime_name;
  5488. }
  5489. $table_data = [
  5490. 'user_id' => $uid,
  5491. 'anime_name' => $anime_name,
  5492. 'model' => $model,
  5493. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5494. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5495. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5496. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5497. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5498. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5499. 'art_style_type' => $input_art_style,
  5500. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5501. 'status' => '解析完成',
  5502. 'content' => $content,
  5503. 'is_multi' => $is_multi,
  5504. 'ace_mode' => $ace_mode,
  5505. 'generate_status' => '待执行',
  5506. 'updated_at' => date('Y-m-d H:i:s')
  5507. ];
  5508. if ($table_data['content']) {
  5509. $chapters = splitContent($table_data['content']);
  5510. $chapter_count = count($chapters);
  5511. if ($chapter_count > 0) {
  5512. $table_data['start_episode_sequence'] = 1;
  5513. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5514. }
  5515. }
  5516. // 如果有剧本ID则进行绑定
  5517. if ($script_id) {
  5518. $table_data['script_id'] = $script_id;
  5519. }
  5520. $single_episode = [];
  5521. try {
  5522. DB::beginTransaction();
  5523. $now = date('Y-m-d H:i:s');
  5524. // 更新动漫大纲
  5525. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5526. if (!$boolen) {
  5527. dLog('deepseek')->info('动漫保存失败', $table_data);
  5528. Utils::throwError('20003:动漫保存失败');
  5529. }
  5530. // 保存对话记录
  5531. $records = [
  5532. [
  5533. 'uid' => $uid,
  5534. 'anime_id' => $anime_id,
  5535. 'sequence' => 0,
  5536. 'role' => 'user',
  5537. 'content' => $prompt,
  5538. 'created_at' => date('Y-m-d H:i:s'),
  5539. 'updated_at' => date('Y-m-d H:i:s')
  5540. ],
  5541. [
  5542. 'uid' => $uid,
  5543. 'anime_id' => $anime_id,
  5544. 'sequence' => 0,
  5545. 'role' => 'assistant',
  5546. 'content' => $fullContent,
  5547. 'created_at' => date('Y-m-d H:i:s'),
  5548. 'updated_at' => date('Y-m-d H:i:s')
  5549. ]
  5550. ];
  5551. // 保存对话记录
  5552. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5553. if (!$boolen3) {
  5554. Utils::throwError('20003:对话记录保存失败');
  5555. }
  5556. if ($is_single) {
  5557. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5558. if (empty($episode_arr['acts'])) {
  5559. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5560. }
  5561. $saveResult = $this->saveEpisodeVersionData(
  5562. $anime_id,
  5563. 1,
  5564. $episode_arr,
  5565. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5566. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5567. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5568. null,
  5569. null,
  5570. false,
  5571. $content,
  5572. $now
  5573. );
  5574. $single_episode = $saveResult['episode'];
  5575. $episode_id = $saveResult['episode_id'];
  5576. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5577. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5578. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5579. 'props' => json_encode($saveResult['merged_props'], 256),
  5580. 'updated_at' => $now
  5581. ]);
  5582. if ($boolen5 === false) {
  5583. Utils::throwError('20003:单剧集主表资源同步失败');
  5584. }
  5585. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5586. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5587. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5588. $episode_record_content = '确认分镜大纲';
  5589. if ($content !== '') {
  5590. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5591. }
  5592. $episode_records = [
  5593. [
  5594. 'uid' => $uid,
  5595. 'anime_id' => $anime_id,
  5596. 'role' => 'user',
  5597. 'content' => $episode_record_content,
  5598. 'sequence' => 1,
  5599. 'episode_id' => $episode_id,
  5600. 'created_at' => $now,
  5601. 'updated_at' => $now
  5602. ],
  5603. [
  5604. 'uid' => $uid,
  5605. 'anime_id' => $anime_id,
  5606. 'role' => 'assistant',
  5607. 'content' => $fullContent,
  5608. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5609. 'sequence' => 1,
  5610. 'episode_id' => $episode_id,
  5611. 'created_at' => $now,
  5612. 'updated_at' => $now
  5613. ]
  5614. ];
  5615. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5616. if (!$boolen4) {
  5617. Utils::throwError('20003:单剧集分镜记录保存失败');
  5618. }
  5619. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5620. if ($is_single && !empty($single_episode)) {
  5621. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5622. 'anime_id' => $anime_id,
  5623. 'episode_id' => $episode_id ?? 0,
  5624. 'model' => $model,
  5625. 'source' => 'addChat',
  5626. ]);
  5627. }
  5628. }
  5629. }catch (\Exception $e) {
  5630. DB::rollBack();
  5631. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5632. yield [
  5633. 'type' => 'done',
  5634. 'answer' => $fullContent,
  5635. 'reasoning' => $fullReasoningContent,
  5636. 'usage' => $usage,
  5637. 'error' => $e->getMessage(),
  5638. ];
  5639. return;
  5640. }
  5641. DB::commit();
  5642. dLog('deepseek')->info('保存完毕');
  5643. if ($is_single && !empty($single_episode)) {
  5644. // $this->batchSetGlobalRoleImg([
  5645. // 'anime_id' => $anime_id,
  5646. // ]);
  5647. // $this->batchSetGlobalSceneImg([
  5648. // 'anime_id' => $anime_id,
  5649. // ]);
  5650. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5651. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5652. }
  5653. $table_data['anime_id'] = $anime_id;
  5654. $table_data['roles'] = json_decode($table_data['roles'], true);
  5655. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5656. // $table_data['episodes'] = $script_arr['episodes'];
  5657. unset($table_data['created_at']);
  5658. unset($table_data['updated_at']);
  5659. unset($table_data['status']);
  5660. dLog('deepseek')->info('开始返回');
  5661. yield [
  5662. 'type' => 'done',
  5663. 'script' => $table_data,
  5664. 'episode' => $single_episode,
  5665. 'answer' => $fullContent,
  5666. 'reasoning' => $fullReasoningContent,
  5667. 'usage' => $usage
  5668. ];
  5669. }
  5670. public function reGenerateAnime($data) {
  5671. $uid = Site::getUid();
  5672. $file = getProp($data, 'file');
  5673. $content = getProp($data, 'content', '');
  5674. $bid = getProp($data, 'bid', 0);
  5675. $script_id = getProp($data, 'script_id', 0);
  5676. $anime_id = getProp($data, 'anime_id');
  5677. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5678. if (!$anime) {
  5679. Utils::throwError('20003:该对话不存在');
  5680. }
  5681. $user_anime_name = getProp($anime, 'anime_name');
  5682. $prompt = getProp($data, 'prompt');
  5683. // 处理文本模型
  5684. $model = getProp($data, 'model');
  5685. if (!$model) {
  5686. // 用户没有输入,从anime表获取
  5687. $model = getProp($anime, 'model');
  5688. if (!$model) {
  5689. // anime表也没有,使用默认值
  5690. $model = 'doubao-seed-2-0-mini-260215';
  5691. }
  5692. }
  5693. // 验证模型是否在可用模型表中
  5694. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5695. $model = 'doubao-seed-2-0-mini-260215';
  5696. }
  5697. $is_multi = getProp($anime, 'is_multi', 1);
  5698. $is_single = (int)$is_multi !== 1;
  5699. // 积分余额预检(仅单剧集模式收费)
  5700. if ($is_single) {
  5701. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5702. }
  5703. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5704. if ($is_single) {
  5705. $episode_exists = DB::table('mp_anime_episodes')
  5706. ->where('anime_id', $anime_id)
  5707. ->where('sequence', 1)
  5708. ->exists();
  5709. if ($episode_exists) {
  5710. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5711. }
  5712. }
  5713. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5714. if ($prompt) {
  5715. $question .= "本次修改要求如下:\n{$prompt}";
  5716. }
  5717. // 提取文件内容
  5718. if ($file) {
  5719. $content = $this->extractFileContent($file);
  5720. if (!$content) {
  5721. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5722. }
  5723. } elseif ($script_id) {
  5724. $content = $this->getContentByScriptId($script_id);
  5725. if (!$content) {
  5726. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5727. }
  5728. } elseif ($bid) {
  5729. $content = $this->getContentByBid($bid);
  5730. if (!$content) {
  5731. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5732. }
  5733. } elseif ($content) {
  5734. $content = filterContent($content);
  5735. }else {
  5736. $content = filterContent(getProp($anime, 'content'));
  5737. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5738. $need_generate_content = true;
  5739. }
  5740. }
  5741. // 判断是否需要生成原文内容
  5742. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5743. // 如果需要生成原文内容,添加额外的要求
  5744. $content_generation_requirement = $need_generate_content
  5745. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5746. : "";
  5747. // 美术风格
  5748. $input_art_style = getProp($anime, 'art_style');
  5749. if (!$input_art_style) {
  5750. $input_art_style = getProp($data, 'art_style');
  5751. }
  5752. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5753. // 美术风格
  5754. if (!$mappedArtStyle) {
  5755. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5756. }else {
  5757. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5758. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5759. }else {
  5760. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5761. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5762. }
  5763. }
  5764. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5765. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5766. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5767. 中年女:邻居阿姨
  5768. 老年男:幽默大爷
  5769. 老年女:婆婆
  5770. 萌娃:奶气萌娃";
  5771. $system_message = ['role'=>'system', 'content'=>$is_single
  5772. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5773. 强制要求:
  5774. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5775. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5776. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5777. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5778. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5779. 普通要求:
  5780. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5781. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5782. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5783. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5784. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5785. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5786. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5787. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5788. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5789. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5790. 3.$mappedArtStyle_prompt\n\n
  5791. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5792. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5793. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5794. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5795. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5796. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5797. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5798. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5799. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5800. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5801. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5802. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5803. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5804. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5805. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5806. 示例如下:\n
  5807. ###剧本名:西昆仑
  5808. ###故事梗概
  5809. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5810. ###剧本亮点
  5811. 亮点1:绝境奇药,生死一线
  5812. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5813. 亮点2:结拜兄妹,化解尴尬
  5814. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5815. 亮点3:纤发夺命,情愫暗涌
  5816. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5817. ###人物关系
  5818. 阿雪与梁萧之间存在兄妹之情。
  5819. ###核心矛盾
  5820. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5821. ###主体列表
  5822. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5823. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5824. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5825. 姿态:站立。}{{甜心小美}}
  5826. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5827. 全景,正面拍摄,青年女性,亚洲人。
  5828. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5829. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5830. 姿态:站立。}{{阳光青年}}
  5831. ###美术风格
  5832. 基础画风风格词:厚涂古风
  5833. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5834. ###场景列表
  5835. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5836. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5837. 无人物。}
  5838. ###分镜剧本
  5839. ##第1幕:徐家老旧厨房 白天 室内
  5840. 分镜1
  5841. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5842. 场景:徐家老旧厨房
  5843. 构图设计:全景,低角度仰视
  5844. 运镜调度:手持拍摄
  5845. 配音角色:旁白
  5846. 出镜角色:许芸-校服装、徐母
  5847. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5848. 画面类型:普通画面
  5849. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5850. 分镜2
  5851. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5852. 场景:徐家老旧厨房
  5853. 构图设计:近景,徐母面部特写
  5854. 运镜调度:固定镜头
  5855. 配音角色:徐母
  5856. 出镜角色:徐母
  5857. 台词内容:问我夜不归宿死哪儿去了。
  5858. 画面类型:对口型
  5859. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5860. ##第2幕:徐家简陋客厅 黄昏 室内
  5861. 分镜3
  5862. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5863. 场景:徐家简陋客厅
  5864. 构图设计:全景,景深虚化
  5865. 运镜调度:固定镜头
  5866. 配音角色:旁白
  5867. 出镜角色:无
  5868. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5869. 画面类型:普通画面
  5870. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5871. 分镜4
  5872. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5873. 场景:徐家简陋客厅
  5874. 构图设计:特写,火车票
  5875. 运镜调度:固定镜头
  5876. 配音角色:旁白
  5877. 出镜角色:无
  5878. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5879. 画面类型:普通画面
  5880. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5881. "
  5882. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5883. 强制要求:\n
  5884. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5885. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5886. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5887. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5888. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5889. 普通要求:\n
  5890. 1.剧本名(必须生成)必须与文档内容高度相关
  5891. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5892. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5893. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5894. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5895. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5896. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5897. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5898. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5899. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5900. 4.$mappedArtStyle_prompt\n\n
  5901. 示例如下:\n
  5902. ###剧本名:西昆仑
  5903. ###故事梗概
  5904. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5905. ###剧本亮点
  5906. 亮点1:绝境奇药,生死一线
  5907. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5908. 亮点2:结拜兄妹,化解尴尬
  5909. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5910. 亮点3:纤发夺命,情愫暗涌
  5911. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5912. ###人物关系
  5913. 阿雪与梁萧之间存在兄妹之情。
  5914. ###核心矛盾
  5915. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5916. ###主体列表
  5917. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5918. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5919. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5920. 姿态:站立。}{{甜心小美}}
  5921. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5922. 全景,正面拍摄,青年女性,亚洲人。
  5923. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5924. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5925. 姿态:站立。}{{阳光青年}}
  5926. ###美术风格
  5927. 基础画风风格词:厚涂古风
  5928. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5929. ###场景列表
  5930. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5931. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5932. 无人物。}"];
  5933. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5934. $episode_count = $this->extractEpisodeNumber($prompt);
  5935. if ((int)getProp($anime, 'is_multi') !== 1) {
  5936. yield [
  5937. 'type' => 'done',
  5938. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5939. 'reasoning' => '',
  5940. 'usage' => []
  5941. ];
  5942. return;
  5943. }
  5944. if ($episode_count) {
  5945. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5946. $system_message = [
  5947. 'role' => 'system',
  5948. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5949. 强制要求:\n
  5950. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5951. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5952. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5953. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5954. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5955. 普通要求:\n
  5956. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5957. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5958. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5959. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5960. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5961. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5962. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5963. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5964. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5965. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5966. 示例如下:\n
  5967. ###剧本名:西昆仑
  5968. ###故事梗概
  5969. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5970. ###剧本亮点
  5971. 亮点1:绝境奇药,生死一线
  5972. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5973. 亮点2:结拜兄妹,化解尴尬
  5974. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5975. 亮点3:纤发夺命,情愫暗涌
  5976. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5977. ###人物关系
  5978. 阿雪与梁萧之间存在兄妹之情。
  5979. ###核心矛盾
  5980. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5981. ###主体列表
  5982. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5983. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5984. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5985. 姿态:站立。}{{甜心小美}}
  5986. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5987. 全景,正面拍摄,青年女性,亚洲人。
  5988. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5989. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5990. 姿态:站立。}{{阳光青年}}
  5991. ###美术风格
  5992. 基础画风风格词:厚涂古风
  5993. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5994. ###场景列表
  5995. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5996. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5997. 无人物。}
  5998. ###分集详细内容
  5999. ##第1章 重生
  6000. 我重生了。
  6001. 源于一个男人偏执的暗恋。
  6002. ##第2章 相救
  6003. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6004. 我眼睛扫向站在锅炉后的卞大伟。"
  6005. ];
  6006. // 构建消息
  6007. $messages = [
  6008. $system_message,
  6009. [
  6010. 'role' => 'user',
  6011. 'content' => "以下是文档内容:
  6012. {$content}
  6013. 用户问题:
  6014. {$question}"
  6015. ]
  6016. ];
  6017. }else {
  6018. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6019. // 构建消息
  6020. $messages = [
  6021. $system_message,
  6022. [
  6023. 'role' => 'user',
  6024. 'content' => "以下是文档内容:
  6025. {$content}
  6026. 用户问题:
  6027. {$question}"
  6028. ]
  6029. ];
  6030. }else {
  6031. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6032. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6033. return (array)$value;
  6034. })->toArray();
  6035. array_unshift($messages, $system_message);
  6036. $messages[] = [
  6037. 'role' => 'user',
  6038. 'content' => $prompt
  6039. ];
  6040. }
  6041. }
  6042. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6043. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6044. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6045. if ($model === 'deepseek-chat') {
  6046. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6047. $model = 'deepseek-v4-flash';
  6048. $thinkingMode = 'disabled';
  6049. } elseif ($model === 'deepseek-reasoner') {
  6050. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6051. $model = 'deepseek-v4-flash';
  6052. $thinkingMode = 'enabled';
  6053. }
  6054. $post_data = [
  6055. 'model' => $model,
  6056. 'messages' => $messages,
  6057. // 'max_tokens' => 8192,
  6058. 'temperature' => 0.7,
  6059. 'frequency_penalty' => 0,
  6060. 'presence_penalty' => 0,
  6061. 'response_format' => ['type' => 'text'],
  6062. 'thinking' => ['type' => $thinkingMode],
  6063. 'stream' => true // 启用流式输出
  6064. ];
  6065. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6066. // 根据模型类型选择调用方法
  6067. $fullContent = '';
  6068. $fullReasoningContent = '';
  6069. $usage = [];
  6070. // dd($post_data);
  6071. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6072. try {
  6073. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6074. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6075. } else if (in_array($model, $this->gpt_text_models)) {
  6076. // GPT-5.4 模型使用 TokenRouter API
  6077. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6078. } else if (in_array($model, $this->gemini_text_models)) {
  6079. // Gemini 模型使用 Gemini API
  6080. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6081. } else {
  6082. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6083. }
  6084. // 验证返回值类型
  6085. if (!is_iterable($streamGenerator)) {
  6086. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6087. dLog('deepseek')->error('方法名流式生成器无效', [
  6088. 'generator_type' => $errorType,
  6089. 'model' => $model,
  6090. // 添加其他上下文信息
  6091. ]);
  6092. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6093. 'type' => $errorType,
  6094. 'model' => $model
  6095. ]);
  6096. yield [
  6097. 'type' => 'error',
  6098. // 根据方法返回相应的空数据结构
  6099. 'answer' => '',
  6100. 'reasoning' => '',
  6101. 'usage' => [],
  6102. 'error' => '接口返回数据异常,请重新请求'
  6103. ];
  6104. return;
  6105. }
  6106. // 处理流式输出
  6107. foreach ($streamGenerator as $chunk) {
  6108. if (isset($chunk['type'])) {
  6109. if ($chunk['type'] === 'done') {
  6110. $fullContent = $chunk['full_content'];
  6111. $fullReasoningContent = $chunk['full_reasoning'];
  6112. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6113. } else {
  6114. yield $chunk;
  6115. }
  6116. }
  6117. }
  6118. } catch (\Exception $e) {
  6119. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6120. 'model' => $model,
  6121. 'trace' => $e->getTraceAsString()
  6122. ]);
  6123. logDB('deepseek', 'error', '方法名流式处理失败', [
  6124. 'error' => $e->getMessage(),
  6125. 'model' => $model
  6126. ]);
  6127. yield [
  6128. 'type' => 'error',
  6129. // 根据方法返回相应的空数据结构
  6130. 'answer' => '',
  6131. 'reasoning' => '',
  6132. 'usage' => [],
  6133. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6134. ];
  6135. return;
  6136. }
  6137. dLog('deepseek')->info('完整内容: '.$fullContent);
  6138. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6139. // 处理完整内容并返回最终结果
  6140. $script_arr = [];
  6141. if ($fullContent) {
  6142. $script_arr = handleScriptContent($fullContent);
  6143. dLog('deepseek')->info('解析内容', $script_arr);
  6144. logDB('deepseek', 'info', '解析内容', $script_arr);
  6145. }
  6146. if (empty($script_arr['roles'])) {
  6147. // 未生成剧本相关内容,保存对话记录并返回提示
  6148. dLog('deepseek')->info('未生成剧本相关的内容');
  6149. try {
  6150. $now = date('Y-m-d H:i:s');
  6151. // 保存对话记录
  6152. $records = [
  6153. [
  6154. 'uid' => $uid,
  6155. 'anime_id' => $anime_id,
  6156. 'sequence' => 0,
  6157. 'role' => 'user',
  6158. 'content' => $prompt,
  6159. 'created_at' => $now,
  6160. 'updated_at' => $now
  6161. ],
  6162. [
  6163. 'uid' => $uid,
  6164. 'anime_id' => $anime_id,
  6165. 'sequence' => 0,
  6166. 'role' => 'assistant',
  6167. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6168. 'created_at' => $now,
  6169. 'updated_at' => $now
  6170. ]
  6171. ];
  6172. DB::table('mp_anime_records')->insert($records);
  6173. } catch (\Exception $e) {
  6174. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6175. }
  6176. yield [
  6177. 'type' => 'done',
  6178. 'script' => [],
  6179. 'episode' => [],
  6180. 'answer' => $fullContent,
  6181. 'reasoning' => $fullReasoningContent,
  6182. 'usage' => $usage,
  6183. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6184. ];
  6185. return;
  6186. }
  6187. // 替换美术风格
  6188. if ($mappedArtStyle !== '') {
  6189. $script_arr['art_style'] = $mappedArtStyle;
  6190. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6191. }
  6192. if ($user_anime_name != '新剧本策划') {
  6193. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6194. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6195. // 确认对话名称唯一性
  6196. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6197. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6198. }
  6199. }else {
  6200. $anime_name = $user_anime_name;
  6201. }
  6202. $table_data = [
  6203. 'user_id' => $uid,
  6204. 'model' => $model,
  6205. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6206. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6207. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6208. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6209. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6210. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6211. 'art_style_type' => $input_art_style,
  6212. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6213. 'status' => '解析完成',
  6214. 'generate_status' => '待执行',
  6215. 'updated_at' => date('Y-m-d H:i:s')
  6216. ];
  6217. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6218. // 如果是修改集数,则将content内容更新(会改变原文)
  6219. if (isset($episode_count) && $episode_count > 0) {
  6220. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6221. $table_data['start_episode_sequence'] = 1;
  6222. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6223. }else {
  6224. // 如果需要生成原文内容,从script_arr中提取
  6225. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6226. $table_data['content'] = $script_arr['content'];
  6227. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6228. if (!$table_data['content']) {
  6229. yield [
  6230. 'type' => 'done',
  6231. 'script' => [],
  6232. 'episode' => [],
  6233. 'answer' => $fullContent,
  6234. 'reasoning' => $fullReasoningContent,
  6235. 'usage' => $usage,
  6236. 'error' => '未生成剧本内容,请调整提示词再试'
  6237. ];
  6238. return;
  6239. }
  6240. }
  6241. if (isset($table_data['content']) && $table_data['content']) {
  6242. $chapters = splitContent($table_data['content']);
  6243. $chapter_count = count($chapters);
  6244. if ($chapter_count > 0) {
  6245. $table_data['start_episode_sequence'] = 1;
  6246. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6247. }
  6248. }
  6249. }
  6250. $single_episode = [];
  6251. try {
  6252. DB::beginTransaction();
  6253. $now = date('Y-m-d H:i:s');
  6254. // 更新动漫大纲
  6255. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6256. if (!$boolen) {
  6257. dLog('deepseek')->info('对话修改失败', $table_data);
  6258. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6259. Utils::throwError('20003:对话修改失败');
  6260. }
  6261. // 保存对话记录
  6262. $records = [
  6263. [
  6264. 'uid' => $uid,
  6265. 'anime_id' => $anime_id,
  6266. 'sequence' => 0,
  6267. 'role' => 'user',
  6268. 'content' => $prompt,
  6269. 'created_at' => $now,
  6270. 'updated_at' => $now
  6271. ],
  6272. [
  6273. 'uid' => $uid,
  6274. 'anime_id' => $anime_id,
  6275. 'sequence' => 0,
  6276. 'role' => 'assistant',
  6277. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6278. 'content' => $fullContent,
  6279. 'created_at' => $now,
  6280. 'updated_at' => $now
  6281. ]
  6282. ];
  6283. // 保存对话记录
  6284. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6285. if (!$boolen3) {
  6286. Utils::throwError('20003:对话记录保存失败');
  6287. }
  6288. // 单剧集模式:生成并保存剧集信息
  6289. if ($is_single) {
  6290. $anime_name = getProp($anime, 'anime_name', '未命名');
  6291. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6292. if (empty($episode_arr['acts'])) {
  6293. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6294. }
  6295. $saveResult = $this->saveEpisodeVersionData(
  6296. $anime_id,
  6297. 1,
  6298. $episode_arr,
  6299. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6300. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6301. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6302. null,
  6303. null,
  6304. false,
  6305. $content,
  6306. $now
  6307. );
  6308. $single_episode = $saveResult['episode'];
  6309. $episode_id = $saveResult['episode_id'];
  6310. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6311. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6312. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6313. 'props' => json_encode($saveResult['merged_props'], 256),
  6314. 'updated_at' => $now
  6315. ]);
  6316. if ($boolen5 === false) {
  6317. Utils::throwError('20003:单剧集主表资源同步失败');
  6318. }
  6319. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6320. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6321. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6322. $episode_record_content = '确认分镜大纲';
  6323. if ($content !== '') {
  6324. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6325. }
  6326. $episode_records = [
  6327. [
  6328. 'uid' => $uid,
  6329. 'anime_id' => $anime_id,
  6330. 'role' => 'user',
  6331. 'content' => $episode_record_content,
  6332. 'sequence' => 1,
  6333. 'episode_id' => $episode_id,
  6334. 'created_at' => $now,
  6335. 'updated_at' => $now
  6336. ],
  6337. [
  6338. 'uid' => $uid,
  6339. 'anime_id' => $anime_id,
  6340. 'role' => 'assistant',
  6341. 'content' => $fullContent,
  6342. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6343. 'sequence' => 1,
  6344. 'episode_id' => $episode_id,
  6345. 'created_at' => $now,
  6346. 'updated_at' => $now
  6347. ]
  6348. ];
  6349. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6350. if (!$boolen4) {
  6351. Utils::throwError('20003:单剧集分镜记录保存失败');
  6352. }
  6353. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6354. if ($is_single && !empty($single_episode)) {
  6355. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6356. 'anime_id' => $anime_id,
  6357. 'episode_id' => $episode_id ?? 0,
  6358. 'model' => $model,
  6359. 'source' => 'reGenerateAnime',
  6360. ]);
  6361. }
  6362. }
  6363. }catch (\Exception $e) {
  6364. DB::rollBack();
  6365. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6366. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6367. yield [
  6368. 'type' => 'done',
  6369. 'answer' => $fullContent,
  6370. 'reasoning' => $fullReasoningContent,
  6371. 'usage' => $usage,
  6372. 'error' => $e->getMessage(),
  6373. ];
  6374. return;
  6375. }
  6376. DB::commit();
  6377. dLog('deepseek')->info('保存完毕');
  6378. if ($is_single && !empty($single_episode)) {
  6379. // $this->batchSetGlobalRoleImg([
  6380. // 'anime_id' => $anime_id,
  6381. // ]);
  6382. // $this->batchSetGlobalSceneImg([
  6383. // 'anime_id' => $anime_id,
  6384. // ]);
  6385. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6386. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6387. }
  6388. $table_data['anime_id'] = $anime_id;
  6389. $table_data['roles'] = json_decode($table_data['roles'], true);
  6390. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6391. unset($table_data['updated_at']);
  6392. unset($table_data['status']);
  6393. yield [
  6394. 'type' => 'done',
  6395. 'script' => $table_data,
  6396. 'episode' => $single_episode,
  6397. 'answer' => $fullContent,
  6398. 'reasoning' => $fullReasoningContent,
  6399. 'usage' => $usage
  6400. ];
  6401. }
  6402. public function chat($data) {
  6403. $uid = Site::getUid();
  6404. // 积分余额预检(不足直接报错)
  6405. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6406. $anime_id = getProp($data, 'anime_id');
  6407. $file = getProp($data, 'file');
  6408. $content = getProp($data, 'content', '');
  6409. $bid = getProp($data, 'bid', 0);
  6410. $script_id = getProp($data, 'script_id', 0);
  6411. $episode_number = getProp($data, 'episode_number', 1);
  6412. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6413. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6414. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6415. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6416. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6417. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6418. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6419. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6420. $roles = is_array($roles) ? $roles : [];
  6421. $scenes = is_array($scenes) ? $scenes : [];
  6422. // 获取最后一集序号
  6423. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6424. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6425. // 转换主体列表和场景列表的格式
  6426. // 获取参考主体或场景
  6427. if ((int)$episode_number === 1) {
  6428. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6429. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6430. }else {
  6431. $prev_episode_number = $episode_number - 1;
  6432. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6433. }
  6434. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6435. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6436. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6437. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6438. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6439. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6440. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6441. 中年女:邻居阿姨
  6442. 老年男:幽默大爷
  6443. 老年女:婆婆
  6444. 萌娃:奶气萌娃";
  6445. if ($roles_content) {
  6446. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6447. 主体范围:\n {$roles_content}\n
  6448. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6449. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6450. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6451. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6452. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6453. }else {
  6454. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6455. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6456. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6457. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6458. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6459. }
  6460. if ($scenes_content) {
  6461. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6462. 场景范围:\n {$scenes_content}\n
  6463. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6464. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6465. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6466. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6467. }else {
  6468. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6469. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6470. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6471. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6472. }
  6473. // 提取文件内容
  6474. if ($file) {
  6475. $uploaded_content = $this->extractFileContent($file);
  6476. if (!$uploaded_content) {
  6477. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6478. }
  6479. } elseif ($script_id) {
  6480. $uploaded_content = $this->getContentByScriptId($script_id);
  6481. if (!$uploaded_content) {
  6482. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6483. }
  6484. } elseif ($bid) {
  6485. $uploaded_content = $this->getContentByBid($bid);
  6486. if (!$uploaded_content) {
  6487. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6488. }
  6489. } elseif ($content) {
  6490. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6491. }
  6492. // elseif ($prompt) {
  6493. // $uploaded_content = filterContent($prompt);
  6494. // }
  6495. else {
  6496. $uploaded_content = '';
  6497. }
  6498. $input_art_style = getProp($anime, 'art_style');
  6499. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6500. // 美术风格
  6501. if (!$mappedArtStyle) {
  6502. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6503. }else {
  6504. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6505. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6506. }else {
  6507. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6508. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6509. }
  6510. }
  6511. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6512. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6513. // 强制要求:
  6514. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6515. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6516. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6517. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6518. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6519. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6520. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6521. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6522. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6523. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6524. // - 分镜要和场景列表、人物主体保持一致\n
  6525. // 普通要求:
  6526. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6527. // {$role_demo}
  6528. // {$scene_demo}
  6529. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6530. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6531. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6532. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6533. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6534. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6535. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6536. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6537. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6538. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6539. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6540. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6541. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6542. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6543. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6544. // 5.$mappedArtStyle_prompt\n\n
  6545. // 示例格式:\n
  6546. // 第1集:隐形的守护者
  6547. // ###故事梗概
  6548. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6549. // ###美术风格
  6550. // 基础画风风格词:韩漫二次元
  6551. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6552. // ###主体列表
  6553. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6554. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6555. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6556. // ###场景列表
  6557. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6558. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6559. // 无人物。}
  6560. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6561. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6562. // 无人物。}
  6563. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6564. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6565. // 无人物。}
  6566. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6567. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6568. // 无人物。}
  6569. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6570. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6571. // 无人物。}
  6572. // ###分镜剧本
  6573. // ##第1幕:徐家老旧厨房 白天 室内
  6574. // 分镜1
  6575. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6576. // 场景:徐家老旧厨房
  6577. // 构图设计:全景,低角度仰视
  6578. // 运镜调度:手持拍摄
  6579. // 配音角色:旁白
  6580. // 出镜角色:许芸-校服装、徐母
  6581. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6582. // 画面类型:普通画面
  6583. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6584. // 分镜2
  6585. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6586. // 场景:徐家老旧厨房
  6587. // 构图设计:近景,徐母面部特写
  6588. // 运镜调度:固定镜头
  6589. // 配音角色:徐母
  6590. // 出镜角色:徐母
  6591. // 台词内容:问我夜不归宿死哪儿去了。
  6592. // 画面类型:对口型
  6593. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6594. // ##第2幕:徐家简陋客厅 黄昏 室内
  6595. // 分镜3
  6596. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6597. // 场景:徐家简陋客厅
  6598. // 构图设计:全景,景深虚化
  6599. // 运镜调度:固定镜头
  6600. // 配音角色:旁白
  6601. // 出镜角色:无
  6602. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6603. // 画面类型:普通画面
  6604. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6605. // 分镜4
  6606. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6607. // 场景:徐家简陋客厅
  6608. // 构图设计:特写,火车票
  6609. // 运镜调度:固定镜头
  6610. // 配音角色:旁白
  6611. // 出镜角色:无
  6612. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6613. // 画面类型:普通画面
  6614. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6615. // \n\n";
  6616. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6617. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6618. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6619. 普通要求:
  6620. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6621. {$role_demo}
  6622. {$scene_demo}
  6623. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6624. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6625. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6626. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6627. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6628. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6629. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6630. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6631. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6632. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6633. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6634. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6635. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6636. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6637. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6638. 5.$mappedArtStyle_prompt
  6639. 6.《情绪-视听语言映射表》:
  6640. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6641. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6642. -----|---------|------------|----------------
  6643. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6644. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6645. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6646. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6647. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6648. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6649. -----|---------|------------|----------------
  6650. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6651. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6652. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6653. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6654. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6655. --------|---------|--------------|-------------
  6656. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6657. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6658. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6659. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6660. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6661. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6662. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6663. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6664. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6665. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6666. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6667. -----|---------|------------|------------
  6668. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6669. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6670. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6671. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6672. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6673. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6674. --------|---------|--------------|----------
  6675. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6676. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6677. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6678. 6.6 声音设计与潜意识影响 (Soundscape)
  6679. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6680. -----|---------|------------|------------------
  6681. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6682. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6683. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6684. 理论基石:
  6685. - The Five C's of Cinematography by Joseph V. Mascelli
  6686. - Film Art: An Introduction by David Bordwell
  6687. - Sight, Sound, Motion by Herbert Zettl
  6688. - Notes on the Cinematograph by Robert Bresson
  6689. \n\n
  6690. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6691. 示例格式:\n
  6692. 第1集:隐形的守护者
  6693. ###故事梗概
  6694. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6695. ###美术风格
  6696. 基础画风风格词:韩漫二次元
  6697. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6698. ###主体列表
  6699. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6700. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6701. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6702. ###场景列表
  6703. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6704. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6705. 无人物。}
  6706. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6707. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6708. 无人物。}
  6709. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6710. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6711. 无人物。}
  6712. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6713. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6714. 无人物。}
  6715. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6716. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6717. 无人物。}
  6718. ###分镜剧本
  6719. ##第1幕:徐家老旧厨房 白天 室内
  6720. 分镜1
  6721. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6722. 场景:徐家老旧厨房
  6723. 构图设计:全景,低角度仰视
  6724. 运镜调度:手持拍摄
  6725. 配音角色:旁白
  6726. 出镜角色:许芸-校服装、徐母
  6727. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6728. 画面类型:普通画面
  6729. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6730. 分镜2
  6731. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6732. 场景:徐家老旧厨房
  6733. 构图设计:近景,徐母面部特写
  6734. 运镜调度:固定镜头
  6735. 配音角色:徐母
  6736. 出镜角色:徐母
  6737. 台词内容:问我夜不归宿死哪儿去了。
  6738. 画面类型:对口型
  6739. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6740. ##第2幕:徐家简陋客厅 黄昏 室内
  6741. 分镜3
  6742. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6743. 场景:徐家简陋客厅
  6744. 构图设计:全景,景深虚化
  6745. 运镜调度:固定镜头
  6746. 配音角色:旁白
  6747. 出镜角色:无
  6748. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6749. 画面类型:普通画面
  6750. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6751. 分镜4
  6752. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6753. 场景:徐家简陋客厅
  6754. 构图设计:特写,火车票
  6755. 运镜调度:固定镜头
  6756. 配音角色:旁白
  6757. 出镜角色:无
  6758. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6759. 画面类型:普通画面
  6760. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6761. \n\n";
  6762. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6763. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6764. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6765. $prompt = $origin_prompt;
  6766. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6767. // 获取章节内容
  6768. $full_content = getProp($anime, 'content');
  6769. if ($uploaded_content) {
  6770. $full_content = $uploaded_content;
  6771. }
  6772. // 根据章节内容拆分章节
  6773. $chapters = splitContent($full_content);
  6774. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6775. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6776. $messages = [];
  6777. if ($prompt == '确认分镜大纲') {
  6778. // 暂时保留
  6779. $content = $chapter_content;
  6780. if ($is_single) $content = $full_content; // 单剧集使用全文
  6781. if (!$content) {
  6782. Utils::throwError('20003:章节内容无法获取,请确认');
  6783. }
  6784. $question = $is_single
  6785. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6786. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6787. // 构建消息
  6788. $messages[] =
  6789. [
  6790. 'role' => 'user',
  6791. 'content' => $question
  6792. ];
  6793. }else if ($prompt == '继续策划下一集') {
  6794. if ($is_single) {
  6795. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6796. }
  6797. $content = $chapter_content;
  6798. if (!$content) {
  6799. Utils::throwError('20003:章节内容无法获取,请确认');
  6800. }
  6801. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6802. // 获取上一集最后记录
  6803. $prev_sequence = $episode_number - 1;
  6804. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6805. // 构建消息
  6806. $messages[] =
  6807. [
  6808. 'role' => 'user',
  6809. 'content' => $question
  6810. ];
  6811. }else {
  6812. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6813. if (!$content) {
  6814. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6815. }
  6816. if (!$content) {
  6817. Utils::throwError('20003:章节内容无法获取,请确认');
  6818. }
  6819. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6820. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6821. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6822. if ($origin_prompt) {
  6823. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6824. }
  6825. $messages[] =
  6826. [
  6827. 'role' => 'user',
  6828. 'content' => $question
  6829. ];
  6830. }
  6831. // 处理文本模型
  6832. $model = getProp($data, 'model');
  6833. if (!$model) {
  6834. // 用户没有输入,从anime表获取
  6835. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6836. $model = getProp($anime, 'model');
  6837. if (!$model) {
  6838. // anime表也没有,使用默认值
  6839. $model = 'doubao-seed-2-0-mini-260215';
  6840. }
  6841. }
  6842. // 验证模型是否在可用模型表中
  6843. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6844. $model = 'doubao-seed-2-0-mini-260215';
  6845. }
  6846. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6847. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6848. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6849. if ($model === 'deepseek-chat') {
  6850. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6851. $model = 'deepseek-v4-flash';
  6852. $thinkingMode = 'disabled';
  6853. } elseif ($model === 'deepseek-reasoner') {
  6854. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6855. $model = 'deepseek-v4-flash';
  6856. $thinkingMode = 'enabled';
  6857. }
  6858. $post_data = [
  6859. 'model' => $model,
  6860. 'messages' => $messages,
  6861. // 'max_tokens' => 8192,
  6862. 'temperature' => 0.2,
  6863. 'frequency_penalty' => 0,
  6864. 'presence_penalty' => 0,
  6865. 'response_format' => ['type' => 'text'],
  6866. 'thinking' => ['type' => $thinkingMode],
  6867. 'stream' => true // 启用流式输出
  6868. ];
  6869. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6870. // 根据模型类型选择调用方法
  6871. $fullContent = '';
  6872. $fullReasoningContent = '';
  6873. $usage = [];
  6874. try {
  6875. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6876. // DeepSeek 官方模型使用 DeepSeek API
  6877. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6878. } else if (in_array($model, $this->gpt_text_models)) {
  6879. // GPT-5.4 模型使用 TokenRouter API
  6880. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6881. } else if (in_array($model, $this->gemini_text_models)) {
  6882. // Gemini 模型使用 Gemini API
  6883. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6884. } else {
  6885. // 其他模型使用火山引擎API
  6886. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6887. }
  6888. // 验证返回值类型
  6889. if (!is_iterable($streamGenerator)) {
  6890. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6891. dLog('deepseek')->error('chat流式生成器无效', [
  6892. 'generator_type' => $errorType,
  6893. 'model' => $model,
  6894. 'anime_id' => $anime_id,
  6895. 'episode_number' => $episode_number
  6896. ]);
  6897. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6898. 'type' => $errorType,
  6899. 'model' => $model
  6900. ]);
  6901. yield [
  6902. 'type' => 'error',
  6903. 'episode' => [],
  6904. 'answer' => '',
  6905. 'reasoning' => '',
  6906. 'usage' => [],
  6907. 'error' => '接口返回数据异常,请重新请求'
  6908. ];
  6909. return;
  6910. }
  6911. // 处理流式输出
  6912. foreach ($streamGenerator as $chunk) {
  6913. if (isset($chunk['type'])) {
  6914. if ($chunk['type'] === 'done') {
  6915. // 最终结果
  6916. $fullContent = $chunk['full_content'];
  6917. $fullReasoningContent = $chunk['full_reasoning'];
  6918. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6919. } else {
  6920. // 逐块yield数据
  6921. yield $chunk;
  6922. }
  6923. }
  6924. }
  6925. } catch (\Exception $e) {
  6926. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6927. 'model' => $model,
  6928. 'anime_id' => $anime_id,
  6929. 'episode_number' => $episode_number,
  6930. 'trace' => $e->getTraceAsString()
  6931. ]);
  6932. logDB('deepseek', 'error', 'chat流式处理失败', [
  6933. 'error' => $e->getMessage(),
  6934. 'model' => $model
  6935. ]);
  6936. yield [
  6937. 'type' => 'error',
  6938. 'episode' => [],
  6939. 'answer' => '',
  6940. 'reasoning' => '',
  6941. 'usage' => [],
  6942. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6943. ];
  6944. return;
  6945. }
  6946. dLog('deepseek')->info('完整内容: '.$fullContent);
  6947. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6948. // 处理完整内容并返回最终结果
  6949. $episode_arr = handleEpisodeContent($fullContent);
  6950. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6951. if (empty($episode_arr['acts'])) {
  6952. // 未生成剧本相关内容,保存对话记录并返回提示
  6953. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6954. try {
  6955. $now = date('Y-m-d H:i:s');
  6956. // 保存对话记录
  6957. $records = [
  6958. [
  6959. 'uid' => $uid,
  6960. 'anime_id' => $anime_id,
  6961. 'sequence' => $episode_number,
  6962. 'role' => 'user',
  6963. 'content' => $prompt,
  6964. 'created_at' => $now,
  6965. 'updated_at' => $now
  6966. ],
  6967. [
  6968. 'uid' => $uid,
  6969. 'anime_id' => $anime_id,
  6970. 'sequence' => $episode_number,
  6971. 'role' => 'assistant',
  6972. 'content' => $fullContent,
  6973. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6974. 'created_at' => $now,
  6975. 'updated_at' => $now
  6976. ]
  6977. ];
  6978. DB::table('mp_anime_records')->insert($records);
  6979. } catch (\Exception $e) {
  6980. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6981. }
  6982. yield [
  6983. 'type' => 'done',
  6984. 'episode' => [],
  6985. 'answer' => $fullContent,
  6986. 'reasoning' => $fullReasoningContent,
  6987. 'usage' => $usage,
  6988. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6989. ];
  6990. return;
  6991. }
  6992. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6993. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6994. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6995. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6996. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6997. $existing_props = is_array($existing_props) ? $existing_props : [];
  6998. $now = date('Y-m-d H:i:s');
  6999. try {
  7000. DB::beginTransaction();
  7001. $saveResult = $this->saveEpisodeVersionData(
  7002. $anime_id,
  7003. $episode_number,
  7004. $episode_arr,
  7005. $existing_roles,
  7006. $existing_scenes,
  7007. $existing_props,
  7008. $current_episode,
  7009. $base_episode,
  7010. $is_regenerate_version,
  7011. $content,
  7012. $now
  7013. );
  7014. $episode = $saveResult['episode'];
  7015. $episode_id = $saveResult['episode_id'];
  7016. $merged_roles = $saveResult['merged_roles'];
  7017. $merged_scenes = $saveResult['merged_scenes'];
  7018. $merged_props = $saveResult['merged_props'];
  7019. $record_content = $origin_prompt;
  7020. if ($uploaded_content !== '') {
  7021. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7022. }
  7023. $records = [
  7024. [
  7025. 'uid' => $uid,
  7026. 'anime_id' => $anime_id,
  7027. 'role' => 'user',
  7028. 'content' => $record_content,
  7029. 'sequence' => $episode_number,
  7030. 'episode_id' => $episode_id,
  7031. 'created_at' => $now,
  7032. 'updated_at' => $now
  7033. ],
  7034. [
  7035. 'uid' => $uid,
  7036. 'anime_id' => $anime_id,
  7037. 'role' => 'assistant',
  7038. 'content' => $fullContent,
  7039. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7040. 'sequence' => $episode_number,
  7041. 'episode_id' => $episode_id,
  7042. 'created_at' => $now,
  7043. 'updated_at' => $now
  7044. ]
  7045. ];
  7046. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7047. if (!$boolen4) {
  7048. Utils::throwError('20003:对话记录保存失败');
  7049. }
  7050. // 保存模型和内容到anime表
  7051. $update_anime_data = [
  7052. 'model' => $model,
  7053. 'updated_at' => $now
  7054. ];
  7055. if ($uploaded_content) {
  7056. $update_anime_data['content'] = $uploaded_content;
  7057. }
  7058. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7059. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7060. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7061. 'anime_id' => $anime_id,
  7062. 'episode_number' => $episode_number,
  7063. 'model' => $model,
  7064. 'source' => 'chat',
  7065. ]);
  7066. }catch (\Exception $e) {
  7067. DB::rollBack();
  7068. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7069. yield [
  7070. 'type' => 'done',
  7071. 'answer' => $fullContent,
  7072. 'reasoning' => $fullReasoningContent,
  7073. 'usage' => $usage,
  7074. 'error' => $e->getMessage(),
  7075. ];
  7076. return;
  7077. }
  7078. DB::commit();
  7079. if ($is_global_generate_pics) {
  7080. // // 批量生成全局角色图片
  7081. // $this->batchSetGlobalRoleImg([
  7082. // 'anime_id' => $anime_id,
  7083. // ], true);
  7084. // // 批量生成全局场景图片
  7085. // $this->batchSetGlobalSceneImg([
  7086. // 'anime_id' => $anime_id,
  7087. // ], true);
  7088. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7089. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7090. }
  7091. $episode['episode_id'] = $episode_id;
  7092. $episode['roles'] = $merged_roles;
  7093. $episode['scenes'] = $merged_scenes;
  7094. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7095. yield [
  7096. 'type' => 'done',
  7097. 'episode' => $episode,
  7098. 'answer' => $fullContent,
  7099. 'reasoning' => $fullReasoningContent,
  7100. 'usage' => $usage
  7101. ];
  7102. }
  7103. public function addChatForAce($data) {
  7104. $uid = Site::getUid();
  7105. $anime_id = getProp($data, 'anime_id');
  7106. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7107. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7108. if (!$anime) Utils::throwError('20003:对话不存在');
  7109. $file = getProp($data, 'file');
  7110. $content = getProp($data, 'content', '');
  7111. $bid = getProp($data, 'bid', 0);
  7112. $script_id = getProp($data, 'script_id', 0);
  7113. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7114. $prompt = getProp($data, 'prompt');
  7115. $is_multi = getProp($anime, 'is_multi');
  7116. $is_single = (int)$is_multi !== 1;
  7117. // 积分余额预检(仅单剧集模式收费)
  7118. if ($is_single) {
  7119. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7120. }
  7121. $extra_products = getProp($data, 'products', []);
  7122. if (!$extra_products) {
  7123. $extra_products = getProp($anime, 'extra_products');
  7124. if ($extra_products) {
  7125. $extra_products = json_decode($extra_products, true);
  7126. }else {
  7127. $extra_products = [];
  7128. }
  7129. }else {
  7130. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7131. }
  7132. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7133. $anime_script_id = getProp($anime, 'script_id');
  7134. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7135. $cpid = Site::getCpid();
  7136. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7137. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7138. ->where('mapping.script_id', $anime_script_id)
  7139. ->where('product.cpid', $cpid)
  7140. ->where('product.is_deleted', 0);
  7141. $mappings = $script_products_mappings->select(
  7142. 'mapping.product_id',
  7143. 'mapping.episode_number',
  7144. 'product.product_name',
  7145. 'product.type',
  7146. 'product.product',
  7147. 'product.pic_prompt',
  7148. 'product.url',
  7149. 'product.pic_task_id',
  7150. 'product.pic_task_status',
  7151. 'product.three_view_image_url'
  7152. )
  7153. ->get();
  7154. // 按 product_id 分组,合并 episode_number
  7155. $productMap = [];
  7156. foreach ($mappings as $item) {
  7157. $product_id = $item->product_id;
  7158. $product_name = $item->product_name;
  7159. // 处理product_name两边的符号
  7160. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7161. if (!isset($productMap[$product_id])) {
  7162. $productMap[$product_id] = [
  7163. 'product_id' => $product_id,
  7164. 'product_name' => $product_name,
  7165. 'type' => (int)$item->type,
  7166. 'product' => (int)$item->product,
  7167. 'pic_prompt' => $item->pic_prompt,
  7168. 'url' => $item->url,
  7169. 'pic_task_id' => $item->pic_task_id,
  7170. 'pic_task_status' => $item->pic_task_status,
  7171. 'episode_numbers' => [],
  7172. ];
  7173. }
  7174. // 添加 episode_number(去重)
  7175. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7176. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7177. }
  7178. }
  7179. // 将查询到的剧本资产合并到extra_products中
  7180. // 先构建extra_products的索引(以product_id为key,用于去重)
  7181. $extraProductsMap = [];
  7182. foreach ($extra_products as $item) {
  7183. $key = getProp($item, 'product_id');
  7184. if ($key) {
  7185. $extraProductsMap[$key] = $item;
  7186. }
  7187. }
  7188. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7189. foreach ($productMap as $product) {
  7190. $product_id = $product['product_id'];
  7191. // 如果不存在则添加(不带episode_number信息)
  7192. if (!isset($extraProductsMap[$product_id])) {
  7193. $extraProductsMap[$product_id] = [
  7194. 'product_id' => $product['product_id'],
  7195. 'product_name' => $product['product_name'],
  7196. 'type' => $product['type'],
  7197. 'product' => $product['product'],
  7198. 'pic_prompt' => $product['pic_prompt'],
  7199. 'url' => $product['url'],
  7200. 'pic_task_id' => $product['pic_task_id'],
  7201. 'pic_task_status' => $product['pic_task_status'],
  7202. ];
  7203. }
  7204. }
  7205. // 重新赋值给extra_products
  7206. $extra_products = array_values($extraProductsMap);
  7207. }
  7208. $user_anime_name = getProp($anime, 'anime_name');
  7209. // 处理提示词
  7210. if ($prompt && $extra_products) {
  7211. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7212. foreach($extra_products as $item) {
  7213. $product_name = getProp($item, 'product_name');
  7214. if ($product_name) {
  7215. // 替换 {product_name} 为 product_name
  7216. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7217. }
  7218. }
  7219. }
  7220. // 处理文本模型
  7221. $model = getProp($data, 'model');
  7222. if (!$model) {
  7223. // 用户没有输入,从anime表获取
  7224. $model = getProp($anime, 'model');
  7225. if (!$model) {
  7226. // anime表也没有,使用默认值
  7227. $model = 'deepseek-v4-pro';
  7228. }
  7229. }
  7230. // 验证模型是否在可用模型表中
  7231. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7232. $model = 'deepseek-v4-pro';
  7233. }
  7234. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7235. if ($prompt) {
  7236. $question .= "本次修改要求如下:\n{$prompt}";
  7237. }
  7238. // if (!$file && !$content && !$bid) {
  7239. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7240. // }
  7241. // 提取文件内容
  7242. if ($file) {
  7243. $content = $this->extractFileContent($file);
  7244. if (!$content) {
  7245. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7246. }
  7247. } elseif ($script_id) {
  7248. $content = $this->getContentByScriptId($script_id);
  7249. if (!$content) {
  7250. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7251. }
  7252. } elseif ($bid) {
  7253. $content = $this->getContentByBid($bid);
  7254. if (!$content) {
  7255. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7256. }
  7257. } elseif ($content) {
  7258. $content = filterContent($content);
  7259. } else {
  7260. $content = getProp($anime, 'content');
  7261. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7262. $need_generate_content = true;
  7263. }
  7264. }
  7265. // 美术风格
  7266. $input_art_style = getProp($data, 'art_style');
  7267. if (!$input_art_style) {
  7268. $mappedArtStyle = getProp($anime, 'art_style');
  7269. }else {
  7270. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7271. }
  7272. // 判断是否需要生成原文内容
  7273. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7274. // 如果需要生成原文内容,添加额外的要求
  7275. $content_generation_requirement = $need_generate_content
  7276. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7277. : "";
  7278. // 美术风格
  7279. if (!$mappedArtStyle) {
  7280. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7281. }else {
  7282. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7283. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7284. }else {
  7285. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7286. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7287. }
  7288. }
  7289. // 构建主体、场景和道具提示词
  7290. $extra_role_prompt = "\n";
  7291. $extra_scene_prompt = "\n";
  7292. $extra_prop_prompt = "\n";
  7293. $ref_products = []; // 参考资产
  7294. if ($extra_products) {
  7295. foreach($extra_products as $item) {
  7296. $product = getProp($item, 'product');
  7297. $product_name = getProp($item, 'product_name');
  7298. if ($product_name == '旁白') continue;
  7299. $ref_products[$product_name] = $item;
  7300. $pic_prompt = getProp($item, 'pic_prompt');
  7301. if ((int)$product === 1) {
  7302. // 拼接角色信息
  7303. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7304. } elseif ((int)$product === 2) {
  7305. // 拼接场景信息
  7306. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7307. } elseif ((int)$product === 3) {
  7308. // 拼接道具信息
  7309. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7310. }
  7311. }
  7312. // 优化提示词,融入剧本
  7313. if (!empty(trim($extra_role_prompt))) {
  7314. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7315. }
  7316. if (!empty(trim($extra_scene_prompt))) {
  7317. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7318. }
  7319. if (!empty(trim($extra_prop_prompt))) {
  7320. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7321. }
  7322. }
  7323. if ($anime_script_id && $is_single) {
  7324. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7325. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7326. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7327. }else {
  7328. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7329. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7330. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7331. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7332. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7333. {$extra_role_prompt}";
  7334. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7335. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7336. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7337. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7338. {$extra_scene_prompt}";
  7339. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7340. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7341. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7342. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7343. {$extra_prop_prompt}";
  7344. }
  7345. $systemPrompt = $is_single
  7346. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7347. 强制要求:
  7348. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7349. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7350. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7351. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7352. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7353. 普通要求:
  7354. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7355. $role_demo
  7356. $scene_demo
  7357. $prop_demo
  7358. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7359. 5.1片段分割逻辑(优先级从高到低):
  7360. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7361. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7362. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7363. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7364. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7365. - 片段数量格式为: 片段数量:8
  7366. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7367. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7368. 5.3分镜结构:每个分镜包含以下字段:
  7369. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7370. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7371. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7372. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7373. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7374. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7375. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7376. - 运镜:场景+画面描述+运镜
  7377. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7378. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7379. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7380. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7381. 6.{$mappedArtStyle_prompt}\n\n
  7382. 示例如下:\n
  7383. ###剧本名:西昆仑
  7384. ###故事梗概
  7385. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7386. ###剧本亮点
  7387. 亮点1:绝境奇药,生死一线
  7388. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7389. 亮点2:结拜兄妹,化解尴尬
  7390. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7391. 亮点3:纤发夺命,情愫暗涌
  7392. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7393. ###人物关系
  7394. 阿雪与梁萧之间存在兄妹之情。
  7395. ###核心矛盾
  7396. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7397. ###主体列表
  7398. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7399. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7400. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7401. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7402. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7403. 全景,正面拍摄,青年女性,亚洲人。
  7404. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7405. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7406. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7407. ###美术风格
  7408. 基础画风风格词:厚涂古风
  7409. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7410. ###场景列表
  7411. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7412. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7413. 无人物。}
  7414. ###分段剧本
  7415. 片段数量:8
  7416. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7417. ##片段1
  7418. 时长:12s
  7419. 分镜1
  7420. 出场角色:刀疤脸
  7421. 场景:边境小镇街道
  7422. 出场道具:酒杯-高脚杯
  7423. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7424. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7425. 配音台词:
  7426. 背景音效:
  7427. 分镜2
  7428. 出场角色:刀疤脸
  7429. 场景:悦来酒馆
  7430. 出场道具:酒杯-高脚杯
  7431. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7432. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7433. 配音台词:
  7434. 背景音效:
  7435. 分镜3
  7436. 出场角色:刀疤脸
  7437. 场景:悦来酒馆
  7438. 出场道具:酒杯-高脚杯
  7439. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7440. 运镜:从中景推向令牌特写。
  7441. 配音台词:
  7442. 背景音效:
  7443. 分镜4
  7444. 出场角色:刀疤脸
  7445. 场景:悦来酒馆
  7446. 出场道具:酒杯-高脚杯
  7447. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7448. 运镜:极速推向酒水溅起的瞬间。
  7449. 配音台词:
  7450. 背景音效:
  7451. 分镜5
  7452. 出场角色:刀疤脸
  7453. 场景:悦来酒馆
  7454. 出场道具:酒杯-高脚杯
  7455. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7456. 运镜:固定机位,利用倾斜构图制造压迫感。
  7457. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7458. 背景音效:
  7459. \n\n"
  7460. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7461. 强制要求:\n
  7462. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7463. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7464. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7465. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7466. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7467. 普通要求:\n
  7468. 1.剧本名(必须生成)必须与文档内容高度相关
  7469. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7470. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7471. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7472. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7473. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7474. {$extra_role_prompt}
  7475. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7476. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7477. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7478. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7479. {$extra_scene_prompt}
  7480. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7481. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7482. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7483. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7484. {$extra_prop_prompt}
  7485. 5.{$mappedArtStyle_prompt}\n\n
  7486. 示例如下:\n
  7487. ###剧本名:西昆仑
  7488. ###故事梗概
  7489. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7490. ###剧本亮点
  7491. 亮点1:绝境奇药,生死一线
  7492. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7493. 亮点2:结拜兄妹,化解尴尬
  7494. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7495. 亮点3:纤发夺命,情愫暗涌
  7496. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7497. ###人物关系
  7498. 阿雪与梁萧之间存在兄妹之情。
  7499. ###核心矛盾
  7500. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7501. ###主体列表
  7502. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7503. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7504. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7505. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7506. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7507. 全景,正面拍摄,青年女性,亚洲人。
  7508. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7509. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7510. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7511. ###美术风格
  7512. 基础画风风格词:厚涂古风
  7513. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7514. ###场景列表
  7515. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7516. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7517. 无人物。}
  7518. ###道具列表
  7519. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7520. // 构建消息
  7521. $messages = [
  7522. [
  7523. 'role' => 'system',
  7524. 'content' => $systemPrompt
  7525. ],
  7526. [
  7527. 'role' => 'user',
  7528. 'content' => "以下是文档内容:
  7529. {$content}
  7530. 用户问题:
  7531. {$question}"
  7532. ]
  7533. ];
  7534. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7535. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7536. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7537. if ($model === 'deepseek-chat') {
  7538. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7539. $model = 'deepseek-v4-flash';
  7540. $thinkingMode = 'disabled';
  7541. } elseif ($model === 'deepseek-reasoner') {
  7542. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7543. $model = 'deepseek-v4-flash';
  7544. $thinkingMode = 'enabled';
  7545. }
  7546. $post_data = [
  7547. 'model' => $model,
  7548. 'messages' => $messages,
  7549. // 'max_tokens' => 8192,
  7550. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7551. 'frequency_penalty' => 0,
  7552. 'presence_penalty' => 0,
  7553. 'response_format' => ['type' => 'text'],
  7554. 'thinking' => ['type'=>$thinkingMode],
  7555. 'stream' => true // 启用流式输出
  7556. ];
  7557. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7558. // 根据模型类型选择调用方法
  7559. $fullContent = '';
  7560. $fullReasoningContent = '';
  7561. $usage = [];
  7562. try {
  7563. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7564. // DeepSeek 官方模型使用 DeepSeek API
  7565. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7566. } else if (in_array($model, $this->gpt_text_models)) {
  7567. // GPT-5.4 模型使用 TokenRouter API
  7568. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7569. } else if (in_array($model, $this->gemini_text_models)) {
  7570. // Gemini 模型使用 Gemini API
  7571. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7572. } else {
  7573. // 其他模型使用火山引擎API
  7574. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7575. }
  7576. // 验证返回值类型
  7577. if (!is_iterable($streamGenerator)) {
  7578. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7579. dLog('deepseek')->error('addChat流式生成器无效', [
  7580. 'generator_type' => $errorType,
  7581. 'model' => $model,
  7582. 'anime_id' => $anime_id
  7583. ]);
  7584. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7585. 'type' => $errorType,
  7586. 'model' => $model
  7587. ]);
  7588. yield [
  7589. 'type' => 'error',
  7590. 'script' => [],
  7591. 'episode' => [],
  7592. 'answer' => '',
  7593. 'reasoning' => '',
  7594. 'usage' => [],
  7595. 'error' => '接口返回数据异常,请重新请求'
  7596. ];
  7597. return;
  7598. }
  7599. // 处理流式输出
  7600. foreach ($streamGenerator as $chunk) {
  7601. if (isset($chunk['type'])) {
  7602. if ($chunk['type'] === 'done') {
  7603. // 最终结果
  7604. $fullContent = $chunk['full_content'];
  7605. $fullReasoningContent = $chunk['full_reasoning'];
  7606. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7607. } else {
  7608. // 逐块yield数据
  7609. yield $chunk;
  7610. }
  7611. }
  7612. }
  7613. } catch (\Exception $e) {
  7614. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7615. 'model' => $model,
  7616. 'anime_id' => $anime_id,
  7617. 'trace' => $e->getTraceAsString()
  7618. ]);
  7619. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7620. 'error' => $e->getMessage(),
  7621. 'model' => $model
  7622. ]);
  7623. yield [
  7624. 'type' => 'error',
  7625. 'script' => [],
  7626. 'episode' => [],
  7627. 'answer' => '',
  7628. 'reasoning' => '',
  7629. 'usage' => [],
  7630. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7631. ];
  7632. return;
  7633. }
  7634. dLog('deepseek')->info('完整内容: '.$fullContent);
  7635. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7636. // 处理完整内容并返回最终结果
  7637. $script_arr = [];
  7638. if ($fullContent) {
  7639. $script_arr = handleScriptContentForAce($fullContent);
  7640. dLog('deepseek')->info('解析内容', $script_arr);
  7641. logDB('deepseek', 'info', '解析内容', $script_arr);
  7642. }
  7643. if (empty($script_arr['roles'])) {
  7644. // 未生成剧本相关内容,保存对话记录并返回提示
  7645. dLog('deepseek')->info('未生成剧本相关的内容');
  7646. try {
  7647. DB::beginTransaction();
  7648. $now = date('Y-m-d H:i:s');
  7649. // 保存对话记录
  7650. $records = [
  7651. [
  7652. 'uid' => $uid,
  7653. 'anime_id' => $anime_id,
  7654. 'sequence' => 0,
  7655. 'role' => 'user',
  7656. 'content' => $prompt,
  7657. 'created_at' => $now,
  7658. 'updated_at' => $now
  7659. ],
  7660. [
  7661. 'uid' => $uid,
  7662. 'anime_id' => $anime_id,
  7663. 'sequence' => 0,
  7664. 'role' => 'assistant',
  7665. // 'content' => $fullContent,
  7666. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7667. 'created_at' => $now,
  7668. 'updated_at' => $now
  7669. ]
  7670. ];
  7671. DB::table('mp_anime_records')->insert($records);
  7672. DB::commit();
  7673. } catch (\Exception $e) {
  7674. DB::rollBack();
  7675. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7676. }
  7677. yield [
  7678. 'type' => 'done',
  7679. 'script' => [],
  7680. 'episode' => [],
  7681. 'answer' => $fullContent,
  7682. 'reasoning' => $fullReasoningContent,
  7683. 'usage' => $usage,
  7684. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7685. ];
  7686. return;
  7687. }
  7688. // 如果需要生成原文内容,从script_arr中提取
  7689. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7690. $content = $script_arr['content'];
  7691. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7692. if (!$content) {
  7693. yield [
  7694. 'type' => 'done',
  7695. 'script' => [],
  7696. 'episode' => [],
  7697. 'answer' => $fullContent,
  7698. 'reasoning' => $fullReasoningContent,
  7699. 'usage' => $usage,
  7700. 'error' => '未生成剧本内容,请调整提示词再试'
  7701. ];
  7702. return;
  7703. }
  7704. }
  7705. // 替换美术风格
  7706. if ($mappedArtStyle !== '') {
  7707. $script_arr['art_style'] = $mappedArtStyle;
  7708. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7709. }
  7710. // 新建动漫
  7711. if ($user_anime_name == '新剧本策划') {
  7712. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7713. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7714. // if (!$anime_name) {
  7715. // // 未识别到剧本名,保存对话记录并返回提示
  7716. // dLog('deepseek')->info('未能识别到剧本名称');
  7717. // try {
  7718. // DB::beginTransaction();
  7719. // $now = date('Y-m-d H:i:s');
  7720. // // 保存对话记录
  7721. // $records = [
  7722. // [
  7723. // 'uid' => $uid,
  7724. // 'anime_id' => $anime_id,
  7725. // 'sequence' => 0,
  7726. // 'role' => 'user',
  7727. // 'content' => $prompt,
  7728. // 'created_at' => $now,
  7729. // 'updated_at' => $now
  7730. // ],
  7731. // [
  7732. // 'uid' => $uid,
  7733. // 'anime_id' => $anime_id,
  7734. // 'sequence' => 0,
  7735. // 'role' => 'assistant',
  7736. // 'content' => '未能生成剧本名称,请重试',
  7737. // 'created_at' => $now,
  7738. // 'updated_at' => $now
  7739. // ]
  7740. // ];
  7741. // DB::table('mp_anime_records')->insert($records);
  7742. // DB::commit();
  7743. // } catch (\Exception $e) {
  7744. // DB::rollBack();
  7745. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7746. // }
  7747. // yield [
  7748. // 'type' => 'done',
  7749. // 'script' => [],
  7750. // 'episode' => [],
  7751. // 'answer' => $fullContent,
  7752. // 'reasoning' => $fullReasoningContent,
  7753. // 'usage' => $usage,
  7754. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7755. // ];
  7756. // return;
  7757. // }
  7758. // 确认对话名称唯一性
  7759. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7760. $anime_name = $anime_name . '_' . date('YmdHis');
  7761. }
  7762. }else {
  7763. $anime_name = $user_anime_name;
  7764. }
  7765. $table_data = [
  7766. 'user_id' => $uid,
  7767. 'anime_name' => $anime_name,
  7768. 'model' => $model,
  7769. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7770. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7771. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7772. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7773. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7774. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7775. 'art_style_type' => $input_art_style,
  7776. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7777. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7778. 'status' => '解析完成',
  7779. 'content' => $content,
  7780. 'is_multi' => $is_multi,
  7781. 'ace_mode' => $ace_mode,
  7782. 'generate_status' => '待执行',
  7783. 'updated_at' => date('Y-m-d H:i:s')
  7784. ];
  7785. if ($table_data['content']) {
  7786. $chapters = splitContent($table_data['content']);
  7787. $chapter_count = count($chapters);
  7788. if ($chapter_count > 0) {
  7789. $table_data['start_episode_sequence'] = 1;
  7790. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7791. }
  7792. }
  7793. if ($extra_products) {
  7794. $table_data['extra_products'] = json_encode($extra_products, 256);
  7795. }
  7796. // 如果有剧本ID则进行绑定
  7797. if ($script_id) {
  7798. $table_data['script_id'] = $script_id;
  7799. }
  7800. $single_episode = [];
  7801. try {
  7802. DB::beginTransaction();
  7803. $now = date('Y-m-d H:i:s');
  7804. // 更新动漫大纲
  7805. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7806. if (!$boolen) {
  7807. dLog('deepseek')->info('动漫保存失败', $table_data);
  7808. Utils::throwError('20003:动漫保存失败');
  7809. }
  7810. // 保存对话记录
  7811. $records = [
  7812. [
  7813. 'uid' => $uid,
  7814. 'anime_id' => $anime_id,
  7815. 'sequence' => 0,
  7816. 'role' => 'user',
  7817. 'content' => $prompt,
  7818. 'created_at' => date('Y-m-d H:i:s'),
  7819. 'updated_at' => date('Y-m-d H:i:s')
  7820. ],
  7821. [
  7822. 'uid' => $uid,
  7823. 'anime_id' => $anime_id,
  7824. 'sequence' => 0,
  7825. 'role' => 'assistant',
  7826. 'content' => $fullContent,
  7827. 'created_at' => date('Y-m-d H:i:s'),
  7828. 'updated_at' => date('Y-m-d H:i:s')
  7829. ]
  7830. ];
  7831. // 保存对话记录
  7832. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7833. if (!$boolen3) {
  7834. Utils::throwError('20003:对话记录保存失败');
  7835. }
  7836. if ($is_single) {
  7837. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7838. if (empty($episode_arr['acts'])) {
  7839. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7840. }
  7841. $saveResult = $this->saveEpisodeVersionData(
  7842. $anime_id,
  7843. 1,
  7844. $episode_arr,
  7845. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7846. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7847. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7848. null,
  7849. null,
  7850. false,
  7851. $content,
  7852. $now,
  7853. $ref_products
  7854. );
  7855. $single_episode = $saveResult['episode'];
  7856. $episode_id = $saveResult['episode_id'];
  7857. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7858. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7859. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7860. 'props' => json_encode($saveResult['merged_props'], 256),
  7861. 'updated_at' => $now
  7862. ]);
  7863. if ($boolen5 === false) {
  7864. Utils::throwError('20003:单剧集主表资源同步失败');
  7865. }
  7866. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7867. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7868. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7869. $episode_record_content = '确认分镜大纲';
  7870. if ($content !== '') {
  7871. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7872. }
  7873. $episode_records = [
  7874. [
  7875. 'uid' => $uid,
  7876. 'anime_id' => $anime_id,
  7877. 'role' => 'user',
  7878. 'content' => $episode_record_content,
  7879. 'sequence' => 1,
  7880. 'episode_id' => $episode_id,
  7881. 'created_at' => $now,
  7882. 'updated_at' => $now
  7883. ],
  7884. [
  7885. 'uid' => $uid,
  7886. 'anime_id' => $anime_id,
  7887. 'role' => 'assistant',
  7888. 'content' => $fullContent,
  7889. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7890. 'sequence' => 1,
  7891. 'episode_id' => $episode_id,
  7892. 'created_at' => $now,
  7893. 'updated_at' => $now
  7894. ]
  7895. ];
  7896. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7897. if (!$boolen4) {
  7898. Utils::throwError('20003:单剧集分镜记录保存失败');
  7899. }
  7900. }
  7901. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7902. if ($is_single && !empty($single_episode)) {
  7903. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7904. 'anime_id' => $anime_id,
  7905. 'episode_id' => $episode_id ?? 0,
  7906. 'model' => $model,
  7907. 'source' => 'addChatForAce',
  7908. ]);
  7909. }
  7910. }catch (\Exception $e) {
  7911. DB::rollBack();
  7912. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7913. yield [
  7914. 'type' => 'done',
  7915. 'answer' => $fullContent,
  7916. 'reasoning' => $fullReasoningContent,
  7917. 'usage' => $usage,
  7918. 'error' => $e->getMessage(),
  7919. ];
  7920. return;
  7921. }
  7922. DB::commit();
  7923. dLog('deepseek')->info('保存完毕');
  7924. if ($is_single && !empty($single_episode)) {
  7925. // $this->batchSetGlobalRoleImg([
  7926. // 'anime_id' => $anime_id,
  7927. // ]);
  7928. // $this->batchSetGlobalSceneImg([
  7929. // 'anime_id' => $anime_id,
  7930. // ]);
  7931. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7932. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7933. }
  7934. $table_data['anime_id'] = $anime_id;
  7935. $table_data['roles'] = json_decode($table_data['roles'], true);
  7936. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7937. // $table_data['episodes'] = $script_arr['episodes'];
  7938. unset($table_data['created_at']);
  7939. unset($table_data['updated_at']);
  7940. unset($table_data['status']);
  7941. dLog('deepseek')->info('开始返回');
  7942. yield [
  7943. 'type' => 'done',
  7944. 'script' => $table_data,
  7945. 'episode' => $single_episode,
  7946. 'answer' => $fullContent,
  7947. 'reasoning' => $fullReasoningContent,
  7948. 'usage' => $usage
  7949. ];
  7950. }
  7951. public function reGenerateAnimeForAce($data) {
  7952. $uid = Site::getUid();
  7953. $file = getProp($data, 'file');
  7954. $content = getProp($data, 'content', '');
  7955. $bid = getProp($data, 'bid', 0);
  7956. $script_id = getProp($data, 'script_id', 0);
  7957. $anime_id = getProp($data, 'anime_id');
  7958. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7959. if (!$anime) {
  7960. Utils::throwError('20003:该对话不存在');
  7961. }
  7962. $is_multi = getProp($anime, 'is_multi', 1);
  7963. $is_single = (int)$is_multi !== 1;
  7964. // 积分余额预检(仅单剧集模式收费)
  7965. if ($is_single) {
  7966. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7967. }
  7968. $extra_products = getProp($data, 'products', []);
  7969. if (!$extra_products) {
  7970. $extra_products = getProp($anime, 'extra_products');
  7971. if ($extra_products) {
  7972. $extra_products = json_decode($extra_products, true);
  7973. }else {
  7974. $extra_products = [];
  7975. }
  7976. }else {
  7977. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7978. }
  7979. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7980. $anime_script_id = getProp($anime, 'script_id');
  7981. if ($anime_script_id && $is_single) {
  7982. $cpid = Site::getCpid();
  7983. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7984. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7985. ->where('mapping.script_id', $anime_script_id)
  7986. ->where('product.cpid', $cpid)
  7987. ->where('product.is_deleted', 0);
  7988. $mappings = $script_products_mappings->select(
  7989. 'mapping.product_id',
  7990. 'mapping.episode_number',
  7991. 'product.product_name',
  7992. 'product.type',
  7993. 'product.product',
  7994. 'product.pic_prompt',
  7995. 'product.url',
  7996. 'product.pic_task_id',
  7997. 'product.pic_task_status',
  7998. 'product.three_view_image_url'
  7999. )
  8000. ->get();
  8001. // 按 product_id 分组,合并 episode_number
  8002. $productMap = [];
  8003. foreach ($mappings as $item) {
  8004. $product_id = $item->product_id;
  8005. $product_name = $item->product_name;
  8006. // 处理product_name两边的符号
  8007. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8008. if (!isset($productMap[$product_id])) {
  8009. $productMap[$product_id] = [
  8010. 'product_id' => $product_id,
  8011. 'product_name' => $product_name,
  8012. 'type' => (int)$item->type,
  8013. 'product' => (int)$item->product,
  8014. 'pic_prompt' => $item->pic_prompt,
  8015. 'url' => $item->url,
  8016. 'pic_task_id' => $item->pic_task_id,
  8017. 'pic_task_status' => $item->pic_task_status,
  8018. 'episode_numbers' => [],
  8019. ];
  8020. }
  8021. // 添加 episode_number(去重)
  8022. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8023. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8024. }
  8025. }
  8026. // 将查询到的剧本资产合并到extra_products中
  8027. // 先构建extra_products的索引(以product_id为key,用于去重)
  8028. $extraProductsMap = [];
  8029. foreach ($extra_products as $item) {
  8030. $key = getProp($item, 'product_id');
  8031. if ($key) {
  8032. $extraProductsMap[$key] = $item;
  8033. }
  8034. }
  8035. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8036. foreach ($productMap as $product) {
  8037. $product_id = $product['product_id'];
  8038. // 如果不存在则添加(不带episode_number信息)
  8039. if (!isset($extraProductsMap[$product_id])) {
  8040. $extraProductsMap[$product_id] = [
  8041. 'product_id' => $product['product_id'],
  8042. 'product_name' => $product['product_name'],
  8043. 'type' => $product['type'],
  8044. 'product' => $product['product'],
  8045. 'pic_prompt' => $product['pic_prompt'],
  8046. 'url' => $product['url'],
  8047. 'pic_task_id' => $product['pic_task_id'],
  8048. 'pic_task_status' => $product['pic_task_status'],
  8049. ];
  8050. }
  8051. }
  8052. // 重新赋值给extra_products
  8053. $extra_products = array_values($extraProductsMap);
  8054. }
  8055. $user_anime_name = getProp($anime, 'anime_name');
  8056. $prompt = getProp($data, 'prompt');
  8057. // 处理提示词
  8058. if ($prompt && $extra_products) {
  8059. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8060. foreach($extra_products as $item) {
  8061. $product_name = getProp($item, 'product_name');
  8062. if ($product_name) {
  8063. // 替换 {product_name} 为 product_name
  8064. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8065. }
  8066. }
  8067. }
  8068. // 处理文本模型
  8069. $model = getProp($data, 'model');
  8070. if (!$model) {
  8071. // 用户没有输入,从anime表获取
  8072. $model = getProp($anime, 'model');
  8073. if (!$model) {
  8074. // anime表也没有,使用默认值
  8075. $model = 'deepseek-v4-pro';
  8076. }
  8077. }
  8078. // 验证模型是否在可用模型表中
  8079. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8080. $model = 'deepseek-v4-pro';
  8081. }
  8082. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8083. if ($is_single) {
  8084. $episode_exists = DB::table('mp_anime_episodes')
  8085. ->where('anime_id', $anime_id)
  8086. ->where('sequence', 1)
  8087. ->exists();
  8088. if ($episode_exists) {
  8089. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8090. }
  8091. }
  8092. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8093. if ($prompt) {
  8094. $question .= "本次修改要求如下:\n{$prompt}";
  8095. }
  8096. // 提取文件内容
  8097. if ($file) {
  8098. $content = $this->extractFileContent($file);
  8099. if (!$content) {
  8100. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8101. }
  8102. } elseif ($script_id) {
  8103. $content = $this->getContentByScriptId($script_id);
  8104. if (!$content) {
  8105. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8106. }
  8107. } elseif ($bid) {
  8108. $content = $this->getContentByBid($bid);
  8109. if (!$content) {
  8110. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8111. }
  8112. } elseif ($content) {
  8113. $content = filterContent($content);
  8114. }else {
  8115. $content = filterContent(getProp($anime, 'content'));
  8116. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  8117. $need_generate_content = true;
  8118. }
  8119. }
  8120. // 判断是否需要生成原文内容
  8121. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  8122. // 如果需要生成原文内容,添加额外的要求
  8123. $content_generation_requirement = $need_generate_content
  8124. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  8125. : "";
  8126. // 美术风格
  8127. $input_art_style = getProp($data, 'art_style');
  8128. if (!$input_art_style) {
  8129. $mappedArtStyle = getProp($anime, 'art_style');
  8130. }else {
  8131. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8132. }
  8133. if (!$mappedArtStyle) {
  8134. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8135. }else {
  8136. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8137. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8138. }else {
  8139. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8140. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8141. }
  8142. }
  8143. // 构建主体、场景和道具提示词
  8144. $extra_role_prompt = "\n";
  8145. $extra_scene_prompt = "\n";
  8146. $extra_prop_prompt = "\n";
  8147. $ref_products = []; // 参考资产
  8148. if ($extra_products) {
  8149. foreach($extra_products as $item) {
  8150. $product = getProp($item, 'product');
  8151. $product_name = getProp($item, 'product_name');
  8152. if ($product_name == '旁白') continue;
  8153. $ref_products[$product_name] = $item;
  8154. $pic_prompt = getProp($item, 'pic_prompt');
  8155. if ((int)$product === 1) {
  8156. // 拼接角色信息
  8157. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8158. } elseif ((int)$product === 2) {
  8159. // 拼接场景信息
  8160. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8161. } elseif ((int)$product === 3) {
  8162. // 拼接道具信息
  8163. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8164. }
  8165. }
  8166. // 优化提示词,融入剧本
  8167. if (!empty(trim($extra_role_prompt))) {
  8168. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8169. }
  8170. if (!empty(trim($extra_scene_prompt))) {
  8171. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8172. }
  8173. if (!empty(trim($extra_prop_prompt))) {
  8174. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8175. }
  8176. }
  8177. if ($anime_script_id && $is_single) {
  8178. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  8179. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  8180. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  8181. }else {
  8182. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8183. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8184. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8185. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8186. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8187. {$extra_role_prompt}";
  8188. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8189. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8190. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8191. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8192. {$extra_scene_prompt}";
  8193. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8194. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8195. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8196. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8197. {$extra_prop_prompt}";
  8198. }
  8199. $system_message = ['role'=>'system', 'content'=>$is_single
  8200. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  8201. 强制要求:
  8202. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8203. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8204. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8205. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8206. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8207. 普通要求:
  8208. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  8209. $role_demo
  8210. $scene_demo
  8211. $prop_demo
  8212. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8213. 5.1片段分割逻辑(优先级从高到低):
  8214. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8215. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8216. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8217. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8218. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8219. - 片段数量格式为: 片段数量:8
  8220. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8221. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8222. 5.3分镜结构:每个分镜包含以下字段:
  8223. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8224. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8225. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8226. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8227. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8228. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8229. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8230. - 运镜:场景+画面描述+运镜
  8231. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8232. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8233. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8234. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  8235. 6.{$mappedArtStyle_prompt}\n\n
  8236. 示例如下:\n
  8237. ###剧本名:西昆仑
  8238. ###故事梗概
  8239. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8240. ###剧本亮点
  8241. 亮点1:绝境奇药,生死一线
  8242. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8243. 亮点2:结拜兄妹,化解尴尬
  8244. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8245. 亮点3:纤发夺命,情愫暗涌
  8246. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8247. ###人物关系
  8248. 阿雪与梁萧之间存在兄妹之情。
  8249. ###核心矛盾
  8250. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8251. ###主体列表
  8252. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8253. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8254. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8255. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8256. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8257. 全景,正面拍摄,青年女性,亚洲人。
  8258. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8259. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8260. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8261. ###美术风格
  8262. 基础画风风格词:厚涂古风
  8263. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8264. ###场景列表
  8265. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8266. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8267. 无人物。}
  8268. ###分段剧本
  8269. 片段数量:8
  8270. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8271. ##片段1
  8272. 时长:12s
  8273. 分镜1
  8274. 出场角色:刀疤脸
  8275. 场景:边境小镇街道
  8276. 出场道具:酒杯-高脚杯
  8277. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8278. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8279. 配音台词:
  8280. 背景音效:
  8281. 分镜2
  8282. 出场角色:刀疤脸
  8283. 场景:悦来酒馆
  8284. 出场道具:酒杯-高脚杯
  8285. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8286. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8287. 配音台词:
  8288. 背景音效:
  8289. 分镜3
  8290. 出场角色:刀疤脸
  8291. 场景:悦来酒馆
  8292. 出场道具:酒杯-高脚杯
  8293. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8294. 运镜:从中景推向令牌特写。
  8295. 配音台词:
  8296. 背景音效:
  8297. 分镜4
  8298. 出场角色:刀疤脸
  8299. 场景:悦来酒馆
  8300. 出场道具:酒杯-高脚杯
  8301. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8302. 运镜:极速推向酒水溅起的瞬间。
  8303. 配音台词:
  8304. 背景音效:
  8305. 分镜5
  8306. 出场角色:刀疤脸
  8307. 场景:悦来酒馆
  8308. 出场道具:酒杯-高脚杯
  8309. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8310. 运镜:固定机位,利用倾斜构图制造压迫感。
  8311. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8312. 背景音效:
  8313. \n\n"
  8314. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8315. 强制要求:\n
  8316. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8317. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8318. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8319. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8320. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8321. 普通要求:\n
  8322. 1.剧本名(必须生成)必须与文档内容高度相关
  8323. $role_demo
  8324. $scene_demo
  8325. $prop_demo
  8326. 5.{$mappedArtStyle_prompt}\n\n
  8327. 示例如下:\n
  8328. ###剧本名:西昆仑
  8329. ###故事梗概
  8330. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8331. ###剧本亮点
  8332. 亮点1:绝境奇药,生死一线
  8333. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8334. 亮点2:结拜兄妹,化解尴尬
  8335. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8336. 亮点3:纤发夺命,情愫暗涌
  8337. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8338. ###人物关系
  8339. 阿雪与梁萧之间存在兄妹之情。
  8340. ###核心矛盾
  8341. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8342. ###主体列表
  8343. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8344. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8345. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8346. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8347. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8348. 全景,正面拍摄,青年女性,亚洲人。
  8349. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8350. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8351. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8352. ###美术风格
  8353. 基础画风风格词:厚涂古风
  8354. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8355. ###场景列表
  8356. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8357. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8358. 无人物。}
  8359. ###道具列表
  8360. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  8361. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  8362. $episode_count = $this->extractEpisodeNumber($prompt);
  8363. if ((int)getProp($anime, 'is_multi') !== 1) {
  8364. yield [
  8365. 'type' => 'done',
  8366. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  8367. 'reasoning' => '',
  8368. 'usage' => []
  8369. ];
  8370. return;
  8371. }
  8372. if ($episode_count) {
  8373. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  8374. $system_message = [
  8375. 'role' => 'system',
  8376. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8377. 强制要求:\n
  8378. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8379. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8380. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8381. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8382. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8383. 普通要求:\n
  8384. 1.<故事梗概>控制在200-300字左右
  8385. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8386. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8387. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8388. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8389. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8390. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8391. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8392. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8393. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8394. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8395. 示例如下:\n
  8396. ###剧本名:西昆仑
  8397. ###故事梗概
  8398. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8399. ###剧本亮点
  8400. 亮点1:绝境奇药,生死一线
  8401. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8402. 亮点2:结拜兄妹,化解尴尬
  8403. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8404. 亮点3:纤发夺命,情愫暗涌
  8405. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8406. ###人物关系
  8407. 阿雪与梁萧之间存在兄妹之情。
  8408. ###核心矛盾
  8409. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8410. ###主体列表
  8411. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8412. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8413. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8414. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8415. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8416. 全景,正面拍摄,青年女性,亚洲人。
  8417. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8418. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8419. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8420. ###美术风格
  8421. 基础画风风格词:厚涂古风
  8422. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8423. ###场景列表
  8424. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8425. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8426. 无人物。}
  8427. ###分集详细内容
  8428. ##第1章 重生
  8429. 我重生了。
  8430. 源于一个男人偏执的暗恋。
  8431. ##第2章 相救
  8432. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8433. 我眼睛扫向站在锅炉后的卞大伟。"
  8434. ];
  8435. // 构建消息
  8436. $messages = [
  8437. $system_message,
  8438. [
  8439. 'role' => 'user',
  8440. 'content' => "以下是文档内容:
  8441. {$content}
  8442. 用户问题:
  8443. {$question}"
  8444. ]
  8445. ];
  8446. }else {
  8447. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8448. // 构建消息
  8449. $messages = [
  8450. $system_message,
  8451. [
  8452. 'role' => 'user',
  8453. 'content' => "以下是文档内容:
  8454. {$content}
  8455. 用户问题:
  8456. {$question}"
  8457. ]
  8458. ];
  8459. }else {
  8460. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8461. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8462. return (array)$value;
  8463. })->toArray();
  8464. array_unshift($messages, $system_message);
  8465. $messages[] = [
  8466. 'role' => 'user',
  8467. 'content' => $prompt
  8468. ];
  8469. }
  8470. }
  8471. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8472. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8473. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8474. if ($model === 'deepseek-chat') {
  8475. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8476. $model = 'deepseek-v4-flash';
  8477. $thinkingMode = 'disabled';
  8478. } elseif ($model === 'deepseek-reasoner') {
  8479. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8480. $model = 'deepseek-v4-flash';
  8481. $thinkingMode = 'enabled';
  8482. }
  8483. $post_data = [
  8484. 'model' => $model,
  8485. 'messages' => $messages,
  8486. // 'max_tokens' => 8192,
  8487. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8488. 'frequency_penalty' => 0,
  8489. 'presence_penalty' => 0,
  8490. 'response_format' => ['type' => 'text'],
  8491. 'thinking' => ['type' => $thinkingMode],
  8492. 'stream' => true // 启用流式输出
  8493. ];
  8494. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8495. // 根据模型类型选择调用方法
  8496. $fullContent = '';
  8497. $fullReasoningContent = '';
  8498. $usage = [];
  8499. // dd($post_data);
  8500. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8501. try {
  8502. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8503. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8504. } else if (in_array($model, $this->gpt_text_models)) {
  8505. // GPT-5.4 模型使用 TokenRouter API
  8506. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8507. } else if (in_array($model, $this->gemini_text_models)) {
  8508. // Gemini 模型使用 Gemini API
  8509. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8510. } else {
  8511. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8512. }
  8513. // 验证返回值类型
  8514. if (!is_iterable($streamGenerator)) {
  8515. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8516. dLog('deepseek')->error('方法名流式生成器无效', [
  8517. 'generator_type' => $errorType,
  8518. 'model' => $model,
  8519. // 添加其他上下文信息
  8520. ]);
  8521. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8522. 'type' => $errorType,
  8523. 'model' => $model
  8524. ]);
  8525. yield [
  8526. 'type' => 'error',
  8527. // 根据方法返回相应的空数据结构
  8528. 'answer' => '',
  8529. 'reasoning' => '',
  8530. 'usage' => [],
  8531. 'error' => '接口返回数据异常,请重新请求'
  8532. ];
  8533. return;
  8534. }
  8535. // 处理流式输出
  8536. foreach ($streamGenerator as $chunk) {
  8537. if (isset($chunk['type'])) {
  8538. if ($chunk['type'] === 'done') {
  8539. $fullContent = $chunk['full_content'];
  8540. $fullReasoningContent = $chunk['full_reasoning'];
  8541. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8542. } else {
  8543. yield $chunk;
  8544. }
  8545. }
  8546. }
  8547. } catch (\Exception $e) {
  8548. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8549. 'model' => $model,
  8550. 'trace' => $e->getTraceAsString()
  8551. ]);
  8552. logDB('deepseek', 'error', '方法名流式处理失败', [
  8553. 'error' => $e->getMessage(),
  8554. 'model' => $model
  8555. ]);
  8556. yield [
  8557. 'type' => 'error',
  8558. // 根据方法返回相应的空数据结构
  8559. 'answer' => '',
  8560. 'reasoning' => '',
  8561. 'usage' => [],
  8562. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8563. ];
  8564. return;
  8565. }
  8566. dLog('deepseek')->info('完整内容: '.$fullContent);
  8567. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8568. // 处理完整内容并返回最终结果
  8569. $script_arr = [];
  8570. if ($fullContent) {
  8571. $script_arr = handleScriptContentForAce($fullContent);
  8572. dLog('deepseek')->info('解析内容', $script_arr);
  8573. logDB('deepseek', 'info', '解析内容', $script_arr);
  8574. }
  8575. if (empty($script_arr['roles'])) {
  8576. // 未生成剧本相关内容,保存对话记录并返回提示
  8577. dLog('deepseek')->info('未生成剧本相关的内容');
  8578. try {
  8579. $now = date('Y-m-d H:i:s');
  8580. // 保存对话记录
  8581. $records = [
  8582. [
  8583. 'uid' => $uid,
  8584. 'anime_id' => $anime_id,
  8585. 'sequence' => 0,
  8586. 'role' => 'user',
  8587. 'content' => $prompt,
  8588. 'created_at' => $now,
  8589. 'updated_at' => $now
  8590. ],
  8591. [
  8592. 'uid' => $uid,
  8593. 'anime_id' => $anime_id,
  8594. 'sequence' => 0,
  8595. 'role' => 'assistant',
  8596. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8597. 'created_at' => $now,
  8598. 'updated_at' => $now
  8599. ]
  8600. ];
  8601. DB::table('mp_anime_records')->insert($records);
  8602. } catch (\Exception $e) {
  8603. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8604. }
  8605. yield [
  8606. 'type' => 'done',
  8607. 'script' => [],
  8608. 'episode' => [],
  8609. 'answer' => $fullContent,
  8610. 'reasoning' => $fullReasoningContent,
  8611. 'usage' => $usage,
  8612. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8613. ];
  8614. return;
  8615. }
  8616. // 替换美术风格
  8617. if ($mappedArtStyle !== '') {
  8618. $script_arr['art_style'] = $mappedArtStyle;
  8619. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8620. }
  8621. if ($user_anime_name != '新剧本策划') {
  8622. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8623. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8624. // 确认对话名称唯一性
  8625. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8626. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8627. }
  8628. }else {
  8629. $anime_name = $user_anime_name;
  8630. }
  8631. $table_data = [
  8632. 'user_id' => $uid,
  8633. 'model' => $model,
  8634. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8635. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8636. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8637. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8638. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8639. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8640. 'art_style_type' => $input_art_style,
  8641. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8642. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8643. 'status' => '解析完成',
  8644. 'generate_status' => '待执行',
  8645. 'updated_at' => date('Y-m-d H:i:s')
  8646. ];
  8647. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8648. // 如果是修改集数,则将content内容更新(会改变原文)
  8649. if (isset($episode_count) && $episode_count > 0) {
  8650. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8651. $table_data['start_episode_sequence'] = 1;
  8652. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8653. }else {
  8654. // 如果需要生成原文内容,从script_arr中提取
  8655. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8656. $table_data['content'] = $script_arr['content'];
  8657. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8658. if (!$table_data['content']) {
  8659. yield [
  8660. 'type' => 'done',
  8661. 'script' => [],
  8662. 'episode' => [],
  8663. 'answer' => $fullContent,
  8664. 'reasoning' => $fullReasoningContent,
  8665. 'usage' => $usage,
  8666. 'error' => '未生成剧本内容,请调整提示词再试'
  8667. ];
  8668. return;
  8669. }
  8670. }
  8671. if (isset($table_data['content']) && $table_data['content']) {
  8672. $chapters = splitContent($table_data['content']);
  8673. $chapter_count = count($chapters);
  8674. if ($chapter_count > 0) {
  8675. $table_data['start_episode_sequence'] = 1;
  8676. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8677. }
  8678. }
  8679. }
  8680. if ($extra_products) {
  8681. $table_data['extra_products'] = json_encode($extra_products, 256);
  8682. }
  8683. $single_episode = [];
  8684. try {
  8685. DB::beginTransaction();
  8686. $now = date('Y-m-d H:i:s');
  8687. // 更新动漫大纲
  8688. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8689. if (!$boolen) {
  8690. dLog('deepseek')->info('对话修改失败', $table_data);
  8691. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8692. Utils::throwError('20003:对话修改失败');
  8693. }
  8694. // 保存对话记录
  8695. $records = [
  8696. [
  8697. 'uid' => $uid,
  8698. 'anime_id' => $anime_id,
  8699. 'sequence' => 0,
  8700. 'role' => 'user',
  8701. 'content' => $prompt,
  8702. 'created_at' => $now,
  8703. 'updated_at' => $now
  8704. ],
  8705. [
  8706. 'uid' => $uid,
  8707. 'anime_id' => $anime_id,
  8708. 'sequence' => 0,
  8709. 'role' => 'assistant',
  8710. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8711. 'content' => $fullContent,
  8712. 'created_at' => $now,
  8713. 'updated_at' => $now
  8714. ]
  8715. ];
  8716. // 保存对话记录
  8717. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8718. if (!$boolen3) {
  8719. Utils::throwError('20003:对话记录保存失败');
  8720. }
  8721. // 单剧集模式:生成并保存剧集信息
  8722. if ($is_single) {
  8723. $anime_name = getProp($anime, 'anime_name', '未命名');
  8724. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8725. if (empty($episode_arr['acts'])) {
  8726. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8727. }
  8728. $saveResult = $this->saveEpisodeVersionData(
  8729. $anime_id,
  8730. 1,
  8731. $episode_arr,
  8732. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8733. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8734. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8735. null,
  8736. null,
  8737. false,
  8738. $content,
  8739. $now,
  8740. $ref_products
  8741. );
  8742. $single_episode = $saveResult['episode'];
  8743. $episode_id = $saveResult['episode_id'];
  8744. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8745. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8746. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8747. 'props' => json_encode($saveResult['merged_props'], 256),
  8748. 'updated_at' => $now
  8749. ]);
  8750. if ($boolen5 === false) {
  8751. Utils::throwError('20003:单剧集主表资源同步失败');
  8752. }
  8753. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8754. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8755. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8756. $episode_record_content = '确认分镜大纲';
  8757. if ($content !== '') {
  8758. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8759. }
  8760. $episode_records = [
  8761. [
  8762. 'uid' => $uid,
  8763. 'anime_id' => $anime_id,
  8764. 'role' => 'user',
  8765. 'content' => $episode_record_content,
  8766. 'sequence' => 1,
  8767. 'episode_id' => $episode_id,
  8768. 'created_at' => $now,
  8769. 'updated_at' => $now
  8770. ],
  8771. [
  8772. 'uid' => $uid,
  8773. 'anime_id' => $anime_id,
  8774. 'role' => 'assistant',
  8775. 'content' => $fullContent,
  8776. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8777. 'sequence' => 1,
  8778. 'episode_id' => $episode_id,
  8779. 'created_at' => $now,
  8780. 'updated_at' => $now
  8781. ]
  8782. ];
  8783. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8784. if (!$boolen4) {
  8785. Utils::throwError('20003:单剧集分镜记录保存失败');
  8786. }
  8787. }
  8788. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8789. if ($is_single && !empty($single_episode)) {
  8790. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8791. 'anime_id' => $anime_id,
  8792. 'episode_id' => $episode_id ?? 0,
  8793. 'model' => $model,
  8794. 'source' => 'reGenerateAnimeForAce',
  8795. ]);
  8796. }
  8797. }catch (\Exception $e) {
  8798. DB::rollBack();
  8799. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8800. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8801. yield [
  8802. 'type' => 'done',
  8803. 'answer' => $fullContent,
  8804. 'reasoning' => $fullReasoningContent,
  8805. 'usage' => $usage,
  8806. 'error' => $e->getMessage(),
  8807. ];
  8808. return;
  8809. }
  8810. DB::commit();
  8811. dLog('deepseek')->info('保存完毕');
  8812. if ($is_single && !empty($single_episode)) {
  8813. // $this->batchSetGlobalRoleImg([
  8814. // 'anime_id' => $anime_id,
  8815. // ]);
  8816. // $this->batchSetGlobalSceneImg([
  8817. // 'anime_id' => $anime_id,
  8818. // ]);
  8819. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8820. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8821. }
  8822. $table_data['anime_id'] = $anime_id;
  8823. $table_data['roles'] = json_decode($table_data['roles'], true);
  8824. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8825. $table_data['props'] = json_decode($table_data['props'], true);
  8826. unset($table_data['updated_at']);
  8827. unset($table_data['status']);
  8828. yield [
  8829. 'type' => 'done',
  8830. 'script' => $table_data,
  8831. 'episode' => $single_episode,
  8832. 'answer' => $fullContent,
  8833. 'reasoning' => $fullReasoningContent,
  8834. 'usage' => $usage
  8835. ];
  8836. }
  8837. public function chatForAce($data) {
  8838. $uid = Site::getUid();
  8839. // 积分余额预检(不足直接报错)
  8840. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  8841. $anime_id = getProp($data, 'anime_id');
  8842. $file = getProp($data, 'file');
  8843. $content = getProp($data, 'content', '');
  8844. $bid = getProp($data, 'bid', 0);
  8845. $script_id = getProp($data, 'script_id', 0);
  8846. $episode_number = getProp($data, 'episode_number', 1);
  8847. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8848. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8849. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8850. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8851. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8852. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8853. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8854. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8855. $roles = is_array($roles) ? $roles : [];
  8856. $scenes = is_array($scenes) ? $scenes : [];
  8857. $extra_products = getProp($data, 'products', []);
  8858. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8859. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8860. $anime_script_id = getProp($anime, 'script_id');
  8861. if ($anime_script_id) {
  8862. $cpid = Site::getCpid();
  8863. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8864. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8865. ->where('mapping.script_id', $anime_script_id)
  8866. ->where('product.cpid', $cpid)
  8867. ->where('product.is_deleted', 0);
  8868. // 如果提供了 episode_number,则过滤指定集数
  8869. if ($episode_number !== null && $episode_number !== '') {
  8870. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8871. }
  8872. $mappings = $script_products_mappings->select(
  8873. 'mapping.product_id',
  8874. 'mapping.episode_number',
  8875. 'product.product_name',
  8876. 'product.type',
  8877. 'product.product',
  8878. 'product.pic_prompt',
  8879. 'product.url',
  8880. 'product.pic_task_id',
  8881. 'product.pic_task_status',
  8882. 'product.three_view_image_url'
  8883. )
  8884. ->get();
  8885. // 按 product_id 分组,合并 episode_number
  8886. $productMap = [];
  8887. foreach ($mappings as $item) {
  8888. $product_id = $item->product_id;
  8889. $product_name = $item->product_name;
  8890. // 处理product_name两边的符号
  8891. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8892. if (!isset($productMap[$product_id])) {
  8893. $productMap[$product_id] = [
  8894. 'product_id' => $product_id,
  8895. 'product_name' => $product_name,
  8896. 'type' => (int)$item->type,
  8897. 'product' => (int)$item->product,
  8898. 'pic_prompt' => $item->pic_prompt,
  8899. 'url' => $item->url,
  8900. 'pic_task_id' => $item->pic_task_id,
  8901. 'pic_task_status' => $item->pic_task_status,
  8902. 'episode_numbers' => [],
  8903. ];
  8904. }
  8905. // 添加 episode_number(去重)
  8906. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8907. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8908. }
  8909. }
  8910. // 将查询到的剧本资产合并到extra_products中
  8911. // 先构建extra_products的索引(以product_id+episode_number为key)
  8912. $extraProductsMap = [];
  8913. foreach ($extra_products as $item) {
  8914. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8915. $extraProductsMap[$key] = $item;
  8916. }
  8917. // 合并剧本资产(去重:product_id+episode_number)
  8918. foreach ($productMap as $product) {
  8919. foreach ($product['episode_numbers'] as $ep_num) {
  8920. $key = $product['product_id'] . '_' . $ep_num;
  8921. // 如果不存在则添加
  8922. if (!isset($extraProductsMap[$key])) {
  8923. $extraProductsMap[$key] = [
  8924. 'product_id' => $product['product_id'],
  8925. 'product_name' => $product['product_name'],
  8926. 'type' => $product['type'],
  8927. 'product' => $product['product'],
  8928. 'pic_prompt' => $product['pic_prompt'],
  8929. 'url' => $product['url'],
  8930. 'pic_task_id' => $product['pic_task_id'],
  8931. 'pic_task_status' => $product['pic_task_status'],
  8932. 'episode_number' => $ep_num,
  8933. ];
  8934. }
  8935. }
  8936. }
  8937. // 重新赋值给extra_products
  8938. $extra_products = array_values($extraProductsMap);
  8939. }
  8940. // 处理提示词
  8941. if ($prompt && $extra_products) {
  8942. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8943. foreach($extra_products as $item) {
  8944. $product_name = getProp($item, 'product_name');
  8945. if ($product_name) {
  8946. // 替换 {product_name} 为 product_name
  8947. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8948. }
  8949. }
  8950. }
  8951. // 获取最后一集序号
  8952. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8953. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8954. // 转换主体列表和场景列表的格式
  8955. // 获取参考主体或场景
  8956. if ((int)$episode_number === 1) {
  8957. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8958. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8959. }else {
  8960. $prev_episode_number = $episode_number - 1;
  8961. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8962. }
  8963. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8964. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8965. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8966. // 合并anime_products和extra_products(extra_products优先,去重)
  8967. $anime_products = getProp($anime, 'extra_products');
  8968. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8969. $ref_products = [];
  8970. foreach($anime_products as $item) {
  8971. $product_name = getProp($item, 'product_name');
  8972. $ref_products[$product_name] = $item;
  8973. }
  8974. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8975. $extra_roles = []; // 从extra_products中提取的角色
  8976. $extra_scenes = []; // 从extra_products中提取的场景
  8977. $extra_props = []; // 从extra_products中提取的道具
  8978. if ($extra_products && is_array($extra_products)) {
  8979. foreach($extra_products as $item) {
  8980. $product = (int)getProp($item, 'product');
  8981. $product_name = getProp($item, 'product_name');
  8982. if ($product_name == '旁白') continue;
  8983. $pic_prompt = getProp($item, 'pic_prompt');
  8984. $ref_products[$product_name] = $item;
  8985. if ($product === 1) {
  8986. // 角色
  8987. $extra_roles[$product_name] = [
  8988. 'role' => $product_name,
  8989. 'pic_prompt' => $pic_prompt,
  8990. 'url' => getProp($item, 'url', ''),
  8991. ];
  8992. } elseif ($product === 2) {
  8993. // 场景
  8994. $extra_scenes[$product_name] = [
  8995. 'scene' => $product_name,
  8996. 'pic_prompt' => $pic_prompt,
  8997. 'url' => getProp($item, 'url', ''),
  8998. ];
  8999. } elseif ($product === 3) {
  9000. // 道具
  9001. $extra_props[$product_name] = [
  9002. 'prop' => $product_name,
  9003. 'pic_prompt' => $pic_prompt,
  9004. 'url' => getProp($item, 'url', ''),
  9005. ];
  9006. }
  9007. }
  9008. }
  9009. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  9010. $merged_roles = [];
  9011. foreach($ref_roles as $role) {
  9012. $role_name = getProp($role, 'role');
  9013. if (!isset($extra_roles[$role_name])) {
  9014. $merged_roles[$role_name] = $role;
  9015. }
  9016. }
  9017. // 添加extra_roles
  9018. foreach($extra_roles as $role_name => $role) {
  9019. $merged_roles[$role_name] = $role;
  9020. }
  9021. $ref_roles = array_values($merged_roles);
  9022. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  9023. $merged_scenes = [];
  9024. foreach($ref_scenes as $scene) {
  9025. $scene_name = getProp($scene, 'scene');
  9026. if (!isset($extra_scenes[$scene_name])) {
  9027. $merged_scenes[$scene_name] = $scene;
  9028. }
  9029. }
  9030. // 添加extra_scenes
  9031. foreach($extra_scenes as $scene_name => $scene) {
  9032. $merged_scenes[$scene_name] = $scene;
  9033. }
  9034. $ref_scenes = array_values($merged_scenes);
  9035. // 合并ref_props和extra_props(extra_props优先,去重)
  9036. $merged_props = [];
  9037. foreach($ref_props as $prop) {
  9038. $prop_name = getProp($prop, 'prop');
  9039. if (!isset($extra_props[$prop_name])) {
  9040. $merged_props[$prop_name] = $prop;
  9041. }
  9042. }
  9043. // 添加extra_props
  9044. foreach($extra_props as $prop_name => $prop) {
  9045. $merged_props[$prop_name] = $prop;
  9046. }
  9047. $ref_props = array_values($merged_props);
  9048. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  9049. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  9050. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  9051. // 构建强制主体、场景和道具提示词
  9052. $forced_roles_prompt = "";
  9053. $forced_scenes_prompt = "";
  9054. $forced_props_prompt = "";
  9055. if (!empty($extra_roles)) {
  9056. $forced_roles_list = "";
  9057. foreach($extra_roles as $role_name => $role) {
  9058. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  9059. }
  9060. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9061. }
  9062. if (!empty($extra_scenes)) {
  9063. $forced_scenes_list = "";
  9064. foreach($extra_scenes as $scene_name => $scene) {
  9065. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  9066. }
  9067. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9068. }
  9069. if (!empty($extra_props)) {
  9070. $forced_props_list = "";
  9071. foreach($extra_props as $prop_name => $prop) {
  9072. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  9073. }
  9074. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9075. }
  9076. if ($anime_script_id) {
  9077. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  9078. }else if ($roles_content) {
  9079. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  9080. 主体范围:\n {$roles_content}\n
  9081. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  9082. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9083. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9084. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9085. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9086. }else {
  9087. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9088. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9089. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9090. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9091. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9092. }
  9093. if ($anime_script_id) {
  9094. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  9095. }else if ($scenes_content) {
  9096. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9097. 场景范围:\n {$scenes_content}\n
  9098. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  9099. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  9100. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9101. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9102. }else {
  9103. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9104. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9105. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9106. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9107. }
  9108. if ($anime_script_id) {
  9109. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  9110. }else if ($props_content) {
  9111. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9112. 道具范围:\n {$props_content}\n
  9113. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  9114. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  9115. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9116. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9117. }else {
  9118. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9119. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  9120. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9121. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9122. }
  9123. // 提取文件内容
  9124. if ($file) {
  9125. $uploaded_content = $this->extractFileContent($file);
  9126. if (!$uploaded_content) {
  9127. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9128. }
  9129. } elseif ($script_id) {
  9130. $uploaded_content = $this->getContentByScriptId($script_id);
  9131. if (!$uploaded_content) {
  9132. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9133. }
  9134. } elseif ($bid) {
  9135. $uploaded_content = $this->getContentByBid($bid);
  9136. if (!$uploaded_content) {
  9137. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9138. }
  9139. } elseif ($content) {
  9140. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  9141. }
  9142. // elseif ($prompt) {
  9143. // $uploaded_content = filterContent($prompt);
  9144. // }
  9145. else {
  9146. $uploaded_content = '';
  9147. }
  9148. // 美术风格
  9149. $input_art_style = getProp($data, 'art_style');
  9150. if (!$input_art_style) {
  9151. $mappedArtStyle = getProp($anime, 'art_style');
  9152. }else {
  9153. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9154. }
  9155. if (!$mappedArtStyle) {
  9156. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9157. }else {
  9158. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9159. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9160. }else {
  9161. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9162. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9163. }
  9164. }
  9165. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9166. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9167. // 强制要求:
  9168. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9169. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9170. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9171. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  9172. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  9173. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  9174. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  9175. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  9176. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  9177. // 10.分镜要和场景列表、人物主体保持一致\n
  9178. // 普通要求:
  9179. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9180. // {$role_demo}
  9181. // {$scene_demo}
  9182. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9183. // 4.1片段分割逻辑(优先级从高到低):
  9184. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9185. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9186. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9187. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9188. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9189. // - 片段数量格式为: 片段数量:8
  9190. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9191. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9192. // 4.3分镜结构:每个分镜包含以下字段:
  9193. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  9194. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  9195. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9196. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  9197. // - 运镜:场景+画面描述+运镜
  9198. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  9199. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9200. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9201. // 5.$mappedArtStyle_prompt\n\n
  9202. // 示例格式:\n
  9203. // 第1集:隐形的守护者
  9204. // ###故事梗概
  9205. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9206. // ###美术风格
  9207. // 基础画风风格词:胡金铨武侠
  9208. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9209. // ###主体列表
  9210. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9211. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9212. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9213. // ###场景列表
  9214. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9215. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9216. // ###分段剧本
  9217. // 片段数量:8
  9218. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9219. // ##片段1
  9220. // 时长:12s
  9221. // 分镜1
  9222. // 场景:边境小镇街道
  9223. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9224. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9225. // 配音台词:
  9226. // 背景音效:
  9227. // 分镜2
  9228. // 场景:悦来酒馆
  9229. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9230. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9231. // 配音台词:
  9232. // 背景音效:
  9233. // 分镜3
  9234. // 场景:悦来酒馆
  9235. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9236. // 运镜:从中景推向令牌特写。
  9237. // 配音台词:
  9238. // 背景音效:
  9239. // 分镜4
  9240. // 场景:悦来酒馆
  9241. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9242. // 运镜:极速推向酒水溅起的瞬间。
  9243. // 配音台词:
  9244. // 背景音效:
  9245. // 分镜5
  9246. // 镜头描述
  9247. // 场景:悦来酒馆
  9248. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9249. // 运镜:固定机位,利用倾斜构图制造压迫感。
  9250. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9251. // 背景音效:
  9252. // \n\n";
  9253. /*
  9254. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  9255. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  9256. // ===================================================================
  9257. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9258. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9259. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9260. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9261. 强制要求:
  9262. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9263. 普通要求:
  9264. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9265. {$role_demo}
  9266. {$scene_demo}
  9267. {$prop_demo}
  9268. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9269. 5.1片段分割逻辑(优先级从高到低):
  9270. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9271. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9272. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9273. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9274. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9275. - 片段数量格式为: 片段数量:8
  9276. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9277. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9278. 5.3分镜结构:每个分镜包含以下字段:
  9279. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9280. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9281. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9282. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9283. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9284. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9285. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9286. - 运镜:场景+画面描述+运镜
  9287. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9288. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9289. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9290. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9291. 6.《情绪-视听语言映射表》:
  9292. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9293. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9294. -----|---------|------------|----------------
  9295. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9296. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9297. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9298. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9299. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9300. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9301. -----|---------|------------|----------------
  9302. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9303. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9304. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9305. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9306. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9307. --------|---------|--------------|-------------
  9308. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9309. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9310. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9311. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9312. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9313. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9314. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9315. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9316. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9317. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9318. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9319. -----|---------|------------|------------
  9320. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9321. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9322. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9323. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9324. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9325. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9326. --------|---------|--------------|----------
  9327. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9328. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9329. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9330. 6.6 声音设计与潜意识影响 (Soundscape)
  9331. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9332. -----|---------|------------|------------------
  9333. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9334. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9335. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9336. 理论基石:
  9337. - The Five C's of Cinematography by Joseph V. Mascelli
  9338. - Film Art: An Introduction by David Bordwell
  9339. - Sight, Sound, Motion by Herbert Zettl
  9340. - Notes on the Cinematograph by Robert Bresson
  9341. \n\n
  9342. 7.{$mappedArtStyle_prompt}
  9343. 示例格式:\n
  9344. 第1集:隐形的守护者
  9345. ###故事梗概
  9346. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9347. ###美术风格
  9348. 基础画风风格词:胡金铨武侠
  9349. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9350. ###主体列表
  9351. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9352. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9353. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9354. ###场景列表
  9355. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9356. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9357. ###道具列表
  9358. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9359. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9360. ###分段剧本
  9361. 片段数量:8
  9362. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9363. ##片段1
  9364. 时长:12s
  9365. 分镜1
  9366. 出场角色:刀疤脸
  9367. 场景:边境小镇街道
  9368. 出场道具:酒杯-高脚杯
  9369. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9370. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9371. 配音台词:
  9372. 背景音效:
  9373. 分镜2
  9374. 出场角色:刀疤脸
  9375. 场景:悦来酒馆
  9376. 出场道具:酒杯-高脚杯
  9377. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9378. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9379. 配音台词:
  9380. 背景音效:
  9381. 分镜3
  9382. 出场角色:刀疤脸
  9383. 场景:悦来酒馆
  9384. 出场道具:酒杯-高脚杯
  9385. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9386. 运镜:从中景推向令牌特写。
  9387. 配音台词:
  9388. 背景音效:
  9389. 分镜4
  9390. 出场角色:刀疤脸
  9391. 场景:悦来酒馆
  9392. 出场道具:酒杯-高脚杯
  9393. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9394. 运镜:极速推向酒水溅起的瞬间。
  9395. 配音台词:
  9396. 背景音效:
  9397. 分镜5
  9398. 出场角色:刀疤脸
  9399. 场景:悦来酒馆
  9400. 出场道具:酒杯-高脚杯
  9401. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9402. 运镜:固定机位,利用倾斜构图制造压迫感。
  9403. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9404. 背景音效:
  9405. \n\n";
  9406. */
  9407. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9408. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9409. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9410. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9411. 强制要求:
  9412. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9413. 普通要求:
  9414. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  9415. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  9416. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  9417. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  9418. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9419. 5.1片段分割逻辑(优先级从高到低):
  9420. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9421. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9422. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9423. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9424. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9425. - 片段数量格式为: 片段数量:8
  9426. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9427. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9428. 5.3分镜结构:每个分镜包含以下字段:
  9429. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9430. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9431. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9432. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9433. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9434. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9435. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9436. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9437. - 运镜:场景+画面描述+运镜
  9438. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9439. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9440. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9441. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9442. 6.《情绪-视听语言映射表》:
  9443. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9444. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9445. -----|---------|------------|----------------
  9446. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9447. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9448. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9449. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9450. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9451. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9452. -----|---------|------------|----------------
  9453. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9454. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9455. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9456. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9457. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9458. --------|---------|--------------|-------------
  9459. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9460. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9461. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9462. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9463. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9464. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9465. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9466. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9467. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9468. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9469. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9470. -----|---------|------------|------------
  9471. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9472. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9473. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9474. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9475. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9476. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9477. --------|---------|--------------|----------
  9478. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9479. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9480. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9481. 6.6 声音设计与潜意识影响 (Soundscape)
  9482. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9483. -----|---------|------------|------------------
  9484. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9485. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9486. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9487. 理论基石:
  9488. - The Five C's of Cinematography by Joseph V. Mascelli
  9489. - Film Art: An Introduction by David Bordwell
  9490. - Sight, Sound, Motion by Herbert Zettl
  9491. - Notes on the Cinematograph by Robert Bresson
  9492. \n\n
  9493. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9494. 示例格式:\n
  9495. 第1集:隐形的守护者
  9496. ###故事梗概
  9497. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9498. ###美术风格
  9499. 基础画风风格词:胡金铨武侠
  9500. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9501. ###主体列表
  9502. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9503. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9504. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9505. ###场景列表
  9506. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9507. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9508. ###道具列表
  9509. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9510. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9511. ###分段剧本
  9512. 片段数量:8
  9513. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9514. ##片段1
  9515. 时长:12s
  9516. 分镜1
  9517. 出场角色:刀疤脸
  9518. 场景:边境小镇街道
  9519. 出场道具:酒杯-高脚杯
  9520. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9521. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9522. 配音台词:
  9523. 背景音效:
  9524. 分镜2
  9525. 出场角色:刀疤脸
  9526. 场景:悦来酒馆
  9527. 出场道具:酒杯-高脚杯
  9528. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9529. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9530. 配音台词:
  9531. 背景音效:
  9532. 分镜3
  9533. 出场角色:刀疤脸
  9534. 场景:悦来酒馆
  9535. 出场道具:酒杯-高脚杯
  9536. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9537. 运镜:从中景推向令牌特写。
  9538. 配音台词:
  9539. 背景音效:
  9540. 分镜4
  9541. 出场角色:刀疤脸
  9542. 场景:悦来酒馆
  9543. 出场道具:酒杯-高脚杯
  9544. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9545. 运镜:极速推向酒水溅起的瞬间。
  9546. 配音台词:
  9547. 背景音效:
  9548. 分镜5
  9549. 出场角色:刀疤脸
  9550. 场景:悦来酒馆
  9551. 出场道具:酒杯-高脚杯
  9552. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9553. 运镜:固定机位,利用倾斜构图制造压迫感。
  9554. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9555. 背景音效:
  9556. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9557. 【本次剧集信息】剧集序号是{$episode_number}。
  9558. 【本次生成数据-主体列表】{$role_demo}
  9559. 【本次生成数据-场景列表】{$scene_demo}
  9560. 【本次生成数据-道具列表】{$prop_demo}
  9561. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9562. \n\n";
  9563. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9564. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  9565. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9566. $is_regenerate_version = true;
  9567. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9568. $prompt = $origin_prompt;
  9569. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9570. // 获取章节内容
  9571. $full_content = getProp($anime, 'content');
  9572. if ($uploaded_content) {
  9573. $full_content = $uploaded_content;
  9574. }
  9575. // 根据章节内容拆分章节
  9576. $chapters = splitContent($full_content);
  9577. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9578. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9579. $messages = [];
  9580. if ($prompt == '确认分镜大纲') {
  9581. // 暂时保留
  9582. $content = $chapter_content;
  9583. if ($is_single) $content = $full_content; // 单剧集使用全文
  9584. if (!$content) {
  9585. Utils::throwError('20003:章节内容无法获取,请确认');
  9586. }
  9587. $question = $is_single
  9588. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9589. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9590. // 构建消息
  9591. $messages[] =
  9592. [
  9593. 'role' => 'user',
  9594. 'content' => $question
  9595. ];
  9596. }else if ($prompt == '继续策划下一集') {
  9597. if ($is_single) {
  9598. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9599. }
  9600. $content = $chapter_content;
  9601. if (!$content) {
  9602. Utils::throwError('20003:章节内容无法获取,请确认');
  9603. }
  9604. // 获取上一集最后记录
  9605. $prev_sequence = $episode_number - 1;
  9606. $messages = array_merge(
  9607. [
  9608. [
  9609. 'role' => 'system',
  9610. 'content' => $demo
  9611. ]
  9612. ],
  9613. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9614. );
  9615. // 构建消息
  9616. $messages[] =
  9617. [
  9618. 'role' => 'user',
  9619. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9620. ];
  9621. /*
  9622. // 旧版逻辑
  9623. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9624. // 构建消息
  9625. $messages[] =
  9626. [
  9627. 'role' => 'user',
  9628. 'content' => $question
  9629. ];
  9630. */
  9631. // dd($messages);
  9632. }else {
  9633. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9634. if (!$content) {
  9635. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9636. }
  9637. if (!$content) {
  9638. Utils::throwError('20003:章节内容无法获取,请确认');
  9639. }
  9640. $messages = array_merge(
  9641. [
  9642. [
  9643. 'role' => 'system',
  9644. 'content' => $demo
  9645. ]
  9646. ],
  9647. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9648. );
  9649. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9650. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9651. if ($origin_prompt) {
  9652. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9653. }
  9654. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9655. $messages[] = [
  9656. 'role' => 'user',
  9657. 'content' => "本集剧情内容:\n\n{$content}\n"
  9658. ];
  9659. $messages[] =
  9660. [
  9661. 'role' => 'user',
  9662. 'content' => $question
  9663. ];
  9664. }
  9665. // 处理文本模型
  9666. $model = getProp($data, 'model');
  9667. if (!$model) {
  9668. // 用户没有输入,从anime表获取
  9669. $model = getProp($anime, 'model');
  9670. if (!$model) {
  9671. // anime表也没有,使用默认值
  9672. $model = 'deepseek-v4-pro';
  9673. }
  9674. }
  9675. // 验证模型是否在可用模型表中
  9676. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9677. $model = 'deepseek-v4-pro';
  9678. }
  9679. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9680. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9681. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9682. if ($model === 'deepseek-chat') {
  9683. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9684. $model = 'deepseek-v4-flash';
  9685. $thinkingMode = 'disabled';
  9686. } elseif ($model === 'deepseek-reasoner') {
  9687. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9688. $model = 'deepseek-v4-flash';
  9689. $thinkingMode = 'enabled';
  9690. }
  9691. $post_data = [
  9692. 'model' => $model,
  9693. 'messages' => $messages,
  9694. // 'max_tokens' => 8192,
  9695. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9696. 'frequency_penalty' => 0,
  9697. 'presence_penalty' => 0,
  9698. 'response_format' => ['type' => 'text'],
  9699. 'thinking' => ['type' => $thinkingMode],
  9700. 'stream' => true // 启用流式输出
  9701. ];
  9702. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9703. // 根据模型类型选择调用方法
  9704. $fullContent = '';
  9705. $fullReasoningContent = '';
  9706. $usage = [];
  9707. try {
  9708. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9709. // DeepSeek 官方模型使用 DeepSeek API
  9710. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9711. } else if (in_array($model, $this->gpt_text_models)) {
  9712. // GPT-5.4 模型使用 TokenRouter API
  9713. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9714. } else if (in_array($model, $this->gemini_text_models)) {
  9715. // Gemini 模型使用 Gemini API
  9716. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9717. } else {
  9718. // 其他模型使用火山引擎API
  9719. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9720. }
  9721. // 验证返回值类型
  9722. if (!is_iterable($streamGenerator)) {
  9723. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9724. dLog('deepseek')->error('chat流式生成器无效', [
  9725. 'generator_type' => $errorType,
  9726. 'model' => $model,
  9727. 'anime_id' => $anime_id,
  9728. 'episode_number' => $episode_number
  9729. ]);
  9730. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9731. 'type' => $errorType,
  9732. 'model' => $model
  9733. ]);
  9734. yield [
  9735. 'type' => 'error',
  9736. 'episode' => [],
  9737. 'answer' => '',
  9738. 'reasoning' => '',
  9739. 'usage' => [],
  9740. 'error' => '接口返回数据异常,请重新请求'
  9741. ];
  9742. return;
  9743. }
  9744. // 处理流式输出
  9745. foreach ($streamGenerator as $chunk) {
  9746. if (isset($chunk['type'])) {
  9747. if ($chunk['type'] === 'done') {
  9748. // 最终结果
  9749. $fullContent = $chunk['full_content'];
  9750. $fullReasoningContent = $chunk['full_reasoning'];
  9751. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9752. } else {
  9753. // 逐块yield数据
  9754. yield $chunk;
  9755. }
  9756. }
  9757. }
  9758. } catch (\Exception $e) {
  9759. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9760. 'model' => $model,
  9761. 'anime_id' => $anime_id,
  9762. 'episode_number' => $episode_number,
  9763. 'trace' => $e->getTraceAsString()
  9764. ]);
  9765. logDB('deepseek', 'error', 'chat流式处理失败', [
  9766. 'error' => $e->getMessage(),
  9767. 'model' => $model
  9768. ]);
  9769. yield [
  9770. 'type' => 'error',
  9771. 'episode' => [],
  9772. 'answer' => '',
  9773. 'reasoning' => '',
  9774. 'usage' => [],
  9775. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9776. ];
  9777. return;
  9778. }
  9779. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9780. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9781. dLog('deepseek')->info('完整内容: '.$fullContent);
  9782. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9783. // 处理完整内容并返回最终结果
  9784. $episode_arr = handleEpisodeContentForAce($fullContent);
  9785. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9786. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9787. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9788. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9789. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9790. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9791. // }
  9792. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9793. $max_retries = 3;
  9794. $retry_count = 0;
  9795. $validation_failed = false;
  9796. $validation_error_msg = '';
  9797. // 验证生成的内容
  9798. if ($anime_script_id) {
  9799. // 检查是否有acts数据
  9800. if (empty($episode_arr['acts'])) {
  9801. $validation_failed = true;
  9802. $validation_error_msg = '未生成分镜剧本相关的内容';
  9803. } else {
  9804. // 校验主体列表:不能为空主体(旁白不算)
  9805. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9806. // 过滤掉"旁白"角色
  9807. $generated_roles = array_filter($generated_roles, function($role) {
  9808. return $role !== '旁白';
  9809. });
  9810. if (empty($generated_roles)) {
  9811. $validation_failed = true;
  9812. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9813. }
  9814. // 仅当存在强制主体设定时校验主体列表
  9815. if (!$validation_failed && !empty($extra_roles)) {
  9816. $expected_roles = array_keys($extra_roles);
  9817. // 找出生成的主体中不在预期列表中的主体
  9818. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9819. if (!empty($invalid_roles)) {
  9820. $validation_failed = true;
  9821. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9822. }
  9823. }
  9824. // 仅当存在强制场景设定时校验场景列表
  9825. if (!$validation_failed && !empty($extra_scenes)) {
  9826. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9827. $expected_scenes = array_keys($extra_scenes);
  9828. // 找出生成的场景中不在预期列表中的场景
  9829. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9830. if (!empty($invalid_scenes)) {
  9831. $validation_failed = true;
  9832. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9833. }
  9834. }
  9835. // 仅当存在强制道具设定时校验道具列表
  9836. if (!$validation_failed && !empty($extra_props)) {
  9837. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9838. $expected_props = array_keys($extra_props);
  9839. // 找出生成的道具中不在预期列表中的道具
  9840. $invalid_props = array_diff($generated_props, $expected_props);
  9841. if (!empty($invalid_props)) {
  9842. $validation_failed = true;
  9843. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9844. }
  9845. }
  9846. }
  9847. } else {
  9848. // 如果没有anime_script_id,只检查是否有acts数据
  9849. if (empty($episode_arr['acts'])) {
  9850. $validation_failed = true;
  9851. $validation_error_msg = '未生成分镜剧本相关的内容';
  9852. } else {
  9853. // 校验主体列表:不能为空主体(旁白不算)
  9854. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9855. // 过滤掉"旁白"角色
  9856. $generated_roles = array_filter($generated_roles, function($role) {
  9857. return $role !== '旁白';
  9858. });
  9859. if (empty($generated_roles)) {
  9860. $validation_failed = true;
  9861. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9862. }
  9863. }
  9864. }
  9865. // 重试逻辑
  9866. while ($validation_failed && $retry_count < $max_retries) {
  9867. $retry_count++;
  9868. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9869. 'reason' => $validation_error_msg,
  9870. 'anime_id' => $anime_id,
  9871. 'episode_number' => $episode_number
  9872. ]);
  9873. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9874. 'reason' => $validation_error_msg,
  9875. 'anime_id' => $anime_id
  9876. ]);
  9877. // 发送流式重试提示
  9878. yield [
  9879. 'type' => 'retry',
  9880. 'retry_count' => $retry_count,
  9881. 'reason' => $validation_error_msg
  9882. ];
  9883. // 构建重试提示词
  9884. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9885. if ($anime_script_id) {
  9886. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9887. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9888. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9889. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9890. } else {
  9891. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9892. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9893. }
  9894. // 添加重试消息到messages
  9895. $messages[] = [
  9896. 'role' => 'assistant',
  9897. 'content' => $fullContent
  9898. ];
  9899. $messages[] = [
  9900. 'role' => 'user',
  9901. 'content' => $retry_prompt
  9902. ];
  9903. // 更新post_data的messages
  9904. $post_data['messages'] = $messages;
  9905. // 重新调用API
  9906. try {
  9907. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9908. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9909. } else if (in_array($model, $this->gpt_text_models)) {
  9910. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9911. } else if (in_array($model, $this->gemini_text_models)) {
  9912. // Gemini 模型使用 Gemini API
  9913. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9914. } else {
  9915. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9916. }
  9917. // 处理流式输出
  9918. $fullContent = '';
  9919. $fullReasoningContent = '';
  9920. foreach ($streamGenerator as $chunk) {
  9921. if (isset($chunk['type'])) {
  9922. if ($chunk['type'] === 'done') {
  9923. $fullContent = $chunk['full_content'];
  9924. $fullReasoningContent = $chunk['full_reasoning'];
  9925. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9926. } else {
  9927. yield $chunk;
  9928. }
  9929. }
  9930. }
  9931. // 重新解析内容
  9932. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9933. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9934. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9935. $episode_arr = handleEpisodeContentForAce($fullContent);
  9936. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9937. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9938. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9939. // }
  9940. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9941. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9942. // 重新验证
  9943. $validation_failed = false;
  9944. $validation_error_msg = '';
  9945. if ($anime_script_id) {
  9946. if (empty($episode_arr['acts'])) {
  9947. $validation_failed = true;
  9948. $validation_error_msg = '未生成分镜剧本相关的内容';
  9949. } else {
  9950. // 校验主体列表:不能为空主体(旁白不算)
  9951. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9952. // 过滤掉"旁白"角色
  9953. $generated_roles = array_filter($generated_roles, function($role) {
  9954. return $role !== '旁白';
  9955. });
  9956. if (empty($generated_roles)) {
  9957. $validation_failed = true;
  9958. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9959. }
  9960. // 仅当存在强制主体设定时校验主体列表
  9961. if (!$validation_failed && !empty($extra_roles)) {
  9962. $expected_roles = array_keys($extra_roles);
  9963. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9964. if (!empty($invalid_roles)) {
  9965. $validation_failed = true;
  9966. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9967. }
  9968. }
  9969. // 仅当存在强制场景设定时校验场景列表
  9970. if (!$validation_failed && !empty($extra_scenes)) {
  9971. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9972. $expected_scenes = array_keys($extra_scenes);
  9973. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9974. if (!empty($invalid_scenes)) {
  9975. $validation_failed = true;
  9976. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9977. }
  9978. }
  9979. // 仅当存在强制道具设定时校验道具列表
  9980. if (!$validation_failed && !empty($extra_props)) {
  9981. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9982. $expected_props = array_keys($extra_props);
  9983. $invalid_props = array_diff($generated_props, $expected_props);
  9984. if (!empty($invalid_props)) {
  9985. $validation_failed = true;
  9986. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9987. }
  9988. }
  9989. }
  9990. } else {
  9991. if (empty($episode_arr['acts'])) {
  9992. $validation_failed = true;
  9993. $validation_error_msg = '未生成分镜剧本相关的内容';
  9994. } else {
  9995. // 校验主体列表:不能为空主体(旁白不算)
  9996. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9997. // 过滤掉"旁白"角色
  9998. $generated_roles = array_filter($generated_roles, function($role) {
  9999. return $role !== '旁白';
  10000. });
  10001. if (empty($generated_roles)) {
  10002. $validation_failed = true;
  10003. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10004. }
  10005. }
  10006. }
  10007. } catch (\Exception $e) {
  10008. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  10009. 'trace' => $e->getTraceAsString()
  10010. ]);
  10011. break;
  10012. }
  10013. }
  10014. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  10015. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  10016. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  10017. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  10018. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  10019. if ($validation_failed && $retry_count >= $max_retries) {
  10020. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  10021. 'retry_count' => $retry_count,
  10022. 'last_error' => $validation_error_msg
  10023. ]);
  10024. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  10025. 'error' => $validation_error_msg,
  10026. 'anime_id' => $anime_id
  10027. ]);
  10028. $validation_failed = false;
  10029. $validation_error_msg = '';
  10030. }
  10031. // 如果重试后仍然失败
  10032. if ($validation_failed) {
  10033. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  10034. 'retry_count' => $retry_count,
  10035. 'last_error' => $validation_error_msg
  10036. ]);
  10037. try {
  10038. $now = date('Y-m-d H:i:s');
  10039. $records = [
  10040. [
  10041. 'uid' => $uid,
  10042. 'anime_id' => $anime_id,
  10043. 'sequence' => $episode_number,
  10044. 'role' => 'user',
  10045. 'content' => $prompt,
  10046. 'created_at' => $now,
  10047. 'updated_at' => $now
  10048. ],
  10049. [
  10050. 'uid' => $uid,
  10051. 'anime_id' => $anime_id,
  10052. 'sequence' => $episode_number,
  10053. 'role' => 'assistant',
  10054. 'content' => $fullContent,
  10055. 'created_at' => $now,
  10056. 'updated_at' => $now
  10057. ]
  10058. ];
  10059. DB::table('mp_anime_records')->insert($records);
  10060. } catch (\Exception $e) {
  10061. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  10062. }
  10063. yield [
  10064. 'type' => 'done',
  10065. 'episode' => [],
  10066. 'answer' => $fullContent,
  10067. 'reasoning' => $fullReasoningContent,
  10068. 'usage' => $usage,
  10069. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  10070. ];
  10071. return;
  10072. }
  10073. // 验证成功,记录日志
  10074. if ($retry_count > 0) {
  10075. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  10076. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  10077. }
  10078. // 老逻辑
  10079. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  10080. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  10081. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  10082. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  10083. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  10084. $existing_props = is_array($existing_props) ? $existing_props : [];
  10085. $now = date('Y-m-d H:i:s');
  10086. try {
  10087. DB::beginTransaction();
  10088. $saveResult = $this->saveEpisodeVersionData(
  10089. $anime_id,
  10090. $episode_number,
  10091. $episode_arr,
  10092. $existing_roles,
  10093. $existing_scenes,
  10094. $existing_props,
  10095. $current_episode,
  10096. $base_episode,
  10097. $is_regenerate_version,
  10098. $content,
  10099. $now,
  10100. $ref_products
  10101. );
  10102. $episode = $saveResult['episode'];
  10103. $episode_id = $saveResult['episode_id'];
  10104. $merged_roles = $saveResult['merged_roles'];
  10105. $merged_scenes = $saveResult['merged_scenes'];
  10106. $merged_props = $saveResult['merged_props'];
  10107. $record_content = $origin_prompt;
  10108. if ($uploaded_content !== '') {
  10109. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  10110. }
  10111. $records = [
  10112. [
  10113. 'uid' => $uid,
  10114. 'anime_id' => $anime_id,
  10115. 'role' => 'user',
  10116. 'content' => $record_content,
  10117. 'sequence' => $episode_number,
  10118. 'episode_id' => $episode_id,
  10119. 'created_at' => $now,
  10120. 'updated_at' => $now
  10121. ],
  10122. [
  10123. 'uid' => $uid,
  10124. 'anime_id' => $anime_id,
  10125. 'role' => 'assistant',
  10126. 'content' => $fullContent,
  10127. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10128. 'sequence' => $episode_number,
  10129. 'episode_id' => $episode_id,
  10130. 'created_at' => $now,
  10131. 'updated_at' => $now
  10132. ]
  10133. ];
  10134. $boolen4 = DB::table('mp_anime_records')->insert($records);
  10135. if (!$boolen4) {
  10136. Utils::throwError('20003:对话记录保存失败');
  10137. }
  10138. // 保存模型到anime表
  10139. $update_anime_data = [
  10140. 'model' => $model,
  10141. 'updated_at' => $now
  10142. ];
  10143. if ($uploaded_content) {
  10144. $update_anime_data['content'] = $uploaded_content;
  10145. }
  10146. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  10147. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10148. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10149. 'anime_id' => $anime_id,
  10150. 'episode_number' => $episode_number,
  10151. 'model' => $model,
  10152. 'source' => 'chatForAce',
  10153. ]);
  10154. }catch (\Exception $e) {
  10155. DB::rollBack();
  10156. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  10157. yield [
  10158. 'type' => 'done',
  10159. 'answer' => $fullContent,
  10160. 'reasoning' => $fullReasoningContent,
  10161. 'usage' => $usage,
  10162. 'error' => $e->getMessage(),
  10163. ];
  10164. return;
  10165. }
  10166. DB::commit();
  10167. if ($is_global_generate_pics) {
  10168. // // 批量生成全局角色图片
  10169. // $this->batchSetGlobalRoleImg([
  10170. // 'anime_id' => $anime_id,
  10171. // ], true);
  10172. // // 批量生成全局场景图片
  10173. // $this->batchSetGlobalSceneImg([
  10174. // 'anime_id' => $anime_id,
  10175. // ], true);
  10176. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10177. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10178. }
  10179. $episode['episode_id'] = $episode_id;
  10180. $episode['roles'] = $merged_roles;
  10181. $episode['scenes'] = $merged_scenes;
  10182. $episode['props'] = $merged_props;
  10183. $episode['end_episode_sequence'] = $end_episode_sequence;
  10184. // 获取mp_animes表中的视频参数
  10185. $episode['video_params'] = [
  10186. 'video_model' => getProp($anime, 'video_model'),
  10187. 'video_resolution' => getProp($anime, 'video_resolution'),
  10188. 'ratio' => getProp($anime, 'video_ratio'),
  10189. ];
  10190. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10191. yield [
  10192. 'type' => 'done',
  10193. 'episode' => $episode,
  10194. 'answer' => $fullContent,
  10195. 'reasoning' => $fullReasoningContent,
  10196. 'usage' => $usage
  10197. ];
  10198. }
  10199. /**
  10200. * chatForAce的非流式版本 - 用于定时任务
  10201. * 只获取最终 type=done 的数据,并验证必要字段
  10202. *
  10203. * @param array $data 请求数据
  10204. * @return array 生成结果
  10205. */
  10206. public function chatForAceNonStream($data) {
  10207. $finalResult = null;
  10208. // 调用流式方法,只保存 type=done 的数据
  10209. foreach ($this->chatForAce($data) as $chunk) {
  10210. // 只关注最终结果
  10211. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  10212. $finalResult = $chunk;
  10213. break; // 找到 done 就退出循环
  10214. }
  10215. }
  10216. // 验证最终结果
  10217. if (!$finalResult) {
  10218. return ['error' => '生成失败:未获取到最终结果'];
  10219. }
  10220. // 检查是否有错误
  10221. if (isset($finalResult['error']) && $finalResult['error']) {
  10222. return $finalResult;
  10223. }
  10224. // 验证必要字段
  10225. $episode = $finalResult['episode'] ?? [];
  10226. // 验证 roles(旁白不算主体,过滤后不能为空)
  10227. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  10228. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  10229. }
  10230. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  10231. return $role !== '旁白';
  10232. });
  10233. if (empty($nonNarratorRoles)) {
  10234. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  10235. }
  10236. // 验证 scenes
  10237. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  10238. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  10239. }
  10240. // 验证 props(道具可以为空,但必须存在且为数组)
  10241. if (!isset($episode['props']) || !is_array($episode['props'])) {
  10242. $episode['props'] = [];
  10243. }
  10244. // 验证 acts(分镜剧本)
  10245. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  10246. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  10247. }
  10248. // 更新验证后的 episode 数据
  10249. $finalResult['episode'] = $episode;
  10250. // 记录验证成功日志
  10251. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  10252. 'roles_count' => count($episode['roles']),
  10253. 'scenes_count' => count($episode['scenes']),
  10254. 'props_count' => count($episode['props']),
  10255. 'acts_count' => count($episode['acts'])
  10256. ]);
  10257. return $finalResult;
  10258. }
  10259. /**
  10260. * 批量生成多个分集
  10261. *
  10262. * @param array $data 请求数据
  10263. * @return array 任务信息
  10264. */
  10265. public function batchGenerateEpisodes($data) {
  10266. $uid = Site::getUid();
  10267. $cpid = Site::getCpid();
  10268. $anime_id = getProp($data, 'anime_id');
  10269. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  10270. $start_episode_number = getProp($data, 'start_episode_number');
  10271. $end_episode_number = getProp($data, 'end_episode_number');
  10272. if (!$anime_id) {
  10273. Utils::throwError('20003:anime_id参数缺失');
  10274. }
  10275. if ($generate_episode_number < 1) {
  10276. Utils::throwError('20003:生成集数必须大于0');
  10277. }
  10278. // 获取动漫信息
  10279. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10280. if (!$anime) {
  10281. Utils::throwError('20003:该剧集不存在');
  10282. }
  10283. // 检查是否是全能模式
  10284. if ((int)getProp($anime, 'ace_mode') !== 1) {
  10285. Utils::throwError('20003:只有全能模式才支持批量生成');
  10286. }
  10287. // 检查是否是多剧集模式
  10288. if ((int)getProp($anime, 'is_multi') !== 1) {
  10289. Utils::throwError('20003:单剧集不支持批量生成');
  10290. }
  10291. // 指定起始/结束剧集序号时的校验
  10292. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  10293. || ($end_episode_number !== null && $end_episode_number !== '');
  10294. if ($hasSpecifiedRange) {
  10295. if ($start_episode_number === null || $start_episode_number === ''
  10296. || $end_episode_number === null || $end_episode_number === '') {
  10297. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  10298. }
  10299. $start_episode_number = (int)$start_episode_number;
  10300. $end_episode_number = (int)$end_episode_number;
  10301. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  10302. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  10303. }
  10304. $startEpisodeNumber = $start_episode_number;
  10305. $endEpisodeNumber = $end_episode_number;
  10306. } else {
  10307. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  10308. $currentMaxEpisode = DB::table('mp_anime_episodes')
  10309. ->where('anime_id', $anime_id)
  10310. ->where('is_default', 1)
  10311. ->max('episode_number');
  10312. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  10313. // 确定起始集数
  10314. $startEpisodeNumber = $currentMaxEpisode + 1;
  10315. // 计算结束集数
  10316. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  10317. }
  10318. // 本次实际生成的集数
  10319. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  10320. // 检查是否超过总集数限制
  10321. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  10322. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  10323. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  10324. }
  10325. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  10326. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  10327. ->where('anime_id', $anime_id)
  10328. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10329. ->pluck('episode_number')
  10330. ->unique()
  10331. ->sort()
  10332. ->values()
  10333. ->toArray();
  10334. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  10335. ->where('anime_id', $anime_id)
  10336. ->where('is_default', 1)
  10337. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10338. ->pluck('episode_number')
  10339. ->unique()
  10340. ->sort()
  10341. ->values()
  10342. ->toArray();
  10343. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  10344. $duplicateMessages = [];
  10345. if (!empty($duplicatedBatchEpisodes)) {
  10346. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  10347. }
  10348. if (!empty($duplicatedAnimeEpisodes)) {
  10349. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  10350. }
  10351. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  10352. }
  10353. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  10354. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  10355. ->where('anime_id', $anime_id)
  10356. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10357. ->whereIn('status', ['pending', 'processing', 'completed'])
  10358. ->count();
  10359. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  10360. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  10361. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  10362. if ($needEpisodeCount > 0) {
  10363. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  10364. }
  10365. $now = date('Y-m-d H:i:s');
  10366. $createdTasks = [];
  10367. $skippedTasks = [];
  10368. // 为每一集创建详情记录
  10369. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  10370. // 检查是否已有该集的任务记录
  10371. $existingTask = DB::table('mp_batch_episode_generation_details')
  10372. ->where('anime_id', $anime_id)
  10373. ->where('episode_number', $episodeNumber)
  10374. ->first();
  10375. if ($existingTask) {
  10376. // 如果已存在且未完成,跳过
  10377. if (in_array($existingTask->status, ['pending', 'processing'])) {
  10378. $skippedTasks[] = $episodeNumber;
  10379. continue;
  10380. }
  10381. // 如果是失败状态,可以重新创建(删除旧记录)
  10382. if ($existingTask->status === 'failed') {
  10383. DB::table('mp_batch_episode_generation_details')
  10384. ->where('id', $existingTask->id)
  10385. ->delete();
  10386. }
  10387. // 如果是已完成状态,也跳过
  10388. if ($existingTask->status === 'completed') {
  10389. $skippedTasks[] = $episodeNumber;
  10390. continue;
  10391. }
  10392. }
  10393. // 准备任务数据
  10394. $taskData = [
  10395. 'anime_id' => $anime_id,
  10396. 'uid' => $uid,
  10397. 'cpid' => $cpid,
  10398. 'episode_number' => $episodeNumber,
  10399. 'status' => 'pending',
  10400. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  10401. 'retry_count' => 0,
  10402. 'created_at' => $now,
  10403. 'updated_at' => $now
  10404. ];
  10405. // 创建任务记录
  10406. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  10407. if ($taskId) {
  10408. $createdTasks[] = $episodeNumber;
  10409. }
  10410. }
  10411. if (empty($createdTasks)) {
  10412. if (!empty($skippedTasks)) {
  10413. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  10414. } else {
  10415. Utils::throwError('20003:创建批量生成任务失败');
  10416. }
  10417. }
  10418. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  10419. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  10420. $uid,
  10421. $cpid,
  10422. $anime_id,
  10423. $generate_episode_number,
  10424. $startEpisodeNumber,
  10425. $endEpisodeNumber
  10426. );
  10427. return [
  10428. 'anime_id' => $anime_id,
  10429. 'start_episode' => $startEpisodeNumber,
  10430. 'end_episode' => $endEpisodeNumber,
  10431. 'total_episodes' => $totalEpisodeCount,
  10432. 'created_episodes' => $createdTasks,
  10433. 'skipped_episodes' => $skippedTasks,
  10434. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  10435. "已创建: " . implode(',', $createdTasks) .
  10436. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  10437. 'task_center_id' => $taskCenterId
  10438. ];
  10439. }
  10440. /**
  10441. * 根据入参创建或复用批量生成分集的任务中心记录
  10442. *
  10443. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  10444. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  10445. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  10446. *
  10447. * @param int|string $uid
  10448. * @param int|string $cpid
  10449. * @param int|string $anime_id
  10450. * @param int $generate_episode_number
  10451. * @param int $startEpisodeNumber
  10452. * @param int $endEpisodeNumber
  10453. * @return int 任务中心ID
  10454. */
  10455. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  10456. $params = [
  10457. 'anime_id' => (int)$anime_id,
  10458. 'generate_episode_number' => (int)$generate_episode_number,
  10459. 'start_episode' => (int)$startEpisodeNumber,
  10460. 'end_episode' => (int)$endEpisodeNumber,
  10461. ];
  10462. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  10463. $paramsMd5 = md5(json_encode([
  10464. 'anime_id' => (int)$anime_id,
  10465. 'generate_episode_number' => (int)$generate_episode_number,
  10466. 'start_episode' => (int)$startEpisodeNumber,
  10467. 'end_episode' => (int)$endEpisodeNumber,
  10468. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  10469. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  10470. $existing = DB::table('mp_task_center')
  10471. ->where('uid', (int)$uid)
  10472. ->where('cpid', (int)$cpid)
  10473. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10474. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10475. ->where('params_md5', $paramsMd5)
  10476. ->orderBy('id', 'desc')
  10477. ->first();
  10478. if ($existing) {
  10479. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  10480. 'anime_id' => $anime_id,
  10481. 'task_center_id' => $existing->id,
  10482. 'params_md5' => $paramsMd5,
  10483. ]);
  10484. return (int)$existing->id;
  10485. }
  10486. $now = date('Y-m-d H:i:s');
  10487. DB::table('mp_task_center')->insertOrIgnore([
  10488. 'uid' => (int)$uid,
  10489. 'cpid' => (int)$cpid,
  10490. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  10491. 'title' => '批量生成分集',
  10492. 'ref_task_id' => 0,
  10493. 'status' => MpTaskCenter::STATUS_PROCESSING,
  10494. 'result' => null,
  10495. 'error_message' => null,
  10496. 'prompt' => null,
  10497. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  10498. 'params_md5' => $paramsMd5,
  10499. 'created_at' => $now,
  10500. 'updated_at' => $now,
  10501. ]);
  10502. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  10503. $taskId = (int)DB::table('mp_task_center')
  10504. ->where('uid', (int)$uid)
  10505. ->where('cpid', (int)$cpid)
  10506. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10507. ->where('params_md5', $paramsMd5)
  10508. ->orderBy('id', 'desc')
  10509. ->value('id');
  10510. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  10511. 'anime_id' => $anime_id,
  10512. 'task_center_id' => $taskId,
  10513. 'params_md5' => $paramsMd5,
  10514. ]);
  10515. return $taskId;
  10516. }
  10517. /**
  10518. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  10519. *
  10520. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  10521. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  10522. * 统一汇总更新,避免在每个更新点重复处理。
  10523. *
  10524. * @param int|string $animeId
  10525. * @return int 更新的任务中心记录数
  10526. */
  10527. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  10528. $animeId = (int)$animeId;
  10529. $updated = 0;
  10530. // 该 anime 是否还有未结束的详情任务
  10531. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  10532. ->where('anime_id', $animeId)
  10533. ->whereIn('status', ['pending', 'processing'])
  10534. ->exists();
  10535. // 扫描该 anime 相关的未完成任务中心记录
  10536. $tasks = DB::table('mp_task_center')
  10537. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10538. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10539. ->orderBy('id', 'desc')
  10540. ->limit(500)
  10541. ->get();
  10542. if ($hasUnfinished && !$tasks) {
  10543. return 0;
  10544. }
  10545. foreach ($tasks as $task) {
  10546. try {
  10547. $taskParams = json_decode((string)$task->params, true);
  10548. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  10549. continue;
  10550. }
  10551. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  10552. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  10553. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  10554. continue;
  10555. }
  10556. $details = DB::table('mp_batch_episode_generation_details')
  10557. ->where('anime_id', $animeId)
  10558. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  10559. ->get();
  10560. // 该批次范围内存在缺失记录,等待下一次检查
  10561. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  10562. continue;
  10563. }
  10564. $completedEpisodes = [];
  10565. $failedEpisodes = [];
  10566. $allFinished = true;
  10567. foreach ($details as $detail) {
  10568. if ($detail->status === 'completed') {
  10569. $completedEpisodes[] = $detail->episode_number;
  10570. } elseif ($detail->status === 'failed') {
  10571. $failedEpisodes[] = [
  10572. 'episode_number' => $detail->episode_number,
  10573. 'error_message' => $detail->error_message ?? '',
  10574. ];
  10575. } else {
  10576. // pending/processing(防御处理,正常不会走到)
  10577. $allFinished = false;
  10578. break;
  10579. }
  10580. }
  10581. if (!$allFinished) {
  10582. continue;
  10583. }
  10584. $result = json_encode([
  10585. 'anime_id' => $animeId,
  10586. 'start_episode' => $startEpisode,
  10587. 'end_episode' => $endEpisode,
  10588. 'total_episodes' => count($details),
  10589. 'completed_count' => count($completedEpisodes),
  10590. 'failed_count' => count($failedEpisodes),
  10591. 'completed_episodes' => $completedEpisodes,
  10592. 'failed_episodes' => $failedEpisodes,
  10593. ], JSON_UNESCAPED_UNICODE);
  10594. DB::table('mp_task_center')
  10595. ->where('id', $task->id)
  10596. ->update([
  10597. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  10598. 'result' => $result,
  10599. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  10600. 'updated_at' => date('Y-m-d H:i:s'),
  10601. ]);
  10602. $updated++;
  10603. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  10604. 'task_center_id' => $task->id,
  10605. 'anime_id' => $animeId,
  10606. 'start_episode' => $startEpisode,
  10607. 'end_episode' => $endEpisode,
  10608. ]);
  10609. } catch (\Exception $e) {
  10610. dLog('command')->error('更新批量生成分集任务中心异常', [
  10611. 'task_center_id' => $task->id,
  10612. 'anime_id' => $animeId,
  10613. 'error' => $e->getMessage(),
  10614. ]);
  10615. }
  10616. }
  10617. return $updated;
  10618. }
  10619. /**
  10620. * 获取批量生成任务状态
  10621. *
  10622. * @param array $data 请求数据
  10623. * @return array 任务状态信息
  10624. */
  10625. public function getBatchGenerationTaskStatus($data) {
  10626. $anime_id = getProp($data, 'anime_id');
  10627. if (!$anime_id) {
  10628. Utils::throwError('20003:anime_id参数缺失');
  10629. }
  10630. // 获取该anime的所有任务
  10631. $tasks = DB::table('mp_batch_episode_generation_details')
  10632. ->where('anime_id', $anime_id)
  10633. ->orderBy('episode_number')
  10634. ->get()
  10635. ->map(function($item) {
  10636. return [
  10637. 'id' => $item->id,
  10638. 'episode_number' => $item->episode_number,
  10639. 'status' => $item->status,
  10640. 'error_message' => $item->error_message,
  10641. 'retry_count' => $item->retry_count,
  10642. 'created_at' => $item->created_at,
  10643. 'updated_at' => $item->updated_at,
  10644. 'completed_at' => $item->completed_at
  10645. ];
  10646. })
  10647. ->toArray();
  10648. if (empty($tasks)) {
  10649. Utils::throwError('20003:该剧集没有批量生成任务');
  10650. }
  10651. // 统计各状态数量
  10652. $totalCount = count($tasks);
  10653. $pendingCount = 0;
  10654. $processingCount = 0;
  10655. $completedCount = 0;
  10656. $failedCount = 0;
  10657. $failed_episodes = [];
  10658. foreach ($tasks as $task) {
  10659. switch ($task['status']) {
  10660. case 'pending':
  10661. $pendingCount++;
  10662. break;
  10663. case 'processing':
  10664. $processingCount++;
  10665. break;
  10666. case 'completed':
  10667. $completedCount++;
  10668. break;
  10669. case 'failed':
  10670. $failedCount++;
  10671. // 组装失败分集对象(新对象):分集序号、错误原因
  10672. $failed_episodes[] = [
  10673. 'episode_number' => $task['episode_number'],
  10674. 'error_message' => $task['error_message'] ?? ''
  10675. ];
  10676. break;
  10677. }
  10678. }
  10679. // 计算进度百分比
  10680. $progress = 0;
  10681. if ($totalCount > 0) {
  10682. $progress = round(($completedCount / $totalCount) * 100, 2);
  10683. }
  10684. // 判断整体状态
  10685. $overallStatus = 'processing';
  10686. if ($completedCount === $totalCount) {
  10687. $overallStatus = 'completed';
  10688. } elseif ($pendingCount === $totalCount) {
  10689. $overallStatus = 'pending';
  10690. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  10691. $overallStatus = 'failed';
  10692. }
  10693. return [
  10694. 'anime_id' => $anime_id,
  10695. 'total_episodes' => $totalCount,
  10696. 'pending_count' => $pendingCount,
  10697. 'processing_count' => $processingCount,
  10698. 'completed_count' => $completedCount,
  10699. 'failed_count' => $failedCount,
  10700. 'progress' => $progress,
  10701. 'overall_status' => $overallStatus,
  10702. 'failed_episodes' => $failed_episodes,
  10703. 'tasks' => $tasks
  10704. ];
  10705. }
  10706. /**
  10707. * 将生成内容中不在强制列表中的资源合并进强制列表
  10708. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  10709. *
  10710. * @param array $generated 生成内容中的资源列表
  10711. * @param array $forced 强制资源列表(key为资源名称)
  10712. * @param string $type 资源类型:role、scene、prop
  10713. * @return array
  10714. */
  10715. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  10716. {
  10717. foreach ($generated as $item) {
  10718. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  10719. if ($name === null || $name === '') {
  10720. continue;
  10721. }
  10722. if ($name === '旁白') {
  10723. continue;
  10724. }
  10725. if (!isset($forced[$name])) {
  10726. $forced[$name] = $item;
  10727. }
  10728. }
  10729. return $forced;
  10730. }
  10731. /**
  10732. * 智能匹配并替换主体和场景名称
  10733. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10734. *
  10735. * @param array $episode_arr 解析后的剧集数据
  10736. * @param array $extra_roles 强制主体设定(key为主体名称)
  10737. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10738. * @return array 替换后的剧集数据
  10739. */
  10740. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10741. $replaced_count = 0;
  10742. // 1. 处理主体列表
  10743. if (!empty($episode_arr['roles'])) {
  10744. foreach ($episode_arr['roles'] as &$role) {
  10745. $generated_role_name = $role['role'] ?? '';
  10746. // 跳过旁白
  10747. if ($generated_role_name === '旁白') {
  10748. continue;
  10749. }
  10750. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10751. if (!isset($extra_roles[$generated_role_name])) {
  10752. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10753. if ($matched_role) {
  10754. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10755. $role['role'] = $matched_role;
  10756. $replaced_count++;
  10757. }
  10758. }
  10759. }
  10760. }
  10761. // 2. 处理场景列表
  10762. if (!empty($episode_arr['scenes'])) {
  10763. foreach ($episode_arr['scenes'] as &$scene) {
  10764. $generated_scene_name = $scene['scene'] ?? '';
  10765. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10766. if (!isset($extra_scenes[$generated_scene_name])) {
  10767. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10768. if ($matched_scene) {
  10769. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10770. $scene['scene'] = $matched_scene;
  10771. $replaced_count++;
  10772. }
  10773. }
  10774. }
  10775. }
  10776. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10777. if (!empty($episode_arr['acts'])) {
  10778. foreach ($episode_arr['acts'] as &$act) {
  10779. if (!empty($act['segments'])) {
  10780. foreach ($act['segments'] as &$segment) {
  10781. if (!empty($segment['segment_content'])) {
  10782. $original_content = $segment['segment_content'];
  10783. $replaced_content = $original_content;
  10784. // 替换场景名 - 在文本中查找并替换
  10785. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10786. // 尝试找到可能的短名称
  10787. $potential_short_names = [];
  10788. // 提取场景名的主要部分(冒号之前)
  10789. if (mb_strpos($full_scene_name, ':') !== false) {
  10790. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10791. $potential_short_names[] = $short_name;
  10792. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10793. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10794. $potential_short_names[] = $short_name;
  10795. }
  10796. // 替换场景字段中的短名称
  10797. foreach ($potential_short_names as $short_name) {
  10798. if ($short_name !== $full_scene_name) {
  10799. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10800. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10801. if ($new_content !== $replaced_content) {
  10802. $replaced_content = $new_content;
  10803. $replaced_count++;
  10804. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10805. }
  10806. }
  10807. }
  10808. }
  10809. // 替换配音角色名(跳过旁白)
  10810. foreach (array_keys($extra_roles) as $full_role_name) {
  10811. if ($full_role_name === '旁白') {
  10812. continue;
  10813. }
  10814. // 尝试找到可能的短名称
  10815. $potential_short_names = [];
  10816. // 提取角色名的主要部分(短横线之前)
  10817. if (mb_strpos($full_role_name, '-') !== false) {
  10818. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10819. $potential_short_names[] = $short_name;
  10820. }
  10821. // 替换配音台词中的短名称
  10822. foreach ($potential_short_names as $short_name) {
  10823. if ($short_name !== $full_role_name) {
  10824. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10825. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10826. if ($new_content !== $replaced_content) {
  10827. $replaced_content = $new_content;
  10828. $replaced_count++;
  10829. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10830. }
  10831. }
  10832. }
  10833. }
  10834. // 如果有替换,更新segment_content
  10835. if ($replaced_content !== $original_content) {
  10836. $segment['segment_content'] = $replaced_content;
  10837. }
  10838. }
  10839. }
  10840. }
  10841. }
  10842. }
  10843. if ($replaced_count > 0) {
  10844. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10845. 'replaced_count' => $replaced_count
  10846. ]);
  10847. }
  10848. return $episode_arr;
  10849. }
  10850. /**
  10851. * 查找匹配的名称
  10852. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10853. *
  10854. * @param string $generated_name 生成的名称
  10855. * @param array $expected_names 预期的名称列表
  10856. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10857. */
  10858. private function findMatchingName($generated_name, $expected_names) {
  10859. if (empty($generated_name)) {
  10860. return null;
  10861. }
  10862. // 尝试精确匹配
  10863. if (in_array($generated_name, $expected_names)) {
  10864. return $generated_name;
  10865. }
  10866. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10867. foreach ($expected_names as $expected_name) {
  10868. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10869. if (mb_strpos($expected_name, $generated_name) === 0) {
  10870. return $expected_name;
  10871. }
  10872. }
  10873. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10874. // 这样可以处理一些变体,但优先级较低
  10875. foreach ($expected_names as $expected_name) {
  10876. if (mb_strpos($expected_name, $generated_name) !== false) {
  10877. return $expected_name;
  10878. }
  10879. }
  10880. return null;
  10881. }
  10882. /**
  10883. * 重新生成分段剧本
  10884. * @param array $data 包含以下字段:
  10885. * - prompt: string|null 用户修改要求(可选)
  10886. * - template_id: int|null 提示词模板ID(可选)
  10887. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10888. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10889. * @return array 返回生成结果
  10890. */
  10891. public function regenerateSegmentScript($data) {
  10892. $uid = Site::getUid();
  10893. $prompt = trim((string)getProp($data, 'prompt', ''));
  10894. $template_id = getProp($data, 'template_id', 0);
  10895. $act_id = getProp($data, 'act_id', 0);
  10896. $episode_id = getProp($data, 'episode_id', 0);
  10897. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  10898. // 验证:prompt和template_id至少提供一个
  10899. if (empty($prompt) && empty($template_id)) {
  10900. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10901. }
  10902. // 验证:act_id和episode_id二选一
  10903. if (empty($act_id) && empty($episode_id)) {
  10904. Utils::throwError('20003:请提供片段ID或剧集ID');
  10905. }
  10906. if (!empty($act_id) && !empty($episode_id)) {
  10907. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10908. }
  10909. // 积分余额预检(仅剧集ID模式收费)
  10910. if (!empty($episode_id)) {
  10911. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  10912. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  10913. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10914. }
  10915. // 如果提供了template_id,获取模板提示词
  10916. $template_prompt = '';
  10917. if ($template_id > 0) {
  10918. $template = DB::table('mp_prompt_templates')
  10919. ->where('id', $template_id)
  10920. ->where('is_deleted', 0)
  10921. ->first();
  10922. if (!$template) {
  10923. Utils::throwError('20003:提示词模板不存在或已删除');
  10924. }
  10925. $template_prompt = $template->template_prompt ?? '';
  10926. }
  10927. // 合并用户提示词和模板提示词
  10928. $final_prompt = '';
  10929. if (!empty($template_prompt)) {
  10930. $final_prompt = $template_prompt;
  10931. if (!empty($prompt)) {
  10932. $final_prompt .= "\n\n补充要求:" . $prompt;
  10933. }
  10934. } else {
  10935. $final_prompt = $prompt;
  10936. }
  10937. // 获取需要重新生成的内容参考
  10938. $reference_content = '';
  10939. $target_episode_id = 0;
  10940. $target_anime_id = 0;
  10941. $target_episode_number = 0;
  10942. if ($act_id > 0) {
  10943. // 单个片段模式:获取该片段的内容
  10944. $segment = DB::table('mp_episode_segments')
  10945. ->where('id', $act_id)
  10946. ->first();
  10947. if (!$segment) {
  10948. Utils::throwError('20003:片段不存在');
  10949. }
  10950. $target_episode_id = $segment->episode_id;
  10951. $target_anime_id = $segment->anime_id;
  10952. $target_episode_number = $segment->episode_number;
  10953. $reference_content = $segment->act_content ?? '';
  10954. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10955. } else {
  10956. // 整个剧集模式:获取所有片段的内容
  10957. $segments = DB::table('mp_episode_segments')
  10958. ->where('episode_id', $episode_id)
  10959. ->orderBy('act_number')
  10960. ->get();
  10961. if ($segments->isEmpty()) {
  10962. Utils::throwError('20003:该剧集没有片段数据');
  10963. }
  10964. $target_episode_id = $episode_id;
  10965. $target_anime_id = $segments[0]->anime_id;
  10966. $target_episode_number = $segments[0]->episode_number;
  10967. // 拼接所有片段内容,保留格式用于AI理解
  10968. $act_contents = [];
  10969. foreach ($segments as $seg) {
  10970. $act_number = $seg->act_number;
  10971. $act_content = $seg->act_content ?? '';
  10972. if (!empty($act_content)) {
  10973. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  10974. }
  10975. }
  10976. $reference_content = implode("\n\n", $act_contents);
  10977. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  10978. if ($episode_content) {
  10979. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  10980. }else {
  10981. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10982. }
  10983. }
  10984. if (empty($reference_content)) {
  10985. Utils::throwError('20003:没有可参考的片段内容');
  10986. }
  10987. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  10988. $episode = DB::table('mp_anime_episodes')
  10989. ->where('id', $target_episode_id)
  10990. ->first();
  10991. if (!$episode) {
  10992. Utils::throwError('20003:剧集不存在');
  10993. }
  10994. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  10995. $anime_script_id = getProp($anime, 'script_id');
  10996. $intro = $episode->intro ?? '';
  10997. $art_style = $episode->art_style ?? '';
  10998. $roles = json_decode($episode->roles ?? '[]', true);
  10999. $scenes = json_decode($episode->scenes ?? '[]', true);
  11000. $props = json_decode($episode->props ?? '[]', true);
  11001. // 构建提示词中的主体列表和场景列表参考
  11002. $roles_ref = '';
  11003. if (!empty($roles) && is_array($roles)) {
  11004. $roles_list = [];
  11005. foreach ($roles as $role) {
  11006. $role_name = getProp($role, 'role', '');
  11007. $role_desc = getProp($role, 'description', '');
  11008. $pic_prompt = getProp($role, 'pic_prompt', '');
  11009. $voice_prompt = getProp($role, 'voice_prompt', '');
  11010. if (!empty($role_name)) {
  11011. $role_line = $role_name;
  11012. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  11013. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  11014. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  11015. $roles_list[] = $role_line;
  11016. }
  11017. }
  11018. if (!empty($roles_list)) {
  11019. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  11020. }
  11021. }
  11022. $scenes_ref = '';
  11023. if (!empty($scenes) && is_array($scenes)) {
  11024. $scenes_list = [];
  11025. foreach ($scenes as $scene) {
  11026. $scene_name = getProp($scene, 'scene', '');
  11027. $scene_desc = getProp($scene, 'description', '');
  11028. $pic_prompt = getProp($scene, 'pic_prompt', '');
  11029. if (!empty($scene_name)) {
  11030. $scene_line = $scene_name;
  11031. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  11032. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  11033. $scenes_list[] = $scene_line;
  11034. }
  11035. }
  11036. if (!empty($scenes_list)) {
  11037. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  11038. }
  11039. }
  11040. $props_ref = '';
  11041. if (!empty($props) && is_array($props)) {
  11042. $props_list = [];
  11043. foreach ($props as $prop) {
  11044. $prop_name = getProp($prop, 'prop', '');
  11045. $prop_desc = getProp($prop, 'description', '');
  11046. $pic_prompt = getProp($prop, 'pic_prompt', '');
  11047. if (!empty($prop_name)) {
  11048. $prop_line = $prop_name;
  11049. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  11050. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  11051. $props_list[] = $prop_line;
  11052. }
  11053. }
  11054. if (!empty($props_list)) {
  11055. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  11056. }
  11057. }
  11058. // 构建美术风格参考
  11059. $art_style_ref = '';
  11060. if (!empty($art_style)) {
  11061. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  11062. }
  11063. // 构建内容简介参考
  11064. $intro_ref = '';
  11065. if (!empty($intro)) {
  11066. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  11067. }
  11068. // 构建完整的AI提示词
  11069. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  11070. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  11071. $user_prompt .= $intro_ref;
  11072. $user_prompt .= $art_style_ref;
  11073. $user_prompt .= $reference_content;
  11074. // $user_prompt .= $roles_ref;
  11075. // $user_prompt .= $scenes_ref;
  11076. $system_prompt = "\n\n【强制要求】\n";
  11077. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  11078. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  11079. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  11080. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  11081. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  11082. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  11083. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  11084. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  11085. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  11086. ###分段剧本
  11087. 片段数量:8
  11088. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  11089. ##片段1
  11090. 时长:12s
  11091. 分镜1
  11092. 出场角色:刀疤脸
  11093. 场景:边境小镇街道
  11094. 出场道具:酒杯-高脚杯
  11095. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  11096. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  11097. 配音台词:
  11098. 背景音效:
  11099. 分镜2
  11100. 出场角色:刀疤脸
  11101. 场景:悦来酒馆
  11102. 出场道具:酒杯-高脚杯
  11103. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  11104. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  11105. 配音台词:
  11106. 背景音效:
  11107. 分镜3
  11108. 出场角色:刀疤脸
  11109. 场景:悦来酒馆
  11110. 出场道具:酒杯-高脚杯
  11111. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  11112. 运镜:从中景推向令牌特写。
  11113. 配音台词:
  11114. 背景音效:
  11115. 分镜4
  11116. 出场角色:刀疤脸
  11117. 场景:悦来酒馆
  11118. 出场道具:酒杯-高脚杯
  11119. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  11120. 运镜:极速推向酒水溅起的瞬间。
  11121. 配音台词:
  11122. 背景音效:
  11123. 分镜5
  11124. 出场角色:刀疤脸
  11125. 场景:悦来酒馆
  11126. 出场道具:酒杯-高脚杯
  11127. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  11128. 运镜:固定机位,利用倾斜构图制造压迫感。
  11129. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  11130. 背景音效:";
  11131. // 获取模型配置
  11132. $model = getProp($data, 'model');
  11133. if (!$model) {
  11134. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  11135. }
  11136. // 验证模型是否在可用模型表中
  11137. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11138. $model = 'deepseek-v4-pro';
  11139. }
  11140. // 模型兼容性处理
  11141. $thinkingMode = 'disabled';
  11142. $reasoningEffort = 'high';
  11143. if ($model === 'deepseek-chat') {
  11144. $model = 'deepseek-v4-flash';
  11145. $thinkingMode = 'disabled';
  11146. } elseif ($model === 'deepseek-reasoner') {
  11147. $model = 'deepseek-v4-flash';
  11148. $thinkingMode = 'enabled';
  11149. }
  11150. // 构建消息
  11151. $messages = [
  11152. [
  11153. 'role' => 'system',
  11154. 'content' => $system_prompt
  11155. ],
  11156. [
  11157. 'role' => 'user',
  11158. 'content' => $user_prompt
  11159. ]
  11160. ];
  11161. // dd($messages);
  11162. // 构建请求参数
  11163. $post_data = [
  11164. 'model' => $model,
  11165. 'messages' => $messages,
  11166. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11167. 'frequency_penalty' => 0,
  11168. 'presence_penalty' => 0,
  11169. 'response_format' => ['type' => 'text'],
  11170. 'thinking' => ['type' => $thinkingMode],
  11171. 'stream' => false // 非流式输出
  11172. ];
  11173. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11174. // 调用AI生成新的分段剧本
  11175. try {
  11176. $fullContent = '';
  11177. $usage = [];
  11178. // 根据模型类型选择调用方法
  11179. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11180. // DeepSeek 官方模型使用 DeepSeek API
  11181. $chatResult = $this->chatOnly($post_data);
  11182. } else if (in_array($model, $this->gpt_text_models)) {
  11183. // GPT 模型使用 TokenRouter API
  11184. $chatResult = $this->gpt54ChatOnly($post_data);
  11185. } else {
  11186. // 其他模型使用火山引擎API
  11187. $chatResult = $this->volcEngineChatCompletion($post_data);
  11188. }
  11189. if (is_array($chatResult)) {
  11190. $fullContent = $chatResult['fullContent'] ?? '';
  11191. $usage = $chatResult['usage'] ?? [];
  11192. }
  11193. $generated_content = $fullContent;
  11194. if (empty($generated_content)) {
  11195. Utils::throwError('20003:AI生成内容为空,请重试');
  11196. }
  11197. // 解析生成的内容 - 按片段分割
  11198. $parsed_segments = [];
  11199. // 先在开头添加换行符,确保第1片段也能被正确分割
  11200. $normalizedText = "\n" . $generated_content;
  11201. $parts = preg_split('/\n\s*##/', $normalizedText);
  11202. foreach ($parts as $part) {
  11203. $part = trim($part);
  11204. if (empty($part)) continue;
  11205. // 匹配"片段X"格式
  11206. if (!preg_match('/^片段\d+/', $part)) {
  11207. continue;
  11208. }
  11209. // 分离标题和内容
  11210. $lines = explode("\n", $part, 2);
  11211. $actTitle = trim($lines[0]);
  11212. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  11213. // 解析标题,提取序号
  11214. $actNumber = 0;
  11215. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  11216. $actNumber = intval($segmentTitleMatch[1]);
  11217. } else {
  11218. $actNumber = count($parsed_segments) + 1;
  11219. }
  11220. // 提取时长(仅保留数字)
  11221. $actDuration = 0;
  11222. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  11223. $actDurationStr = trim($actDurationMatch[1]);
  11224. // 提取数字部分(支持整数和小数)
  11225. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  11226. $actDuration = (float)$numMatch[1];
  11227. }
  11228. }
  11229. // 清理act_content:去除时长、旁白音色等非分镜内容行
  11230. // 只保留分镜内容,并确保分镜标记使用【】格式
  11231. $cleaned_content = '';
  11232. $content_lines = explode("\n", $actContent);
  11233. $is_capturing = false; // 标记是否开始捕获分镜内容
  11234. $count = 0;
  11235. foreach ($content_lines as $line) {
  11236. $trimmed_line = trim($line);
  11237. // 跳过时长和旁白音色行
  11238. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  11239. continue;
  11240. }
  11241. // 检测是否是分镜开始
  11242. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  11243. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  11244. $count++;
  11245. $is_capturing = true;
  11246. // 如果没有【】,则添加
  11247. if (!preg_match('/^【/u', $trimmed_line)) {
  11248. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  11249. }
  11250. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  11251. }
  11252. // 如果已经开始捕获,则添加该行
  11253. if ($is_capturing && !empty($trimmed_line)) {
  11254. $cleaned_content .= $trimmed_line."\n";
  11255. }
  11256. }
  11257. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  11258. $parsed_segments[] = [
  11259. 'act_number' => $actNumber,
  11260. 'act_title' => $actTitle,
  11261. 'act_duration' => $actDuration,
  11262. 'act_content' => $cleaned_content,
  11263. ];
  11264. }
  11265. if (empty($parsed_segments)) {
  11266. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  11267. }
  11268. // 收集所有资产名称(角色、场景、道具)
  11269. $product_names = [];
  11270. // 收集角色名称
  11271. if (!empty($roles) && is_array($roles)) {
  11272. foreach ($roles as $role) {
  11273. $role_name = getProp($role, 'role', '');
  11274. if (!empty($role_name)) {
  11275. $product_names[] = $role_name;
  11276. }
  11277. }
  11278. }
  11279. // 收集场景名称
  11280. if (!empty($scenes) && is_array($scenes)) {
  11281. foreach ($scenes as $scene) {
  11282. $scene_name = getProp($scene, 'scene', '');
  11283. if (!empty($scene_name)) {
  11284. $product_names[] = $scene_name;
  11285. }
  11286. }
  11287. }
  11288. // 收集道具名称
  11289. if (!empty($props) && is_array($props)) {
  11290. foreach ($props as $prop) {
  11291. $prop_name = getProp($prop, 'prop', '');
  11292. if (!empty($prop_name)) {
  11293. $product_names[] = $prop_name;
  11294. }
  11295. }
  11296. }
  11297. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  11298. $product_names = array_unique($product_names);
  11299. usort($product_names, function($a, $b) {
  11300. return mb_strlen($b) - mb_strlen($a);
  11301. });
  11302. // 处理每个片段的 act_show_content
  11303. foreach ($parsed_segments as &$segment) {
  11304. $act_content = getProp($segment, 'act_content', '');
  11305. if (empty($act_content)) {
  11306. $segment['act_show_content'] = '';
  11307. continue;
  11308. }
  11309. $processed_content = $act_content;
  11310. // 统一替换所有资产名称为 {资产名} 格式
  11311. // 使用占位符避免嵌套替换问题
  11312. $placeholder_map = [];
  11313. $placeholder_index = 0;
  11314. foreach ($product_names as $product_name) {
  11315. // 转义特殊字符
  11316. $escaped_product = preg_quote($product_name, '/');
  11317. // 检查是否匹配且未被 {} 包裹
  11318. $processed_content = preg_replace_callback(
  11319. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  11320. function($matches) use (&$placeholder_map, &$placeholder_index) {
  11321. // 使用唯一占位符
  11322. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  11323. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  11324. $placeholder_index++;
  11325. return $placeholder;
  11326. },
  11327. $processed_content
  11328. );
  11329. }
  11330. // 将所有占位符替换回实际内容
  11331. foreach ($placeholder_map as $placeholder => $replacement) {
  11332. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  11333. }
  11334. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  11335. $shot_counter = 0;
  11336. $processed_content = preg_replace_callback(
  11337. '/【(?:镜头|分镜)(\d+)】/u',
  11338. function($matches) use (&$shot_counter) {
  11339. $shot_counter++;
  11340. return '【镜头' . $shot_counter . '】';
  11341. },
  11342. $processed_content
  11343. );
  11344. $segment['act_show_content'] = $processed_content;
  11345. }
  11346. unset($segment); // 解除引用
  11347. // 保存到数据库
  11348. $now = date('Y-m-d H:i:s');
  11349. $saved_acts = []; // 用于记录保存后的片段信息
  11350. if ($act_id > 0) {
  11351. // 单个片段模式:更新单条记录
  11352. if (count($parsed_segments) > 0) {
  11353. $new_segment = $parsed_segments[0];
  11354. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  11355. if ($check_mode === 1) {
  11356. return [
  11357. 'check_mode' => 1,
  11358. 'act_id' => (int)$act_id,
  11359. 'act_title' => getProp($new_segment, 'act_title', ''),
  11360. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11361. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  11362. ];
  11363. }
  11364. $update_data = [
  11365. 'act_content' => getProp($new_segment, 'act_content', ''),
  11366. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  11367. 'act_title' => getProp($new_segment, 'act_title', ''),
  11368. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11369. 'updated_at' => $now,
  11370. ];
  11371. DB::table('mp_episode_segments')
  11372. ->where('id', $act_id)
  11373. ->update($update_data);
  11374. // 获取更新后的记录
  11375. $updated_act = DB::table('mp_episode_segments')
  11376. ->where('id', $act_id)
  11377. ->first();
  11378. if ($updated_act) {
  11379. $saved_acts[] = [
  11380. 'act_id' => $updated_act->id,
  11381. 'act_number' => $updated_act->act_number,
  11382. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  11383. 'act_content' => $updated_act->act_content,
  11384. 'act_show_content' => $updated_act->act_show_content,
  11385. 'video_url' => $updated_act->video_url ?? '',
  11386. 'video_duration' => $updated_act->video_duration ?? 0,
  11387. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  11388. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  11389. ];
  11390. }
  11391. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  11392. }
  11393. } else {
  11394. // 整个剧集模式:删除原有记录并批量保存新记录
  11395. DB::beginTransaction();
  11396. try {
  11397. // 删除原有的所有片段记录
  11398. DB::table('mp_episode_segments')
  11399. ->where('episode_id', $target_episode_id)
  11400. ->delete();
  11401. // 批量插入新的片段记录
  11402. $segments_to_insert = [];
  11403. foreach ($parsed_segments as $index => $segment) {
  11404. $act_number = $index + 1;
  11405. $segments_to_insert[] = [
  11406. 'anime_id' => $target_anime_id,
  11407. 'episode_id' => $target_episode_id,
  11408. 'episode_number' => $target_episode_number,
  11409. 'act_number' => $act_number,
  11410. 'act_title' => getProp($segment, 'act_title', ''),
  11411. 'act_duration' => getProp($segment, 'act_duration', 0),
  11412. 'act_content' => getProp($segment, 'act_content', ''),
  11413. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  11414. 'created_at' => $now,
  11415. 'updated_at' => $now,
  11416. ];
  11417. }
  11418. if (!empty($segments_to_insert)) {
  11419. DB::table('mp_episode_segments')->insert($segments_to_insert);
  11420. }
  11421. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11422. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11423. 'anime_id' => $target_anime_id,
  11424. 'episode_id' => $target_episode_id,
  11425. 'model' => $model,
  11426. 'source' => 'regenerateSegmentScript',
  11427. ]);
  11428. DB::commit();
  11429. // 查询保存后的所有片段记录
  11430. $saved_segments = DB::table('mp_episode_segments')
  11431. ->where('episode_id', $target_episode_id)
  11432. ->orderBy('act_number')
  11433. ->get();
  11434. foreach ($saved_segments as $saved_segment) {
  11435. $saved_acts[] = [
  11436. 'act_id' => $saved_segment->id,
  11437. 'act_number' => $saved_segment->act_number,
  11438. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  11439. 'act_content' => $saved_segment->act_content,
  11440. 'act_show_content' => $saved_segment->act_show_content,
  11441. 'video_url' => $saved_segment->video_url ?? '',
  11442. 'video_duration' => $saved_segment->video_duration ?? 0,
  11443. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  11444. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  11445. ];
  11446. }
  11447. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  11448. 'episode_id' => $target_episode_id,
  11449. 'segments_count' => count($segments_to_insert)
  11450. ]);
  11451. } catch (\Exception $e) {
  11452. DB::rollBack();
  11453. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  11454. Utils::throwError('20003:保存失败,请重试');
  11455. }
  11456. }
  11457. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  11458. return [
  11459. 'anime_id' => $target_anime_id,
  11460. 'episode_id' => $target_episode_id,
  11461. 'title' => getProp($episode, 'title', ''),
  11462. 'episode_number' => $target_episode_number,
  11463. 'is_generated' => getProp($episode, 'is_generated', 0),
  11464. 'acts' => $saved_acts,
  11465. ];
  11466. } catch (\Exception $e) {
  11467. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  11468. throw $e;
  11469. }
  11470. }
  11471. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  11472. {
  11473. $episode_arr = [
  11474. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  11475. 'intro' => getProp($script_arr, 'intro'),
  11476. 'art_style' => getProp($script_arr, 'art_style'),
  11477. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  11478. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  11479. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  11480. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  11481. ];
  11482. if (empty($episode_arr['acts'])) {
  11483. $fallback_episode_arr = handleEpisodeContent($fullContent);
  11484. if (!empty($fallback_episode_arr['acts'])) {
  11485. $episode_arr = array_merge($fallback_episode_arr, [
  11486. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  11487. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  11488. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  11489. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  11490. ]);
  11491. }
  11492. }
  11493. // if (!getProp($episode_arr, 'episode_title')) {
  11494. // $episode_title = '';
  11495. // $episodes = getProp($script_arr, 'episodes', []);
  11496. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  11497. // $episode_title = '第1集:' . $episodes[0]['title'];
  11498. // }
  11499. // if (!$episode_title) {
  11500. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  11501. // }
  11502. // $episode_arr['episode_title'] = $episode_title;
  11503. // }
  11504. return $episode_arr;
  11505. }
  11506. private function saveEpisodeVersionData(
  11507. int $anime_id,
  11508. int $episode_number,
  11509. array $episode_arr,
  11510. array $existing_roles,
  11511. array $existing_scenes,
  11512. array $existing_props,
  11513. $current_episode,
  11514. $base_episode,
  11515. bool $is_regenerate_version,
  11516. string $content,
  11517. string $now,
  11518. array $ref_products = []
  11519. ): array {
  11520. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  11521. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  11522. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  11523. // 过滤掉关键字段为空的条目
  11524. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  11525. return !empty($item['role'] ?? null);
  11526. }));
  11527. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  11528. return !empty($item['scene'] ?? null);
  11529. }));
  11530. $merged_props = array_values(array_filter($generated_props, function ($item) {
  11531. return !empty($item['prop'] ?? null);
  11532. }));
  11533. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  11534. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  11535. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  11536. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11537. $ace_mode = getProp($anime, 'ace_mode');
  11538. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  11539. $global_roles = json_decode(getProp($anime, 'roles'), true);
  11540. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  11541. $global_roles = is_array($global_roles) ? $global_roles : [];
  11542. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  11543. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  11544. $art_style_type = getProp($anime, 'art_style_type');
  11545. // 检查并创建 roles 的图片生成任务
  11546. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  11547. // 检查并创建 scenes 的图片生成任务
  11548. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  11549. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  11550. if ($arr && is_array($arr)) {
  11551. $merged_roles = $arr['roles'];
  11552. $merged_scenes = $arr['scenes'];
  11553. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  11554. }
  11555. // 确保数据是数组类型
  11556. if (!is_array($merged_roles)) {
  11557. dLog('deepseek')->error('merged_roles不是数组类型', [
  11558. 'type' => gettype($merged_roles),
  11559. 'value' => $merged_roles
  11560. ]);
  11561. $merged_roles = [];
  11562. }
  11563. if (!is_array($merged_scenes)) {
  11564. dLog('deepseek')->error('merged_scenes不是数组类型', [
  11565. 'type' => gettype($merged_scenes),
  11566. 'value' => $merged_scenes
  11567. ]);
  11568. $merged_scenes = [];
  11569. }
  11570. if (!is_array($merged_props)) {
  11571. dLog('deepseek')->error('merged_props不是数组类型', [
  11572. 'type' => gettype($merged_props),
  11573. 'value' => $merged_props
  11574. ]);
  11575. $merged_props = [];
  11576. }
  11577. // 同步新出现的主体和场景到全局
  11578. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  11579. $role_arr = [];
  11580. foreach ($merged_roles as $item) {
  11581. $role_arr[$item['role']] = $item;
  11582. }
  11583. $version_count = DB::table('mp_anime_episodes')
  11584. ->where('anime_id', $anime_id)
  11585. ->where('episode_number', $episode_number)
  11586. ->count('id');
  11587. $episode = [
  11588. 'anime_id' => $anime_id,
  11589. 'episode_number' => $episode_number,
  11590. 'title' => getProp($episode_arr, 'episode_title'),
  11591. 'content' => $content,
  11592. 'intro' => getProp($episode_arr, 'intro'),
  11593. 'art_style' => getProp($episode_arr, 'art_style'),
  11594. 'roles' => json_encode($merged_roles, 256),
  11595. 'scenes' => json_encode($merged_scenes, 256),
  11596. 'props' => json_encode($merged_props, 256),
  11597. 'generate_status' => '待执行',
  11598. 'generate_at' => $now,
  11599. 'is_default' => 1,
  11600. 'updated_at' => $now,
  11601. ];
  11602. $del_flag = false;
  11603. if ($is_regenerate_version) {
  11604. DB::table('mp_anime_episodes')
  11605. ->where('anime_id', $anime_id)
  11606. ->where('episode_number', $episode_number)
  11607. ->update(['is_default' => 0, 'updated_at' => $now]);
  11608. $episode['sequence'] = $version_count + 1;
  11609. $episode['created_at'] = $now;
  11610. $episode['cpid'] = Site::getCpid();
  11611. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11612. if (!$episode_id) {
  11613. Utils::throwError('20003:创建剧集版本失败');
  11614. }
  11615. } else {
  11616. $target_episode = $current_episode ?: $base_episode;
  11617. if ($target_episode) {
  11618. $episode_id = getProp($target_episode, 'id');
  11619. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  11620. DB::table('mp_anime_episodes')
  11621. ->where('anime_id', $anime_id)
  11622. ->where('episode_number', $episode_number)
  11623. ->where('id', '<>', $episode_id)
  11624. ->update(['is_default' => 0, 'updated_at' => $now]);
  11625. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  11626. if ($boolen === false) {
  11627. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11628. Utils::throwError('20003:分集内容保存失败');
  11629. }
  11630. $del_flag = true;
  11631. } else {
  11632. DB::table('mp_anime_episodes')
  11633. ->where('anime_id', $anime_id)
  11634. ->where('episode_number', $episode_number)
  11635. ->update(['is_default' => 0, 'updated_at' => $now]);
  11636. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  11637. $episode['created_at'] = $now;
  11638. $episode['cpid'] = Site::getCpid();
  11639. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11640. if (!$episode_id) {
  11641. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  11642. Utils::throwError('20003:分集内容保存失败');
  11643. }
  11644. }
  11645. }
  11646. $segments = [];
  11647. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11648. // 如果是第2集及以后,获取上一集的主体音色数据
  11649. $previous_roles_voice = [];
  11650. if ($episode_number >= 2) {
  11651. $previous_episode = DB::table('mp_anime_episodes')
  11652. ->where('anime_id', $anime_id)
  11653. ->where('episode_number', $episode_number - 1)
  11654. ->where('is_default', 1)
  11655. ->first();
  11656. if ($previous_episode) {
  11657. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  11658. if (is_array($previous_roles)) {
  11659. foreach ($previous_roles as $prev_role) {
  11660. $role_name = getProp($prev_role, 'role');
  11661. if ($role_name) {
  11662. $previous_roles_voice[$role_name] = [
  11663. 'voice_name' => getProp($prev_role, 'voice_name'),
  11664. 'voice_type' => getProp($prev_role, 'voice_type'),
  11665. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  11666. ];
  11667. $voice_prompt = getProp($prev_role, 'voice_prompt');
  11668. if ($voice_prompt) {
  11669. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  11670. }
  11671. }
  11672. }
  11673. }
  11674. }
  11675. }
  11676. // 将继承的音色数据同步到当前集的主体列表
  11677. if (!empty($previous_roles_voice)) {
  11678. foreach ($merged_roles as &$role) {
  11679. $role_name = getProp($role, 'role');
  11680. if ($role_name && isset($previous_roles_voice[$role_name])) {
  11681. // 强制继承上一集的音色数据
  11682. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  11683. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  11684. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  11685. // 如果上一集有 voice_prompt 则继承,否则跳过
  11686. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  11687. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  11688. }
  11689. }
  11690. }
  11691. unset($role); // 解除引用
  11692. // 更新 role_arr 以便后续使用
  11693. $role_arr = [];
  11694. foreach ($merged_roles as $item) {
  11695. $role_arr[$item['role']] = $item;
  11696. }
  11697. }
  11698. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  11699. $emotion_list = array_flip($emotion_list);
  11700. foreach ($acts as $act) {
  11701. $act_segments = getProp($act, 'segments', []);
  11702. if (!is_array($act_segments)) {
  11703. continue;
  11704. }
  11705. if ((int)$ace_mode === 1) {
  11706. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  11707. $merged_parts = [];
  11708. foreach ($act_segments as $seg) {
  11709. $seg_num = getProp($seg, 'segment_number');
  11710. $seg_content = getProp($seg, 'segment_content');
  11711. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  11712. }
  11713. $act_content = implode("\n", $merged_parts);
  11714. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11715. $segments[] = [
  11716. 'anime_id' => $anime_id,
  11717. 'episode_id' => $episode_id,
  11718. 'episode_number' => $episode_number,
  11719. 'act_number' => getProp($act, 'act_number'),
  11720. 'act_title' => getProp($act, 'act_title'),
  11721. 'act_duration' => getProp($act, 'act_duration'),
  11722. 'act_content' => $act_content,
  11723. 'created_at' => $now,
  11724. 'updated_at' => $now
  11725. ];
  11726. } else {
  11727. foreach ($act_segments as $segment) {
  11728. $voice_actor = getProp($segment, 'voice_actor');
  11729. // 优先从上一集继承音色数据
  11730. $timbre_info = [];
  11731. if (isset($previous_roles_voice[$voice_actor])) {
  11732. // 从上一集继承音色数据
  11733. $timbre_info = $previous_roles_voice[$voice_actor];
  11734. } elseif (isset($role_arr[$voice_actor])) {
  11735. // 使用当前集的主体音色数据
  11736. $timbre_info = $role_arr[$voice_actor];
  11737. }
  11738. $voice_type = getProp($timbre_info, 'voice_type');
  11739. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  11740. if ($timbre_emotion) {
  11741. $timbre_emotion = explode(',', $timbre_emotion);
  11742. } else {
  11743. $timbre_emotion = [];
  11744. }
  11745. $emotion = getProp($segment, 'emotion', '中性');
  11746. if (!in_array($emotion, $timbre_emotion)) {
  11747. $emotion = '中性';
  11748. }
  11749. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11750. $segments[] = [
  11751. 'anime_id' => $anime_id,
  11752. 'episode_id' => $episode_id,
  11753. 'episode_number' => $episode_number,
  11754. 'act_number' => getProp($act, 'act_number'),
  11755. 'act_title' => getProp($act, 'act_title'),
  11756. 'act_duration' => getProp($act, 'act_duration'),
  11757. 'segment_id' => getProp($segment, 'segment_id'),
  11758. 'segment_number' => getProp($segment, 'segment_number'),
  11759. 'segment_content' => getProp($segment, 'segment_content'),
  11760. 'description' => getProp($segment, 'description'),
  11761. 'composition' => getProp($segment, 'composition'),
  11762. 'camera_movement' => getProp($segment, 'camera_movement'),
  11763. 'voice_actor' => $voice_actor,
  11764. 'dialogue' => getProp($segment, 'dialogue'),
  11765. 'frame_type' => getProp($segment, 'frame_type'),
  11766. 'scene' => getProp($segment, 'scene'),
  11767. 'characters' => getProp($segment, 'characters'),
  11768. 'tail_frame' => getProp($segment, 'tail_frame'),
  11769. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11770. 'voice_type' => $voice_type,
  11771. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11772. 'emotion' => $emotion,
  11773. 'emotion_type' => $emotion_type,
  11774. 'gender' => getProp($segment, 'gender', '0'),
  11775. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11776. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11777. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11778. 'pitch' => getProp($segment, 'pitch', 0),
  11779. 'created_at' => $now,
  11780. 'updated_at' => $now
  11781. ];
  11782. }
  11783. }
  11784. }
  11785. if ($segments) {
  11786. if ($del_flag) {
  11787. DB::table('mp_episode_segments')
  11788. ->where('anime_id', $anime_id)
  11789. ->where('episode_id', $episode_id)
  11790. ->delete();
  11791. }
  11792. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11793. if (!$boolen) {
  11794. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11795. Utils::throwError('20003:分镜内容保存失败');
  11796. }
  11797. }
  11798. dLog('deepseek')->info('segments', $segments);
  11799. // ace_mode=1: acts 返回值按合并格式调整
  11800. if ((int)$ace_mode === 1) {
  11801. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11802. $act_map = [];
  11803. foreach ($table_act_data as $item) {
  11804. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11805. }
  11806. $restructured_acts = [];
  11807. foreach ($acts as $act) {
  11808. $act_segments = getProp($act, 'segments', []);
  11809. if (!is_array($act_segments)) {
  11810. continue;
  11811. }
  11812. $merged_parts = [];
  11813. foreach ($act_segments as $seg) {
  11814. $seg_num = getProp($seg, 'segment_number');
  11815. $seg_content = getProp($seg, 'segment_content');
  11816. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11817. }
  11818. $act_content = implode("\n", $merged_parts);
  11819. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11820. $restructured_acts[] = [
  11821. 'anime_id' => $anime_id,
  11822. 'episode_id' => $episode_id,
  11823. 'episode_number' => $episode_number,
  11824. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11825. 'act_number' => getProp($act, 'act_number'),
  11826. 'act_title' => getProp($act, 'act_title'),
  11827. 'act_duration' => getProp($act, 'act_duration'),
  11828. 'act_content' => $act_content,
  11829. 'created_at' => $now,
  11830. 'updated_at' => $now,
  11831. ];
  11832. }
  11833. $acts = $restructured_acts;
  11834. }
  11835. $episode['episode_id'] = $episode_id;
  11836. $episode['roles'] = $merged_roles;
  11837. $episode['scenes'] = $merged_scenes;
  11838. $episode['props'] = $merged_props;
  11839. $episode['acts'] = $acts;
  11840. return [
  11841. 'episode' => $episode,
  11842. 'episode_id' => $episode_id,
  11843. 'merged_roles' => $merged_roles,
  11844. 'merged_scenes' => $merged_scenes,
  11845. 'merged_props' => $merged_props,
  11846. ];
  11847. }
  11848. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11849. {
  11850. $content = '';
  11851. foreach ($items as $item) {
  11852. $name = trim((string)getProp($item, $nameKey));
  11853. if ($name === '' || $name === '旁白') {
  11854. continue;
  11855. }
  11856. $description = trim((string)getProp($item, 'description'));
  11857. $content .= $name . ': ' . $description;
  11858. if ($nameKey == 'role') {
  11859. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11860. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11861. $voice_name = trim(getProp($item, 'voice_name'));
  11862. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11863. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  11864. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11865. }else {
  11866. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11867. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11868. }
  11869. $content .= "\n";
  11870. }
  11871. return trim($content);
  11872. }
  11873. private function getEpisodeChatContent($animeId, $sequence, $content) {
  11874. if ((int)$sequence <= 0) {
  11875. return [];
  11876. }
  11877. $origin_content = '';
  11878. if ($content) {
  11879. $origin_content = '本集剧情内容:'.$content;
  11880. }else {
  11881. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  11882. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  11883. }
  11884. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  11885. // 获取分集信息
  11886. $episode = DB::table('mp_anime_episodes')
  11887. ->where('anime_id', $animeId)
  11888. ->where('episode_number', $sequence)
  11889. ->where('is_default', 1)
  11890. ->first();
  11891. if (!$episode) {
  11892. return [];
  11893. }
  11894. $episode_id = getProp($episode, 'id');
  11895. $episode_number = getProp($episode, 'episode_number');
  11896. $title = getProp($episode, 'title');
  11897. $intro = getProp($episode, 'intro');
  11898. $art_style = getProp($episode, 'art_style');
  11899. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11900. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11901. // 组装纯文本内容
  11902. $content = '';
  11903. // 添加分集标题和梗概
  11904. $content .= "###第{$episode_number}集:{$title}\n\n";
  11905. $content .= "###故事梗概\n";
  11906. $content .= trim($intro) . "\n\n";
  11907. // 添加美术风格
  11908. $content .= "###美术风格\n";
  11909. $content .= trim($art_style) . "\n\n";
  11910. // 添加主体列表
  11911. $content .= "###主体列表\n";
  11912. $pangbai_voice_prompt = "";
  11913. foreach ($roles as $role) {
  11914. $name = getProp($role, 'role');
  11915. $description = getProp($role, 'description');
  11916. $pic_prompt = getProp($role, 'pic_prompt');
  11917. $voice_prompt = getProp($role, 'voice_prompt');
  11918. $voice_name = getProp($role, 'voice_name');
  11919. $content .= "{$name}: {$description}";
  11920. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11921. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11922. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11923. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  11924. $content .= "\n";
  11925. }
  11926. $content .= "\n";
  11927. // 添加场景列表
  11928. $content .= "###场景列表\n";
  11929. foreach ($scenes as $scene) {
  11930. $name = getProp($scene, 'scene');
  11931. $description = getProp($scene, 'description');
  11932. $pic_prompt = getProp($scene, 'pic_prompt');
  11933. $content .= "{$name}: {$description}";
  11934. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11935. $content .= "\n";
  11936. }
  11937. $content .= "\n";
  11938. // 获取分镜信息
  11939. $segments = DB::table('mp_episode_segments')
  11940. ->where('anime_id', $animeId)
  11941. ->where('episode_id', $episode_id)
  11942. ->orderBy('segment_number')
  11943. ->get();
  11944. if ($segments && count($segments) > 0) {
  11945. if ((int)$ace_mode === 1) {
  11946. $content .= "###分段剧本\n";
  11947. // 获取片段数量
  11948. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  11949. $content .= "片段数量:{$act_count}\n";
  11950. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  11951. $content .= "\n";
  11952. }else {
  11953. $content .= "###分镜剧本\n";
  11954. }
  11955. // 按幕分组
  11956. $currentAct = null;
  11957. foreach ($segments as $segment) {
  11958. $act_number = getProp($segment, 'act_number');
  11959. $act_title = getProp($segment, 'act_title');
  11960. $act_duration = getProp($segment, 'act_duration');
  11961. $segment_number = getProp($segment, 'segment_number');
  11962. $segment_content = getProp($segment, 'segment_content');
  11963. $scene_description = getProp($segment, 'scene_description');
  11964. $scene_name = getProp($segment, 'scene_name');
  11965. $composition = getProp($segment, 'composition');
  11966. $camera_movement = getProp($segment, 'camera_movement');
  11967. $voice_type = getProp($segment, 'voice_type');
  11968. $characters = getProp($segment, 'characters');
  11969. $dialogue = getProp($segment, 'dialogue');
  11970. $frame_type = getProp($segment, 'frame_type');
  11971. $tail_frame_description = getProp($segment, 'tail_frame_description');
  11972. // 判断是否是全能模式
  11973. if ((int)$ace_mode === 1) { // 全能模式
  11974. // 如果是新的分段,添加分段标题
  11975. if ($act_number !== $currentAct) {
  11976. $currentAct = $act_number;
  11977. $content .= "##{$act_title}\n";
  11978. $content .= "时长:{$act_duration}s\n";
  11979. }
  11980. }else {
  11981. // 如果是新的幕,添加幕标题
  11982. if ($act_number !== $currentAct) {
  11983. $currentAct = $act_number;
  11984. $content .= "##第{$act_number}幕:{$scene_name}\n";
  11985. }
  11986. }
  11987. // 添加分镜信息
  11988. $content .= "分镜{$segment_number}\n";
  11989. $content .= "分镜内容:\n{$segment_content}\n";
  11990. // $content .= "画面描述:{$scene_description}\n";
  11991. // $content .= "场景:{$scene_name}\n";
  11992. // $content .= "构图设计:{$composition}\n";
  11993. // $content .= "运镜调度:{$camera_movement}\n";
  11994. // if (!empty($voice_type)) {
  11995. // $content .= "配音角色:{$voice_type}\n";
  11996. // }
  11997. // if (!empty($characters)) {
  11998. // $content .= "出镜角色:{$characters}\n";
  11999. // }
  12000. // if (!empty($dialogue)) {
  12001. // $content .= "台词内容:\"{$dialogue}\"\n";
  12002. // }
  12003. // $content .= "画面类型:{$frame_type}\n";
  12004. // $content .= "尾帧描述:{$tail_frame_description}\n";
  12005. $content .= "\n";
  12006. }
  12007. }
  12008. $content = trim($content);
  12009. if($content) $content = "上集剧本内容:\n{$content}";
  12010. return [
  12011. [
  12012. 'role' => 'user',
  12013. 'content' => $origin_content
  12014. ],
  12015. [
  12016. 'role' => 'assistant',
  12017. 'content' => $content
  12018. ]
  12019. ];
  12020. }
  12021. private function getEpisodeChatMessages($animeId, $sequence): array
  12022. {
  12023. if ((int)$sequence <= 0) {
  12024. return [];
  12025. }
  12026. return DB::table('mp_anime_records')
  12027. ->where('anime_id', $animeId)
  12028. ->where('sequence', $sequence)
  12029. ->where('episode_id', '>', 0)
  12030. ->select('role', 'content')
  12031. ->orderBy('created_at')
  12032. ->orderBy('id')
  12033. ->get()
  12034. ->map(function ($value) {
  12035. return (array)$value;
  12036. })
  12037. ->toArray();
  12038. }
  12039. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  12040. {
  12041. $existingMap = [];
  12042. foreach ($existingItems as $item) {
  12043. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12044. if ($itemKey === '') {
  12045. continue;
  12046. }
  12047. $existingMap[$itemKey] = $item;
  12048. }
  12049. if (!$generatedItems) {
  12050. return array_values($existingItems);
  12051. }
  12052. $merged = [];
  12053. foreach ($generatedItems as $item) {
  12054. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12055. if ($itemKey === '') {
  12056. continue;
  12057. }
  12058. if (isset($existingMap[$itemKey])) {
  12059. if (trim((string)getProp($item, 'description')) === '') {
  12060. $merged[] = $existingMap[$itemKey];
  12061. continue;
  12062. }
  12063. // 检查内容是否发生变化
  12064. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  12065. if (!$isChanged) {
  12066. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  12067. $mergedItem = [
  12068. $nameKey => trim((string)getProp($item, $nameKey)),
  12069. 'description' => trim((string)getProp($item, 'description')),
  12070. ];
  12071. // 如果有 pic_prompt,添加到合并项中
  12072. $picPrompt = getProp($item, 'pic_prompt');
  12073. if (!empty($picPrompt)) {
  12074. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12075. }
  12076. // 继承现有项的 URL
  12077. $existingUrl = getProp($existingMap[$itemKey], 'url');
  12078. if (!empty($existingUrl)) {
  12079. $mergedItem['url'] = $existingUrl;
  12080. }
  12081. // 继承现有项的 task_id
  12082. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  12083. if (!empty($existingTaskId)) {
  12084. $mergedItem['task_id'] = $existingTaskId;
  12085. }
  12086. // 继承现有项的 task_status
  12087. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  12088. if (!empty($existingTaskStatus)) {
  12089. $mergedItem['task_status'] = $existingTaskStatus;
  12090. }
  12091. // 保留生成项的音色字段
  12092. $voiceName = getProp($item, 'voice_name');
  12093. if (!empty($voiceName)) {
  12094. $mergedItem['voice_name'] = $voiceName;
  12095. }
  12096. $voiceType = getProp($item, 'voice_type');
  12097. if (!empty($voiceType)) {
  12098. $mergedItem['voice_type'] = $voiceType;
  12099. }
  12100. $audioUrl = getProp($item, 'voice_audio_url');
  12101. if (!empty($audioUrl)) {
  12102. $mergedItem['voice_audio_url'] = $audioUrl;
  12103. }
  12104. $merged[] = $mergedItem;
  12105. } else {
  12106. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  12107. $mergedItem = [
  12108. $nameKey => trim((string)getProp($item, $nameKey)),
  12109. 'description' => trim((string)getProp($item, 'description')),
  12110. ];
  12111. // 如果有 pic_prompt,添加到合并项中
  12112. $picPrompt = getProp($item, 'pic_prompt');
  12113. if (!empty($picPrompt)) {
  12114. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12115. }
  12116. // 保留生成项的音色字段
  12117. $voiceName = getProp($item, 'voice_name');
  12118. if (!empty($voiceName)) {
  12119. $mergedItem['voice_name'] = $voiceName;
  12120. }
  12121. $voiceType = getProp($item, 'voice_type');
  12122. if (!empty($voiceType)) {
  12123. $mergedItem['voice_type'] = $voiceType;
  12124. }
  12125. $audioUrl = getProp($item, 'voice_audio_url');
  12126. if (!empty($audioUrl)) {
  12127. $mergedItem['voice_audio_url'] = $audioUrl;
  12128. }
  12129. // 不继承 URL、task_id 和 task_status(重置状态)
  12130. $merged[] = $mergedItem;
  12131. }
  12132. } else {
  12133. // 新增项,保留生成项的所有字段
  12134. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  12135. }
  12136. }
  12137. return $merged ?: array_values($existingItems);
  12138. }
  12139. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  12140. {
  12141. $resetItem = [
  12142. $nameKey => trim((string)getProp($item, $nameKey)),
  12143. 'description' => trim((string)getProp($item, 'description')),
  12144. ];
  12145. // 保留指定的字段
  12146. foreach ($preserveFields as $field) {
  12147. $value = getProp($item, $field);
  12148. if (!empty($value)) {
  12149. $resetItem[$field] = $value;
  12150. }
  12151. }
  12152. return $resetItem;
  12153. }
  12154. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  12155. {
  12156. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  12157. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  12158. if ($existingKey !== $generatedKey) {
  12159. return true;
  12160. }
  12161. // 比较 description 是否变化
  12162. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  12163. return true;
  12164. }
  12165. // 比较 pic_prompt 是否变化
  12166. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  12167. }
  12168. private function normalizeEpisodeResourceKey($value): string
  12169. {
  12170. $value = trim((string)$value);
  12171. if ($value === '') {
  12172. return '';
  12173. }
  12174. return strtolower((string)preg_replace('/\s+/u', '', $value));
  12175. }
  12176. // 生成全局角色图片
  12177. private function batchSetGlobalRoleImg($data, $is_force=false) {
  12178. $anime_id = getProp($data, 'anime_id');
  12179. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12180. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12181. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12182. $art_style = getProp($anime, 'art_style');
  12183. $update_flag = false;
  12184. foreach ($roles as &$role) {
  12185. $role_name = getProp($role, 'role');
  12186. if ($role_name == '旁白') continue;
  12187. // 优先使用 pic_prompt,如果没有则使用 description
  12188. $pic_prompt = getProp($role, 'pic_prompt');
  12189. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12190. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12191. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12192. // 参考图地址
  12193. $ref_img_url = getProp($role, 'url');
  12194. if (!$is_force && $ref_img_url) continue;
  12195. $update_flag = true;
  12196. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12197. try {
  12198. $params = [
  12199. 'prompt' => $description,
  12200. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  12201. 'ref_img_urls' => []
  12202. ];
  12203. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12204. $task_id = $task->id;
  12205. if (!$task_id) {
  12206. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  12207. }
  12208. $role['task_id'] = $task_id;
  12209. $role['task_status'] = 'processing';
  12210. } catch (\Exception $e) {
  12211. Utils::throwError("20003:" . $e->getMessage());
  12212. }
  12213. }
  12214. if (!$update_flag) return true;
  12215. // 保存角色信息
  12216. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12217. 'roles' => json_encode($roles, 256),
  12218. 'generate_status' => '执行中',
  12219. 'generate_at' => date('Y-m-d H:i:s'),
  12220. 'updated_at' => date('Y-m-d H:i:s')
  12221. ]);
  12222. if (!$boolen) {
  12223. Utils::throwError('20003:保存角色信息失败');
  12224. }
  12225. return $boolen;
  12226. }
  12227. // 生成全局场景图片
  12228. private function batchSetGlobalSceneImg($data, $is_force=false) {
  12229. $anime_id = getProp($data, 'anime_id');
  12230. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12231. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12232. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12233. $art_style = getProp($anime, 'art_style');
  12234. $update_flag = false;
  12235. foreach ($scenes as &$scene) {
  12236. $scene_name = getProp($scene, 'scene');
  12237. // 优先使用 pic_prompt,如果没有则使用 description
  12238. $pic_prompt = getProp($scene, 'pic_prompt');
  12239. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12240. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  12241. // 参考图地址
  12242. $ref_img_url = getProp($scene, 'url');
  12243. if (!$is_force && $ref_img_url) continue;
  12244. $update_flag = true;
  12245. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12246. try {
  12247. $params = [
  12248. 'prompt' => $description,
  12249. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  12250. 'ref_img_urls' => []
  12251. ];
  12252. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12253. $task_id = $task->id;
  12254. if (!$task_id) {
  12255. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  12256. }
  12257. $scene['task_id'] = $task_id;
  12258. $scene['task_status'] = 'processing';
  12259. } catch (\Exception $e) {
  12260. Utils::throwError("20003:" . $e->getMessage());
  12261. }
  12262. }
  12263. if (!$update_flag) return true;
  12264. // 保存角色信息
  12265. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12266. 'scenes' => json_encode($scenes, 256),
  12267. 'generate_status' => '执行中',
  12268. 'generate_at' => date('Y-m-d H:i:s'),
  12269. 'updated_at' => date('Y-m-d H:i:s')
  12270. ]);
  12271. if (!$boolen) {
  12272. Utils::throwError('20003:保存角色信息失败');
  12273. }
  12274. return $boolen;
  12275. }
  12276. // 生成分镜主体、场景和道具图片
  12277. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  12278. $character_prefix = '';
  12279. $scene_prefix = '';
  12280. $prop_prefix = '';
  12281. if ($art_style_type) {
  12282. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  12283. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  12284. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  12285. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  12286. }
  12287. $update_flag = false;
  12288. // 获取上一集的roles、scenes和props数据
  12289. $prev_roles = [];
  12290. $prev_scenes = [];
  12291. $prev_props = [];
  12292. if ($episode_number > 1) {
  12293. $prev_episode = DB::table('mp_anime_episodes')
  12294. ->where('anime_id', $anime_id)
  12295. ->where('episode_number', $episode_number - 1)
  12296. ->where('is_default', 1)
  12297. ->first();
  12298. if ($prev_episode) {
  12299. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  12300. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  12301. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  12302. dLog('deepseek')->info("获取上一集数据成功", [
  12303. 'anime_id' => $anime_id,
  12304. 'prev_episode_number' => $episode_number - 1,
  12305. 'prev_roles_count' => count($prev_roles),
  12306. 'prev_scenes_count' => count($prev_scenes),
  12307. 'prev_props_count' => count($prev_props)
  12308. ]);
  12309. }
  12310. }
  12311. // 处理角色图片生成
  12312. foreach ($roles as &$role) {
  12313. $role_name = getProp($role, 'role');
  12314. if ($role_name == '旁白') continue;
  12315. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  12316. if (isset($ref_products[$role_name])) {
  12317. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  12318. if ($role['url']) continue;
  12319. }
  12320. $role_description = getProp($role, 'description');
  12321. $role_pic_prompt = getProp($role, 'pic_prompt');
  12322. $role_url = getProp($role, 'url');
  12323. // 检查是否可以从上一集继承
  12324. $inherited = false;
  12325. if (!$is_force && !empty($prev_roles)) {
  12326. foreach ($prev_roles as $prev_role) {
  12327. $prev_role_name = getProp($prev_role, 'role');
  12328. $prev_description = getProp($prev_role, 'description');
  12329. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  12330. $prev_url = getProp($prev_role, 'url');
  12331. $prev_task_id = getProp($prev_role, 'task_id');
  12332. $prev_task_status = getProp($prev_role, 'task_status');
  12333. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  12334. if ($role_name == $prev_role_name
  12335. && $role_description == $prev_description
  12336. && $role_pic_prompt == $prev_pic_prompt
  12337. && !empty($prev_url)) {
  12338. $role['task_id'] = $prev_task_id;
  12339. $role['task_status'] = $prev_task_status;
  12340. $role['url'] = $prev_url;
  12341. $inherited = true;
  12342. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  12343. 'anime_id' => $anime_id,
  12344. 'episode_number' => $episode_number,
  12345. 'task_id' => $prev_task_id,
  12346. 'url' => $prev_url
  12347. ]);
  12348. break;
  12349. }
  12350. }
  12351. }
  12352. // 如果已继承或已有url,跳过生成
  12353. if ($inherited || (!$is_force && $role_url)) {
  12354. continue;
  12355. }
  12356. // 优先使用 pic_prompt,如果没有则使用 description
  12357. $pic_prompt = getProp($role, 'pic_prompt');
  12358. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12359. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12360. $update_flag = true;
  12361. // 调用AIImageGenerationService的生成图片任务接口
  12362. try {
  12363. $params = [
  12364. 'prompt' => $description,
  12365. 'ref_img_urls' => []
  12366. ];
  12367. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12368. $task_id = $task->id;
  12369. if (!$task_id) {
  12370. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  12371. continue; // 不中断,继续处理其他角色
  12372. }
  12373. $role['task_id'] = $task_id;
  12374. $role['task_status'] = 'processing';
  12375. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  12376. 'anime_id' => $anime_id,
  12377. 'episode_number' => $episode_number,
  12378. 'task_id' => $task_id
  12379. ]);
  12380. } catch (\Exception $e) {
  12381. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  12382. // 不抛出异常,继续处理其他角色
  12383. }
  12384. }
  12385. // 处理场景图片生成
  12386. foreach ($scenes as &$scene) {
  12387. $scene_name = getProp($scene, 'scene');
  12388. $scene_description = getProp($scene, 'description');
  12389. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  12390. $scene_url = getProp($scene, 'url');
  12391. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  12392. if (isset($ref_products[$scene_name])) {
  12393. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  12394. if ($scene['url']) continue;
  12395. }
  12396. // 检查是否可以从上一集继承
  12397. $inherited = false;
  12398. if (!$is_force && !empty($prev_scenes)) {
  12399. foreach ($prev_scenes as $prev_scene) {
  12400. $prev_scene_name = getProp($prev_scene, 'scene');
  12401. $prev_description = getProp($prev_scene, 'description');
  12402. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  12403. $prev_url = getProp($prev_scene, 'url');
  12404. $prev_task_id = getProp($prev_scene, 'task_id');
  12405. $prev_task_status = getProp($prev_scene, 'task_status');
  12406. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  12407. if ($scene_name == $prev_scene_name
  12408. && $scene_description == $prev_description
  12409. && $scene_pic_prompt == $prev_pic_prompt
  12410. && !empty($prev_url)) {
  12411. $scene['task_id'] = $prev_task_id;
  12412. $scene['task_status'] = $prev_task_status;
  12413. $scene['url'] = $prev_url;
  12414. $inherited = true;
  12415. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  12416. 'anime_id' => $anime_id,
  12417. 'episode_number' => $episode_number,
  12418. 'task_id' => $prev_task_id,
  12419. 'url' => $prev_url
  12420. ]);
  12421. break;
  12422. }
  12423. }
  12424. }
  12425. // 如果已继承或已有url,跳过生成
  12426. if ($inherited || (!$is_force && $scene_url)) {
  12427. continue;
  12428. }
  12429. // 优先使用 pic_prompt,如果没有则使用 description
  12430. $pic_prompt = getProp($scene, 'pic_prompt');
  12431. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12432. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12433. $update_flag = true;
  12434. // 调用AIImageGenerationService的生成图片任务接口
  12435. try {
  12436. $params = [
  12437. 'prompt' => $description,
  12438. 'ref_img_urls' => []
  12439. ];
  12440. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12441. $task_id = $task->id;
  12442. if (!$task_id) {
  12443. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  12444. continue; // 不中断,继续处理其他场景
  12445. }
  12446. $scene['task_id'] = $task_id;
  12447. $scene['task_status'] = 'processing';
  12448. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  12449. 'anime_id' => $anime_id,
  12450. 'episode_number' => $episode_number,
  12451. 'task_id' => $task_id
  12452. ]);
  12453. } catch (\Exception $e) {
  12454. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  12455. // 不抛出异常,继续处理其他场景
  12456. }
  12457. }
  12458. // 处理道具图片生成(逻辑与场景一致)
  12459. foreach ($props as &$prop) {
  12460. $prop_name = getProp($prop, 'prop');
  12461. $prop_description = getProp($prop, 'description');
  12462. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  12463. $prop_url = getProp($prop, 'url');
  12464. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  12465. if (isset($ref_products[$prop_name])) {
  12466. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  12467. if ($prop['url']) continue;
  12468. }
  12469. // 检查是否可以从上一集继承
  12470. $inherited = false;
  12471. if (!$is_force && !empty($prev_props)) {
  12472. foreach ($prev_props as $prev_prop) {
  12473. $prev_prop_name = getProp($prev_prop, 'prop');
  12474. $prev_description = getProp($prev_prop, 'description');
  12475. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  12476. $prev_url = getProp($prev_prop, 'url');
  12477. $prev_task_id = getProp($prev_prop, 'task_id');
  12478. $prev_task_status = getProp($prev_prop, 'task_status');
  12479. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  12480. if ($prop_name == $prev_prop_name
  12481. && $prop_description == $prev_description
  12482. && $prop_pic_prompt == $prev_pic_prompt
  12483. && !empty($prev_url)) {
  12484. $prop['task_id'] = $prev_task_id;
  12485. $prop['task_status'] = $prev_task_status;
  12486. $prop['url'] = $prev_url;
  12487. $inherited = true;
  12488. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  12489. 'anime_id' => $anime_id,
  12490. 'episode_number' => $episode_number,
  12491. 'task_id' => $prev_task_id,
  12492. 'url' => $prev_url
  12493. ]);
  12494. break;
  12495. }
  12496. }
  12497. }
  12498. // 如果已继承或已有url,跳过生成
  12499. if ($inherited || (!$is_force && $prop_url)) {
  12500. continue;
  12501. }
  12502. // 优先使用 pic_prompt,如果没有则使用 description
  12503. $pic_prompt = getProp($prop, 'pic_prompt');
  12504. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  12505. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12506. $update_flag = true;
  12507. // 调用AIImageGenerationService的生成图片任务接口
  12508. try {
  12509. $params = [
  12510. 'prompt' => $description,
  12511. 'ref_img_urls' => []
  12512. ];
  12513. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12514. $task_id = $task->id;
  12515. if (!$task_id) {
  12516. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  12517. continue; // 不中断,继续处理其他道具
  12518. }
  12519. $prop['task_id'] = $task_id;
  12520. $prop['task_status'] = 'processing';
  12521. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  12522. 'anime_id' => $anime_id,
  12523. 'episode_number' => $episode_number,
  12524. 'task_id' => $task_id
  12525. ]);
  12526. } catch (\Exception $e) {
  12527. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  12528. // 不抛出异常,继续处理其他道具
  12529. }
  12530. }
  12531. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12532. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  12533. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  12534. // // 保存剧集的角色和场景信息
  12535. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  12536. // 'roles' => json_encode($roles, 256),
  12537. // 'scenes' => json_encode($scenes, 256),
  12538. // 'generate_status' => '执行中',
  12539. // 'generate_at' => date('Y-m-d H:i:s'),
  12540. // 'updated_at' => date('Y-m-d H:i:s')
  12541. // ]);
  12542. // if (!$boolen) {
  12543. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  12544. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  12545. // }
  12546. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  12547. // 'episode_id' => $episode_id,
  12548. 'roles_count' => count($roles),
  12549. 'scenes_count' => count($scenes),
  12550. 'props_count' => count($props)
  12551. ]);
  12552. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12553. }
  12554. /**
  12555. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  12556. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  12557. *
  12558. * @param int $anime_id 动漫对话ID
  12559. * @param array $episode_roles 剧集角色数据
  12560. * @param array $episode_scenes 剧集场景数据
  12561. * @param array $episode_props 剧集道具数据
  12562. * @return bool
  12563. */
  12564. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  12565. // 获取全局数据
  12566. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12567. if (!$anime) {
  12568. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12569. return false;
  12570. }
  12571. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12572. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12573. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  12574. $roles_added = false;
  12575. $roles_updated = false;
  12576. $scenes_added = false;
  12577. $props_added = false;
  12578. // 处理角色同步
  12579. foreach ($episode_roles as $episode_role) {
  12580. $episode_role_name = getProp($episode_role, 'role');
  12581. $episode_description = getProp($episode_role, 'description');
  12582. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12583. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  12584. // 跳过旁白
  12585. if ($episode_role_name == '旁白') {
  12586. continue;
  12587. }
  12588. // 检查全局中是否已存在相同的角色
  12589. $exists = false;
  12590. $global_role_index = -1;
  12591. foreach ($global_roles as $index => $global_role) {
  12592. $global_role_name = getProp($global_role, 'role');
  12593. $global_description = getProp($global_role, 'description');
  12594. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12595. // 如果role、description、pic_prompt三项都一致,则认为已存在
  12596. if ($episode_role_name == $global_role_name
  12597. && $episode_description == $global_description
  12598. && $episode_pic_prompt == $global_pic_prompt) {
  12599. $exists = true;
  12600. $global_role_index = $index;
  12601. break;
  12602. }
  12603. }
  12604. // 如果不存在,则添加到全局
  12605. if (!$exists) {
  12606. $global_roles[] = $episode_role;
  12607. $roles_added = true;
  12608. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  12609. 'anime_id' => $anime_id,
  12610. 'role' => $episode_role_name
  12611. ]);
  12612. } else {
  12613. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  12614. if (!empty($episode_voice_prompt)) {
  12615. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  12616. // 如果全局没有voice_prompt或与剧集不一致,则更新
  12617. if ($global_voice_prompt !== $episode_voice_prompt) {
  12618. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  12619. $roles_updated = true;
  12620. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  12621. 'anime_id' => $anime_id,
  12622. 'role' => $episode_role_name,
  12623. 'voice_prompt' => $episode_voice_prompt
  12624. ]);
  12625. }
  12626. }
  12627. }
  12628. }
  12629. // 处理场景同步
  12630. foreach ($episode_scenes as $episode_scene) {
  12631. $episode_scene_name = getProp($episode_scene, 'scene');
  12632. $episode_description = getProp($episode_scene, 'description');
  12633. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12634. // 检查全局中是否已存在相同的场景
  12635. $exists = false;
  12636. foreach ($global_scenes as $global_scene) {
  12637. $global_scene_name = getProp($global_scene, 'scene');
  12638. $global_description = getProp($global_scene, 'description');
  12639. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12640. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  12641. if ($episode_scene_name == $global_scene_name
  12642. && $episode_description == $global_description
  12643. && $episode_pic_prompt == $global_pic_prompt) {
  12644. $exists = true;
  12645. break;
  12646. }
  12647. }
  12648. // 如果不存在,则添加到全局
  12649. if (!$exists) {
  12650. $global_scenes[] = $episode_scene;
  12651. $scenes_added = true;
  12652. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  12653. 'anime_id' => $anime_id,
  12654. 'scene' => $episode_scene_name
  12655. ]);
  12656. }
  12657. }
  12658. // 处理道具同步(逻辑与场景一致)
  12659. foreach ($episode_props as $episode_prop) {
  12660. $episode_prop_name = getProp($episode_prop, 'prop');
  12661. $episode_description = getProp($episode_prop, 'description');
  12662. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  12663. // 检查全局中是否已存在相同的道具
  12664. $exists = false;
  12665. foreach ($global_props as $global_prop) {
  12666. $global_prop_name = getProp($global_prop, 'prop');
  12667. $global_description = getProp($global_prop, 'description');
  12668. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  12669. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  12670. if ($episode_prop_name == $global_prop_name
  12671. && $episode_description == $global_description
  12672. && $episode_pic_prompt == $global_pic_prompt) {
  12673. $exists = true;
  12674. break;
  12675. }
  12676. }
  12677. // 如果不存在,则添加到全局
  12678. if (!$exists) {
  12679. $global_props[] = $episode_prop;
  12680. $props_added = true;
  12681. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  12682. 'anime_id' => $anime_id,
  12683. 'prop' => $episode_prop_name
  12684. ]);
  12685. }
  12686. }
  12687. // 如果有新增或更新,则更新全局数据
  12688. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  12689. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12690. if ($roles_added || $roles_updated) {
  12691. $update_data['roles'] = json_encode($global_roles, 256);
  12692. }
  12693. if ($scenes_added) {
  12694. $update_data['scenes'] = json_encode($global_scenes, 256);
  12695. }
  12696. if ($props_added) {
  12697. $update_data['props'] = json_encode($global_props, 256);
  12698. }
  12699. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12700. dLog('deepseek')->info('剧集数据同步到全局完成', [
  12701. 'anime_id' => $anime_id,
  12702. 'roles_added' => $roles_added,
  12703. 'roles_updated' => $roles_updated,
  12704. 'scenes_added' => $scenes_added,
  12705. 'props_added' => $props_added,
  12706. 'global_roles_count' => count($global_roles),
  12707. 'global_scenes_count' => count($global_scenes),
  12708. 'global_props_count' => count($global_props)
  12709. ]);
  12710. }
  12711. return true;
  12712. }
  12713. /**
  12714. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  12715. *
  12716. * @param int $anime_id 动漫对话ID
  12717. * @param int $episode_id 分集ID
  12718. * @return bool
  12719. */
  12720. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  12721. // 获取全局角色和场景数据
  12722. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12723. if (!$anime) {
  12724. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12725. return false;
  12726. }
  12727. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12728. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12729. // 获取指定的分集
  12730. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  12731. if (!$episode) {
  12732. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12733. return false;
  12734. }
  12735. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12736. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12737. $roles_updated = false;
  12738. $scenes_updated = false;
  12739. // 继承角色的task_id、task_status和url
  12740. foreach ($episode_roles as &$episode_role) {
  12741. $episode_role_name = getProp($episode_role, 'role');
  12742. $episode_description = getProp($episode_role, 'description');
  12743. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12744. $episode_url = getProp($episode_role, 'url');
  12745. // 跳过旁白角色
  12746. if ($episode_role_name == '旁白') {
  12747. continue;
  12748. }
  12749. // 如果剧集中已有URL,跳过
  12750. if (!empty($episode_url)) {
  12751. continue;
  12752. }
  12753. // 遍历全局角色数据,查找匹配的角色
  12754. foreach ($global_roles as $global_role) {
  12755. $global_role_name = getProp($global_role, 'role');
  12756. $global_description = getProp($global_role, 'description');
  12757. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12758. $global_url = getProp($global_role, 'url');
  12759. $global_task_id = getProp($global_role, 'task_id');
  12760. $global_task_status = getProp($global_role, 'task_status');
  12761. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12762. if ($episode_role_name == $global_role_name
  12763. && $episode_description == $global_description
  12764. && $episode_pic_prompt == $global_pic_prompt) {
  12765. // 继承 task_id、task_status 和 url
  12766. if (!empty($global_task_id)) {
  12767. $episode_role['task_id'] = $global_task_id;
  12768. $episode_role['task_status'] = $global_task_status;
  12769. $roles_updated = true;
  12770. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12771. 'episode_id' => $episode_id,
  12772. 'role' => $episode_role_name,
  12773. 'task_id' => $global_task_id,
  12774. 'task_status' => $global_task_status
  12775. ]);
  12776. }
  12777. if (!empty($global_url)) {
  12778. $episode_role['url'] = $global_url;
  12779. $roles_updated = true;
  12780. dLog('deepseek')->info('剧集角色继承全局url', [
  12781. 'episode_id' => $episode_id,
  12782. 'role' => $episode_role_name,
  12783. 'url' => $global_url
  12784. ]);
  12785. }
  12786. break;
  12787. }
  12788. }
  12789. }
  12790. // 继承场景的task_id、task_status和url
  12791. foreach ($episode_scenes as &$episode_scene) {
  12792. $episode_scene_name = getProp($episode_scene, 'scene');
  12793. $episode_description = getProp($episode_scene, 'description');
  12794. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12795. $episode_url = getProp($episode_scene, 'url');
  12796. // 如果剧集中已有URL,跳过
  12797. if (!empty($episode_url)) {
  12798. continue;
  12799. }
  12800. // 遍历全局场景数据,查找匹配的场景
  12801. foreach ($global_scenes as $global_scene) {
  12802. $global_scene_name = getProp($global_scene, 'scene');
  12803. $global_description = getProp($global_scene, 'description');
  12804. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12805. $global_url = getProp($global_scene, 'url');
  12806. $global_task_id = getProp($global_scene, 'task_id');
  12807. $global_task_status = getProp($global_scene, 'task_status');
  12808. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12809. if ($episode_scene_name == $global_scene_name
  12810. && $episode_description == $global_description
  12811. && $episode_pic_prompt == $global_pic_prompt) {
  12812. // 继承 task_id、task_status 和 url
  12813. if (!empty($global_task_id)) {
  12814. $episode_scene['task_id'] = $global_task_id;
  12815. $episode_scene['task_status'] = $global_task_status;
  12816. $scenes_updated = true;
  12817. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12818. 'episode_id' => $episode_id,
  12819. 'scene' => $episode_scene_name,
  12820. 'task_id' => $global_task_id,
  12821. 'task_status' => $global_task_status
  12822. ]);
  12823. }
  12824. if (!empty($global_url)) {
  12825. $episode_scene['url'] = $global_url;
  12826. $scenes_updated = true;
  12827. dLog('deepseek')->info('剧集场景继承全局url', [
  12828. 'episode_id' => $episode_id,
  12829. 'scene' => $episode_scene_name,
  12830. 'url' => $global_url
  12831. ]);
  12832. }
  12833. break;
  12834. }
  12835. }
  12836. }
  12837. // 如果有更新,则保存到数据库
  12838. if ($roles_updated || $scenes_updated) {
  12839. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12840. if ($roles_updated) {
  12841. $update_data['roles'] = json_encode($episode_roles, 256);
  12842. }
  12843. if ($scenes_updated) {
  12844. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12845. }
  12846. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12847. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12848. 'episode_id' => $episode_id,
  12849. 'roles_updated' => $roles_updated,
  12850. 'scenes_updated' => $scenes_updated
  12851. ]);
  12852. }
  12853. return true;
  12854. }
  12855. public function chatChangeImg($data) {
  12856. $segment = getProp($data, 'segment');
  12857. $segment_content = getProp($segment, 'segment_content');
  12858. $prompt = getProp($data, 'prompt');
  12859. $ref_img = getProp($data, 'ref_img');
  12860. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12861. // 处理文本模型
  12862. $model = getProp($data, 'model');
  12863. if (!$model) {
  12864. // 用户没有输入,从anime表获取
  12865. $segment_id = getProp($segment, 'segment_id');
  12866. if ($segment_id) {
  12867. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  12868. if ($episode_id) {
  12869. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  12870. if ($anime_id) {
  12871. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  12872. }
  12873. }
  12874. }
  12875. if (!$model) {
  12876. // anime表也没有,使用默认值
  12877. $model = 'doubao-seed-2-0-mini-260215';
  12878. }
  12879. }
  12880. // 验证模型是否在可用模型表中
  12881. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12882. $model = 'doubao-seed-2-0-mini-260215';
  12883. }
  12884. $messages[] =
  12885. [
  12886. 'role' => 'user',
  12887. 'content' => $question
  12888. ];
  12889. $post_data = [
  12890. 'model' => $model,
  12891. 'messages' => $messages,
  12892. // 'max_tokens' => 8192,
  12893. 'temperature' => 0.7,
  12894. 'frequency_penalty' => 0,
  12895. 'presence_penalty' => 0,
  12896. 'response_format' => ['type' => 'text'],
  12897. 'stream' => false // 是否启用流式输出
  12898. ];
  12899. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12900. // DeepSeek 官方模型使用 DeepSeek API
  12901. $chatResult = $this->chatOnly($post_data);
  12902. } else if (in_array($model, $this->gpt_text_models)) {
  12903. // GPT-5.4 模型使用 TokenRouter API
  12904. $chatResult = $this->gpt54ChatOnly($post_data);
  12905. } else {
  12906. // 其他模型使用火山引擎API
  12907. $chatResult = $this->volcEngineChatCompletion($post_data);
  12908. }
  12909. if (is_array($chatResult)) {
  12910. extract($chatResult);
  12911. }else {
  12912. Utils::throwError('20003: 接口调用失败!');
  12913. }
  12914. // 仅记录 token 使用明细(不扣积分)
  12915. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  12916. 'model' => $model,
  12917. 'source' => 'chatChangeImg',
  12918. ], $model);
  12919. return [
  12920. 'type' => 'done',
  12921. // 'episode' => $episode,
  12922. 'answer' => $fullContent,
  12923. 'reasoning' => $fullReasoningContent,
  12924. 'usage' => $usage
  12925. ];
  12926. }
  12927. /**
  12928. * 仅调用 deepseek 对话接口(非流式)
  12929. *
  12930. * @param array $post_data
  12931. * @param int $timeout
  12932. * @return array
  12933. */
  12934. private function chatOnly($post_data, $timeout = 1800) {
  12935. $post_data['max_tokens'] = 300000;
  12936. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  12937. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  12938. $response = $result->getBody()->getContents();
  12939. $response_arr = json_decode($response, true);
  12940. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  12941. $fullContent = '';
  12942. $fullReasoningContent = [];
  12943. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12944. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12945. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12946. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  12947. }
  12948. return [
  12949. 'fullContent' => $fullContent,
  12950. 'fullReasoningContent' => $fullReasoningContent,
  12951. 'usage' => $usage
  12952. ];
  12953. }
  12954. /**
  12955. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  12956. *
  12957. * @param string $errorMessage
  12958. * @return string|null
  12959. */
  12960. public function analyzeErrorMessage($errorMessage)
  12961. {
  12962. try {
  12963. $post_data = [
  12964. 'model' => 'deepseek-v4-flash',
  12965. 'messages' => [
  12966. [
  12967. 'role' => 'system',
  12968. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  12969. ],
  12970. [
  12971. 'role' => 'user',
  12972. 'content' => (string)$errorMessage,
  12973. ],
  12974. ],
  12975. 'temperature' => 0.3,
  12976. 'frequency_penalty' => 0,
  12977. 'presence_penalty' => 0,
  12978. 'response_format' => ['type' => 'text'],
  12979. 'stream' => false,
  12980. ];
  12981. $result = $this->chatOnly($post_data, 8);
  12982. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  12983. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  12984. 'model' => 'deepseek-v4-flash',
  12985. 'source' => 'analyzeErrorMessage',
  12986. ], 'deepseek-v4-flash');
  12987. $content = trim((string)($result['fullContent'] ?? ''));
  12988. if ($content === '') {
  12989. return null;
  12990. }
  12991. return mb_substr($content, 0, 50);
  12992. } catch (\Exception $e) {
  12993. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  12994. 'error_message' => $errorMessage
  12995. ]);
  12996. return null;
  12997. }
  12998. }
  12999. // 仅调用 GPT-5.4 对话接口(非流式)
  13000. private function gpt54ChatOnly($post_data) {
  13001. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  13002. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  13003. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  13004. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  13005. $usedLunaFallback = false;
  13006. if (empty($apiKey)) {
  13007. Utils::throwError('20003:GPT-5.4 API Key未配置');
  13008. }
  13009. // 先探活,服务不可用时自动重试
  13010. $this->ensureGptServiceAvailable($apiKey);
  13011. $client = new Client(['timeout' => 1800, 'verify' => false]);
  13012. // 移除 thinking 参数,GPT-5.4 不支持
  13013. if (isset($post_data['thinking'])) {
  13014. unset($post_data['thinking']);
  13015. }
  13016. if (isset($post_data['reasoning_effort'])) {
  13017. unset($post_data['reasoning_effort']);
  13018. }
  13019. $post_data['max_completion_tokens'] = 100000;
  13020. // 确保 stream 为 false
  13021. $post_data['stream'] = false;
  13022. $maxRetries = $this->gptRetryTimes();
  13023. $interval = $this->gptRetryInterval();
  13024. $attempt = 0;
  13025. while (true) {
  13026. try {
  13027. $headers = [
  13028. 'Authorization' => 'Bearer ' . $apiKey,
  13029. 'Content-Type' => 'application/json'
  13030. ];
  13031. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  13032. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  13033. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  13034. 'json' => $post_data,
  13035. 'headers' => $headers
  13036. ]);
  13037. $response = $result->getBody()->getContents();
  13038. $response_arr = json_decode($response, true);
  13039. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  13040. $fullContent = '';
  13041. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  13042. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  13043. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  13044. }
  13045. return [
  13046. 'fullContent' => $fullContent,
  13047. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  13048. 'usage' => $usage
  13049. ];
  13050. } catch (\Exception $e) {
  13051. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  13052. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  13053. $usedLunaFallback = true;
  13054. $apiKey = $lunaApiKey;
  13055. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  13056. continue;
  13057. }
  13058. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  13059. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  13060. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  13061. throw $e;
  13062. }
  13063. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  13064. 'retry' => $attempt + 1,
  13065. 'max_retries' => $maxRetries,
  13066. 'error' => $e->getMessage()
  13067. ]);
  13068. sleep($interval);
  13069. $attempt++;
  13070. }
  13071. }
  13072. }
  13073. public function getContentByBid($bid) {
  13074. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  13075. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  13076. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  13077. $content = '';
  13078. foreach ($chapters as $chapter) {
  13079. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  13080. }
  13081. return $content;
  13082. }
  13083. public function getContentByScriptId($script_id) {
  13084. $content = '';
  13085. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  13086. if ($contents) {
  13087. $content = implode(PHP_EOL, $contents);
  13088. }else {
  13089. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  13090. }
  13091. return $content;
  13092. }
  13093. /**
  13094. * 根据文件类型提取文本内容
  13095. *
  13096. * @param mixed $file 文件对象或文件路径
  13097. * @return string
  13098. */
  13099. public function extractFileContent($file) {
  13100. // 获取文件路径和扩展名
  13101. if (is_string($file)) {
  13102. $filePath = $file;
  13103. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  13104. } else {
  13105. // Laravel UploadedFile 对象
  13106. $filePath = $file->getRealPath();
  13107. $extension = strtolower($file->getClientOriginalExtension());
  13108. }
  13109. $content = '';
  13110. switch ($extension) {
  13111. case 'txt':
  13112. $content = $this->extractTxtContent($filePath);
  13113. break;
  13114. case 'pdf':
  13115. $content = $this->extractPdfContent($filePath);
  13116. break;
  13117. case 'doc':
  13118. case 'docx':
  13119. $content = $this->extractWordContent($filePath);
  13120. break;
  13121. // case 'jpg':
  13122. // case 'jpeg':
  13123. // case 'png':
  13124. // case 'gif':
  13125. // case 'bmp':
  13126. // case 'webp':
  13127. // $content = $this->extractImageContent($filePath);
  13128. // break;
  13129. default:
  13130. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  13131. }
  13132. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  13133. if (!mb_check_encoding($content, 'UTF-8')) {
  13134. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  13135. $content = $cleaned === false ? $content : $cleaned;
  13136. }
  13137. return $content;
  13138. }
  13139. /**
  13140. * 提取 TXT 文件内容
  13141. */
  13142. private function extractTxtContent($filePath) {
  13143. if (!file_exists($filePath)) {
  13144. Utils::throwError('20003:文件不存在');
  13145. }
  13146. $content = file_get_contents($filePath);
  13147. // 尝试检测并转换编码
  13148. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  13149. if ($encoding && $encoding !== 'UTF-8') {
  13150. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  13151. }
  13152. return trim($content);
  13153. }
  13154. /**
  13155. * 提取 PDF 文件内容
  13156. */
  13157. private function extractPdfContent($filePath) {
  13158. if (!file_exists($filePath)) {
  13159. Utils::throwError('20003:文件不存在');
  13160. }
  13161. try {
  13162. $parser = new PdfParser();
  13163. $pdf = $parser->parseFile($filePath);
  13164. $content = $pdf->getText();
  13165. return trim($content);
  13166. } catch (\Exception $e) {
  13167. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  13168. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  13169. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  13170. }
  13171. }
  13172. /**
  13173. * 提取 Word 文件内容(支持 doc 和 docx)
  13174. */
  13175. private function extractWordContent($filePath) {
  13176. if (!file_exists($filePath)) {
  13177. Utils::throwError('20003:文件不存在');
  13178. }
  13179. try {
  13180. $phpWord = WordIOFactory::load($filePath);
  13181. $content = '';
  13182. foreach ($phpWord->getSections() as $section) {
  13183. foreach ($section->getElements() as $element) {
  13184. $content .= $this->extractWordElementText($element);
  13185. }
  13186. }
  13187. return trim($content);
  13188. } catch (\Exception $e) {
  13189. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  13190. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  13191. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  13192. }
  13193. }
  13194. /**
  13195. * 递归提取 Word 元素中的文本
  13196. */
  13197. private function extractWordElementText($element) {
  13198. $text = '';
  13199. if (method_exists($element, 'getText')) {
  13200. $text .= $element->getText() . "\n";
  13201. } elseif (method_exists($element, 'getElements')) {
  13202. foreach ($element->getElements() as $childElement) {
  13203. $text .= $this->extractWordElementText($childElement);
  13204. }
  13205. }
  13206. return $text;
  13207. }
  13208. /**
  13209. * 提取图片内容(使用火山引擎 OCR)
  13210. */
  13211. private function extractImageContent($filePath) {
  13212. if (!file_exists($filePath)) {
  13213. Utils::throwError('20003:文件不存在');
  13214. }
  13215. try {
  13216. // 读取图片并转换为 base64
  13217. $imageData = file_get_contents($filePath);
  13218. $base64Image = base64_encode($imageData);
  13219. // 调用火山引擎 OCR 服务
  13220. $content = $this->callVolcEngineOCR($base64Image);
  13221. return trim($content);
  13222. } catch (\Exception $e) {
  13223. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  13224. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  13225. Utils::throwError('20003:图片识别失败');
  13226. }
  13227. }
  13228. /**
  13229. * 调用火山引擎 OCR 服务识别图片文字
  13230. *
  13231. * @param string $base64Image base64 编码的图片数据
  13232. * @return string 识别的文字内容
  13233. */
  13234. private function callVolcEngineOCR($base64Image) {
  13235. $method = 'POST';
  13236. $service = 'cv';
  13237. $host = 'visual.volcengineapi.com';
  13238. $region = env('VOLC_REGION', 'cn-north-1');
  13239. $access_key = env('VOLC_AK');
  13240. $secret_key = env('VOLC_SK');
  13241. $action = 'OCRNormal';
  13242. $version = '2020-08-26';
  13243. if (!$access_key || !$secret_key) {
  13244. Utils::throwError('20003:请配置火山引擎 AK/SK');
  13245. }
  13246. // 请求体
  13247. $body = json_encode([
  13248. 'image_base64' => $base64Image
  13249. ]);
  13250. // 生成签名
  13251. $headers = $this->getVolcEngineSignHeaders(
  13252. $method, $service, $host, $region,
  13253. "Action={$action}&Version={$version}",
  13254. $access_key, $secret_key, $body
  13255. );
  13256. $client = new Client(['timeout' => 1800, 'verify' => false]);
  13257. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  13258. 'headers' => $headers,
  13259. 'body' => $body
  13260. ]);
  13261. $response_arr = json_decode($response->getBody()->getContents(), true);
  13262. // 提取识别的文字
  13263. $textLines = [];
  13264. if (isset($response_arr['data']['line_texts'])) {
  13265. $textLines = $response_arr['data']['line_texts'];
  13266. } elseif (isset($response_arr['data']['ocr_infos'])) {
  13267. foreach ($response_arr['data']['ocr_infos'] as $info) {
  13268. if (isset($info['text'])) {
  13269. $textLines[] = $info['text'];
  13270. }
  13271. }
  13272. }
  13273. if (empty($textLines)) {
  13274. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  13275. return '';
  13276. }
  13277. return implode("\n", $textLines);
  13278. }
  13279. /**
  13280. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  13281. */
  13282. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  13283. $contentType = 'application/json';
  13284. $accept = 'application/json';
  13285. // 获取当前UTC时间
  13286. $t = new DateTime('now', new DateTimeZone('UTC'));
  13287. $xDate = $t->format('Ymd\THis\Z');
  13288. $dateStamp = $t->format('Ymd');
  13289. // 计算 body 的 sha256 哈希
  13290. $payloadHash = hash('sha256', $body);
  13291. // 1. 拼接规范请求串
  13292. $canonicalUri = '/';
  13293. $canonicalQueryString = $queryString;
  13294. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  13295. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  13296. $canonicalRequest = implode("\n", [
  13297. $method,
  13298. $canonicalUri,
  13299. $canonicalQueryString,
  13300. $canonicalHeaders,
  13301. $signedHeaders,
  13302. $payloadHash
  13303. ]);
  13304. // 2. 拼接待签名字符串
  13305. $algorithm = 'HMAC-SHA256';
  13306. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  13307. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  13308. $stringToSign = implode("\n", [
  13309. $algorithm,
  13310. $xDate,
  13311. $credentialScope,
  13312. $hashedCanonicalRequest
  13313. ]);
  13314. // 3. 计算签名
  13315. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  13316. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  13317. // 4. 添加签名到请求头
  13318. $authorizationHeader = sprintf(
  13319. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  13320. $algorithm,
  13321. $access_key,
  13322. $credentialScope,
  13323. $signedHeaders,
  13324. $signature
  13325. );
  13326. return [
  13327. 'Accept' => $accept,
  13328. 'Content-Type' => $contentType,
  13329. 'Host' => $host,
  13330. 'X-Date' => $xDate,
  13331. 'X-Content-Sha256'=> $payloadHash,
  13332. 'Authorization' => $authorizationHeader
  13333. ];
  13334. }
  13335. public function generateScriptWords($cid, $model = 'r1') {
  13336. ini_set('max_execution_time', 0);
  13337. if (!$cid) Utils::throwError('20003: 请选择章节!');
  13338. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  13339. // 模型兼容性处理和思考模式设置
  13340. $thinkingMode = 'disabled';
  13341. $reasoningEffort = 'high';
  13342. if ($model == 'r1') {
  13343. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  13344. $thinkingMode = 'enabled';
  13345. } else {
  13346. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  13347. $thinkingMode = 'disabled';
  13348. }
  13349. $messages = [
  13350. [
  13351. 'role' => 'system',
  13352. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  13353. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  13354. 2.非对话部分请全部用旁白角色代替
  13355. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  13356. ],
  13357. [
  13358. 'role' => 'user',
  13359. 'content' => $content
  13360. ]
  13361. ];
  13362. $post_data = [
  13363. 'model' => $model,
  13364. 'messages' => $messages,
  13365. // 'max_tokens' => 8192,
  13366. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  13367. 'frequency_penalty' => 0,
  13368. 'presence_penalty' => 0,
  13369. 'thinking' => ['type' => $thinkingMode],
  13370. 'response_format' => [
  13371. 'type' => 'text'
  13372. ],
  13373. 'stream' => false
  13374. ];
  13375. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  13376. // 根据模型类型选择调用方法
  13377. $fullContent = '';
  13378. $usage = [];
  13379. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  13380. // DeepSeek 官方模型使用 DeepSeek API
  13381. $chatResult = $this->chatOnly($post_data);
  13382. } else if (in_array($model, $this->gpt_text_models)) {
  13383. // GPT-5.4 模型使用 TokenRouter API
  13384. $chatResult = $this->gpt54ChatOnly($post_data);
  13385. } else {
  13386. // 其他模型使用火山引擎API
  13387. $chatResult = $this->volcEngineChatCompletion($post_data);
  13388. }
  13389. if (is_array($chatResult)) {
  13390. $fullContent = $chatResult['fullContent'];
  13391. $usage = $chatResult['usage'] ?? [];
  13392. }
  13393. // 仅记录 token 使用明细(不扣积分)
  13394. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  13395. 'model' => $model,
  13396. 'cid' => $cid,
  13397. 'source' => 'generateScriptWords',
  13398. ], $model);
  13399. return $fullContent;
  13400. }
  13401. /**
  13402. * 智能化解析集数信息
  13403. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  13404. *
  13405. * @param string $prompt 用户输入的提示词
  13406. * @return int|null 解析出的集数,如果没有找到则返回null
  13407. */
  13408. private function extractEpisodeNumber($prompt)
  13409. {
  13410. if (empty($prompt)) {
  13411. return null;
  13412. }
  13413. // 定义各种可能的表达模式
  13414. $patterns = [
  13415. // 基本模式:改成N集、调整成N集、修改成N集
  13416. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  13417. // 扩展模式:分成N集、拆分成N集、分割成N集
  13418. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  13419. // 数量模式:N集、共N集、总共N集
  13420. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  13421. // 制作模式:制作N集、生成N集、创建N集
  13422. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  13423. // 计划模式:计划N集、预计N集、打算N集
  13424. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  13425. // 需要模式:需要N集、要N集
  13426. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  13427. // 中文数字模式:改成三集、调整成五集等
  13428. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  13429. // 英文数字模式
  13430. '/(?: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',
  13431. ];
  13432. // 中文数字转阿拉伯数字的映射
  13433. $chineseNumbers = [
  13434. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  13435. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  13436. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  13437. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  13438. ];
  13439. // 逐个尝试匹配模式
  13440. foreach ($patterns as $pattern) {
  13441. if (preg_match($pattern, $prompt, $matches)) {
  13442. $number = trim($matches[1]);
  13443. // 如果是中文数字,转换为阿拉伯数字
  13444. if (isset($chineseNumbers[$number])) {
  13445. return $chineseNumbers[$number];
  13446. }
  13447. // 如果是阿拉伯数字,直接返回
  13448. if (is_numeric($number)) {
  13449. $episodeNum = intval($number);
  13450. // 合理性检查:集数应该在1-100之间
  13451. if ($episodeNum >= 1 && $episodeNum <= 100) {
  13452. return $episodeNum;
  13453. }
  13454. }
  13455. }
  13456. }
  13457. return null;
  13458. }
  13459. /**
  13460. * 调用火山引擎对话(Chat) API
  13461. *
  13462. * @param array $params 包含以下参数:
  13463. * - model: 模型ID(必填)
  13464. * - messages: 消息列表(必填)
  13465. * - stream: 是否流式输出(可选,默认false)
  13466. * - max_tokens: 最大输出token数(可选)
  13467. * - temperature: 采样温度(可选,默认1)
  13468. * - top_p: 核采样概率(可选,默认0.7)
  13469. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  13470. * - presence_penalty: 存在惩罚系数(可选,默认0)
  13471. * - stop: 停止词(可选)
  13472. * - tools: 工具列表(可选)
  13473. * @return array|Generator 非流式返回数组,流式返回生成器
  13474. */
  13475. public function volcEngineChatCompletion(array $params)
  13476. {
  13477. $apiKey = env('VOLC_AI_API_KEY');
  13478. if (empty($apiKey)) {
  13479. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  13480. }
  13481. // 构建请求参数
  13482. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  13483. $requestData = [
  13484. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  13485. 'messages' => $params['messages'] ?? [],
  13486. ];
  13487. if (!in_array($originalModel, $this->valid_text_models)) {
  13488. Utils::throwError('20003:该模型不支持!');
  13489. }
  13490. // 添加可选参数
  13491. if (isset($params['stream'])) {
  13492. $requestData['stream'] = $params['stream'];
  13493. }
  13494. if (isset($params['stream_options'])) {
  13495. $requestData['stream_options'] = $params['stream_options'];
  13496. }
  13497. if (isset($params['max_tokens'])) {
  13498. $requestData['max_tokens'] = $params['max_tokens'];
  13499. }else if (isset($params['max_completion_tokens'])) {
  13500. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  13501. }else {
  13502. $requestData['max_completion_tokens'] = 100000;
  13503. }
  13504. if (isset($params['temperature'])) {
  13505. $requestData['temperature'] = $params['temperature'];
  13506. }
  13507. if (isset($params['top_p'])) {
  13508. $requestData['top_p'] = $params['top_p'];
  13509. }
  13510. if (isset($params['frequency_penalty'])) {
  13511. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  13512. }
  13513. if (isset($params['presence_penalty'])) {
  13514. $requestData['presence_penalty'] = $params['presence_penalty'];
  13515. }
  13516. if (isset($params['stop'])) {
  13517. $requestData['stop'] = $params['stop'];
  13518. }
  13519. if (isset($params['tools'])) {
  13520. $requestData['tools'] = $params['tools'];
  13521. }
  13522. if (isset($params['tool_choice'])) {
  13523. $requestData['tool_choice'] = $params['tool_choice'];
  13524. }
  13525. if (isset($params['response_format'])) {
  13526. $requestData['response_format'] = $params['response_format'];
  13527. }
  13528. if (isset($params['thinking'])) {
  13529. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  13530. if (is_array($params['thinking'])) {
  13531. $requestData['thinking'] = $params['thinking'];
  13532. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  13533. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13534. }
  13535. } else {
  13536. $requestData['thinking'] = ['type' => $params['thinking']];
  13537. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  13538. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13539. }
  13540. }
  13541. } else {
  13542. $requestData['thinking'] = ['type' => 'disabled'];
  13543. }
  13544. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  13545. $client = new Client(['verify' => false, 'timeout' => 1800]);
  13546. try {
  13547. // 判断是否为流式输出
  13548. $isStream = isset($params['stream']) && $params['stream'] === true;
  13549. if ($isStream) {
  13550. // 流式输出
  13551. // 流式请求默认声明返回 usage(未显式传参时)
  13552. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  13553. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  13554. } else {
  13555. // 非流式输出
  13556. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13557. 'headers' => [
  13558. 'Authorization' => 'Bearer ' . $apiKey,
  13559. 'Content-Type' => 'application/json',
  13560. ],
  13561. 'json' => $requestData
  13562. ]);
  13563. $responseData = json_decode($response->getBody(), true);
  13564. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  13565. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  13566. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  13567. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  13568. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  13569. }
  13570. return [
  13571. 'fullContent' => $fullContent,
  13572. 'fullReasoningContent' => $fullReasoningContent,
  13573. 'usage' => $usage
  13574. ];
  13575. }
  13576. } catch (\Exception $e) {
  13577. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  13578. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  13579. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  13580. }
  13581. }
  13582. /**
  13583. * 火山引擎对话API流式输出
  13584. *
  13585. * @param Client $client HTTP客户端
  13586. * @param string $apiKey API密钥
  13587. * @param array $requestData 请求数据
  13588. * @return Generator
  13589. */
  13590. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  13591. {
  13592. try {
  13593. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13594. 'headers' => [
  13595. 'Authorization' => 'Bearer ' . $apiKey,
  13596. 'Content-Type' => 'application/json',
  13597. ],
  13598. 'json' => $requestData,
  13599. 'stream' => true
  13600. ]);
  13601. $body = $response->getBody();
  13602. $buffer = '';
  13603. $fullContent = '';
  13604. $fullReasoningContent = '';
  13605. $usage = [];
  13606. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  13607. // 逐行读取流式响应
  13608. while (!$body->eof()) {
  13609. $chunk = $body->read(1024);
  13610. $buffer .= $chunk;
  13611. // 按行分割
  13612. $lines = explode("\n", $buffer);
  13613. $buffer = array_pop($lines);
  13614. foreach ($lines as $line) {
  13615. $line = trim($line);
  13616. if (empty($line)) {
  13617. continue;
  13618. }
  13619. // 检查是否是SSE数据行
  13620. if (strpos($line, 'data: ') !== 0) {
  13621. continue;
  13622. }
  13623. $data = substr($line, 6);
  13624. if ($data === '[DONE]') {
  13625. dLog('deepseek')->info('收到结束标记');
  13626. break 2;
  13627. }
  13628. try {
  13629. $json = json_decode($data, true);
  13630. if (json_last_error() !== JSON_ERROR_NONE) {
  13631. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  13632. continue;
  13633. }
  13634. if (isset($json['choices'][0]['delta'])) {
  13635. $delta = $json['choices'][0]['delta'];
  13636. // 处理思维链内容
  13637. if (isset($delta['reasoning_content'])) {
  13638. $fullReasoningContent .= $delta['reasoning_content'];
  13639. yield [
  13640. 'type' => 'reasoning',
  13641. 'content' => $delta['reasoning_content'],
  13642. 'full_reasoning' => $fullReasoningContent
  13643. ];
  13644. }
  13645. // 处理回答内容
  13646. if (isset($delta['content'])) {
  13647. $fullContent .= $delta['content'];
  13648. yield [
  13649. 'type' => 'content',
  13650. 'content' => $delta['content'],
  13651. ];
  13652. }
  13653. }
  13654. // 获取使用统计信息
  13655. if (isset($json['usage'])) {
  13656. $usage = $json['usage'];
  13657. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  13658. }
  13659. } catch (\Exception $e) {
  13660. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  13661. continue;
  13662. }
  13663. }
  13664. }
  13665. dLog('deepseek')->info('流式读取完成', [
  13666. 'content_length' => strlen($fullContent),
  13667. 'reasoning_length' => strlen($fullReasoningContent)
  13668. ]);
  13669. yield [
  13670. 'type' => 'done',
  13671. 'full_content' => $fullContent,
  13672. 'full_reasoning' => $fullReasoningContent,
  13673. 'usage' => $usage
  13674. ];
  13675. } catch (\Exception $e) {
  13676. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  13677. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  13678. throw $e;
  13679. }
  13680. }
  13681. /**
  13682. * 检查并创建图片生成任务
  13683. *
  13684. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  13685. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  13686. * @param string $nameKey 资源名称字段('role' 或 'scene')
  13687. * @param string $art_style 美术风格
  13688. * @return array 更新后的资源列表
  13689. */
  13690. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  13691. {
  13692. // 确保参数为数组
  13693. $merged_items = is_array($merged_items) ? $merged_items : [];
  13694. $global_items = is_array($global_items) ? $global_items : [];
  13695. // 构建全局资源映射表,用于快速查找
  13696. $global_map = [];
  13697. foreach ($global_items as $item) {
  13698. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13699. if ($itemKey === '') {
  13700. continue;
  13701. }
  13702. $global_map[$itemKey] = $item;
  13703. }
  13704. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  13705. foreach ($merged_items as &$item) {
  13706. $item_name = getProp($item, $nameKey);
  13707. $item_description = getProp($item, 'description');
  13708. // $item_url = getProp($item, 'url');
  13709. // // 如果已有图片URL,跳过
  13710. // if (!empty($item_url)) {
  13711. // continue;
  13712. // }
  13713. // 如果是旁白角色,跳过
  13714. if ($nameKey === 'role' && $item_name === '旁白') {
  13715. continue;
  13716. }
  13717. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13718. if ($itemKey === '') {
  13719. continue;
  13720. }
  13721. $need_create_task = false;
  13722. // 条件1:在全局资源中找不到匹配的名称
  13723. if (!isset($global_map[$itemKey])) {
  13724. $need_create_task = true;
  13725. } else {
  13726. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13727. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13728. $current_description = trim((string)$item_description);
  13729. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13730. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13731. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13732. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13733. $need_create_task = true;
  13734. }
  13735. }
  13736. // 如果需要创建任务,调用图片生成服务
  13737. if ($need_create_task) {
  13738. try {
  13739. // 优先使用 pic_prompt,如果没有则使用 description
  13740. $pic_prompt = getProp($item, 'pic_prompt');
  13741. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13742. // 添加美术风格前缀
  13743. if ($art_style) {
  13744. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13745. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13746. $description = "{$prefix}:{$description}";
  13747. }
  13748. $params = [
  13749. 'prompt' => $description,
  13750. 'ref_img_urls' => []
  13751. ];
  13752. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13753. $task_id = $task->id;
  13754. if ($task_id) {
  13755. $item['task_id'] = $task_id;
  13756. $item['task_status'] = 'processing';
  13757. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13758. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13759. }
  13760. } catch (\Exception $e) {
  13761. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13762. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13763. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13764. // 不抛出异常,继续处理其他资源
  13765. }
  13766. }
  13767. }
  13768. return $merged_items;
  13769. }
  13770. /**
  13771. * 同步新出现的主体和场景到全局
  13772. *
  13773. * @param int $anime_id 动漫ID
  13774. * @param array $merged_roles 合并后的角色列表
  13775. * @param array $merged_scenes 合并后的场景列表
  13776. * @param array $global_roles 全局角色列表
  13777. * @param array $global_scenes 全局场景列表
  13778. * @return void
  13779. */
  13780. private function syncNewResourcesToGlobal(
  13781. int $anime_id,
  13782. array $merged_roles,
  13783. array $merged_scenes,
  13784. array $global_roles,
  13785. array $global_scenes
  13786. ): void {
  13787. // 构建全局角色映射表
  13788. $global_role_map = [];
  13789. foreach ($global_roles as $role) {
  13790. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13791. if ($roleKey !== '') {
  13792. $global_role_map[$roleKey] = $role;
  13793. }
  13794. }
  13795. // 构建全局场景映射表
  13796. $global_scene_map = [];
  13797. foreach ($global_scenes as $scene) {
  13798. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13799. if ($sceneKey !== '') {
  13800. $global_scene_map[$sceneKey] = $scene;
  13801. }
  13802. }
  13803. $need_update = false;
  13804. $new_global_roles = $global_roles;
  13805. $new_global_scenes = $global_scenes;
  13806. // 检查并添加新角色到全局
  13807. foreach ($merged_roles as $role) {
  13808. $role_name = getProp($role, 'role');
  13809. // 跳过旁白
  13810. if ($role_name === '旁白') {
  13811. continue;
  13812. }
  13813. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13814. if ($roleKey === '') {
  13815. continue;
  13816. }
  13817. // 如果全局中不存在该角色,添加到全局
  13818. if (!isset($global_role_map[$roleKey])) {
  13819. $new_global_roles[] = [
  13820. 'role' => $role_name,
  13821. 'description' => getProp($role, 'description', ''),
  13822. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13823. 'voice_name' => getProp($role, 'voice_name', ''),
  13824. 'voice_type' => getProp($role, 'voice_type', ''),
  13825. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13826. 'url' => getProp($role, 'url', ''),
  13827. 'task_id' => getProp($role, 'task_id', ''),
  13828. 'task_status' => getProp($role, 'task_status', ''),
  13829. ];
  13830. $global_role_map[$roleKey] = true; // 标记已添加
  13831. $need_update = true;
  13832. dLog('deepseek')->info("新角色同步到全局", [
  13833. 'anime_id' => $anime_id,
  13834. 'role' => $role_name,
  13835. 'task_id' => getProp($role, 'task_id', ''),
  13836. ]);
  13837. }
  13838. // else {
  13839. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13840. // $global_role = $global_role_map[$roleKey];
  13841. // if (is_array($global_role)) {
  13842. // $updated = false;
  13843. // $update_fields = [];
  13844. // // 检查描述是否更新
  13845. // $current_description = trim((string)getProp($role, 'description'));
  13846. // $global_description = trim((string)getProp($global_role, 'description'));
  13847. // if ($current_description !== '' && $current_description !== $global_description) {
  13848. // $updated = true;
  13849. // $update_fields[] = 'description';
  13850. // }
  13851. // // 检查pic_prompt是否更新
  13852. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13853. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13854. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13855. // $updated = true;
  13856. // $update_fields[] = 'pic_prompt';
  13857. // }
  13858. // // 检查图片任务信息是否更新
  13859. // $current_task_id = getProp($role, 'task_id');
  13860. // $global_task_id = getProp($global_role, 'task_id');
  13861. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13862. // $updated = true;
  13863. // $update_fields[] = 'task_id';
  13864. // }
  13865. // // 如果有更新,同步到全局
  13866. // if ($updated) {
  13867. // foreach ($new_global_roles as &$global_role_item) {
  13868. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  13869. // if ($global_role_key === $roleKey) {
  13870. // if (in_array('description', $update_fields)) {
  13871. // $global_role_item['description'] = $current_description;
  13872. // }
  13873. // if (in_array('pic_prompt', $update_fields)) {
  13874. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  13875. // }
  13876. // if (in_array('task_id', $update_fields)) {
  13877. // $global_role_item['task_id'] = $current_task_id;
  13878. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  13879. // $global_role_item['url'] = getProp($role, 'url', '');
  13880. // }
  13881. // break;
  13882. // }
  13883. // }
  13884. // $need_update = true;
  13885. // dLog('deepseek')->info("角色信息更新到全局", [
  13886. // 'anime_id' => $anime_id,
  13887. // 'role' => $role_name,
  13888. // 'update_fields' => implode(',', $update_fields),
  13889. // ]);
  13890. // }
  13891. // }
  13892. // }
  13893. }
  13894. // 检查并添加新场景到全局
  13895. foreach ($merged_scenes as $scene) {
  13896. $scene_name = getProp($scene, 'scene');
  13897. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  13898. if ($sceneKey === '') {
  13899. continue;
  13900. }
  13901. // 如果全局中不存在该场景,添加到全局
  13902. if (!isset($global_scene_map[$sceneKey])) {
  13903. $new_global_scenes[] = [
  13904. 'scene' => $scene_name,
  13905. 'description' => getProp($scene, 'description', ''),
  13906. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  13907. 'url' => getProp($scene, 'url', ''),
  13908. 'task_id' => getProp($scene, 'task_id', ''),
  13909. 'task_status' => getProp($scene, 'task_status', ''),
  13910. ];
  13911. $global_scene_map[$sceneKey] = true; // 标记已添加
  13912. $need_update = true;
  13913. dLog('deepseek')->info("新场景同步到全局", [
  13914. 'anime_id' => $anime_id,
  13915. 'scene' => $scene_name,
  13916. 'task_id' => getProp($scene, 'task_id', ''),
  13917. ]);
  13918. }
  13919. // else {
  13920. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13921. // $global_scene = $global_scene_map[$sceneKey];
  13922. // if (is_array($global_scene)) {
  13923. // $updated = false;
  13924. // $update_fields = [];
  13925. // // 检查描述是否更新
  13926. // $current_description = trim((string)getProp($scene, 'description'));
  13927. // $global_description = trim((string)getProp($global_scene, 'description'));
  13928. // if ($current_description !== '' && $current_description !== $global_description) {
  13929. // $updated = true;
  13930. // $update_fields[] = 'description';
  13931. // }
  13932. // // 检查pic_prompt是否更新
  13933. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  13934. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  13935. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13936. // $updated = true;
  13937. // $update_fields[] = 'pic_prompt';
  13938. // }
  13939. // // 检查图片任务信息是否更新
  13940. // $current_task_id = getProp($scene, 'task_id');
  13941. // $global_task_id = getProp($global_scene, 'task_id');
  13942. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13943. // $updated = true;
  13944. // $update_fields[] = 'task_id';
  13945. // }
  13946. // // 如果有更新,同步到全局
  13947. // if ($updated) {
  13948. // foreach ($new_global_scenes as &$global_scene_item) {
  13949. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  13950. // if ($global_scene_key === $sceneKey) {
  13951. // if (in_array('description', $update_fields)) {
  13952. // $global_scene_item['description'] = $current_description;
  13953. // }
  13954. // if (in_array('pic_prompt', $update_fields)) {
  13955. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  13956. // }
  13957. // if (in_array('task_id', $update_fields)) {
  13958. // $global_scene_item['task_id'] = $current_task_id;
  13959. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  13960. // $global_scene_item['url'] = getProp($scene, 'url', '');
  13961. // }
  13962. // break;
  13963. // }
  13964. // }
  13965. // $need_update = true;
  13966. // dLog('deepseek')->info("场景信息更新到全局", [
  13967. // 'anime_id' => $anime_id,
  13968. // 'scene' => $scene_name,
  13969. // 'update_fields' => implode(',', $update_fields),
  13970. // ]);
  13971. // }
  13972. // }
  13973. // }
  13974. }
  13975. // 如果有新增或更新,更新数据库
  13976. if ($need_update) {
  13977. $update_data = [
  13978. 'roles' => json_encode($new_global_roles, 256),
  13979. 'scenes' => json_encode($new_global_scenes, 256),
  13980. 'updated_at' => date('Y-m-d H:i:s'),
  13981. ];
  13982. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13983. if ($result !== false) {
  13984. dLog('deepseek')->info("全局角色和场景更新成功", [
  13985. 'anime_id' => $anime_id,
  13986. 'roles_count' => count($new_global_roles),
  13987. 'scenes_count' => count($new_global_scenes),
  13988. ]);
  13989. } else {
  13990. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  13991. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  13992. }
  13993. }
  13994. }
  13995. }