DeepSeekService.php 828 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137
  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\MpUserPointsDetail;
  11. use App\Services\AIGeneration\AIImageGenerationService;
  12. use App\Services\PointsService;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. use Smalot\PdfParser\Parser as PdfParser;
  19. use TCPDF;
  20. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  21. use Predis\Command\Traits\Get\Get;
  22. class DeepSeekService
  23. {
  24. private $url;
  25. private $api_key;
  26. private $sys_message;
  27. private $headers;
  28. private $valid_text_models;
  29. private $gpt_text_models;
  30. private $gemini_text_models;
  31. protected $aiImageGenerationService;
  32. protected $pointsService;
  33. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  34. $this->aiImageGenerationService = $aiImageGenerationService;
  35. $this->pointsService = $pointsService;
  36. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  37. $this->api_key = env('DEEPSEEK_API_KEY');
  38. $this->headers = [
  39. 'Authorization' => 'Bearer '.$this->api_key,
  40. 'Content-Type' => 'application/json; charset=UTF-8'
  41. ];
  42. // 火山引擎模型列表
  43. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  44. // GPT文本模型列表
  45. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  46. // Gemini文本模型列表
  47. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  48. $this->sys_message = [
  49. 'role' => 'system',
  50. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  51. 强制要求:\n
  52. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  53. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  54. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  55. 普通要求:\n
  56. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  57. 2.<分集剧本>的要求如下:
  58.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  59.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  60.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  61.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  62. \n\n
  63. 示例如下:\n
  64. ###剧本名:西昆仑
  65. ###故事梗概
  66. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  67. ###剧本亮点
  68. 亮点1:绝境奇药,生死一线
  69. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  70. 亮点2:结拜兄妹,化解尴尬
  71. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  72. 亮点3:纤发夺命,情愫暗涌
  73. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  74. ###人物关系
  75. 阿雪与梁萧之间存在兄妹之情。
  76. ###核心矛盾
  77. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  78. ###主体列表
  79. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  80. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  81. 阴阳球:天地异宝,能化生精气,救人于危难。
  82. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  83. ###美术风格
  84. 基础画风风格词:厚涂古风
  85. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  86. ###场景列表
  87. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  88. ###分集剧本
  89. ##分集01
  90. 第1集: 第一集的标题
  91. 场景描述:地点、时间、场景
  92. 运镜:固定近距离
  93. 出场角色:男主、女主
  94. 台词内容:
  95. 女主: 女主对话
  96. 男主:男主对话
  97. 女主: 女主对话
  98. 男主: 男主对话
  99. ##分集02
  100. 第2集: 第二集的标题
  101. 场景描述:地点、时间、场景
  102. 运镜:固定近距离
  103. 出场角色:男主、女主
  104. 台词内容:
  105. 女主: 女主对话
  106. 男主:男主对话
  107. 女主: 女主对话
  108. 男主: 男主对话"
  109. ];
  110. }
  111. /**
  112. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  113. *
  114. * @param array $data 请求参数
  115. * @return \Generator 返回生成器,用于流式输出
  116. */
  117. public function generateText($data) {
  118. // 获取请求参数
  119. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  120. $messages = getProp($data, 'messages', []);
  121. $systemPrompt = getProp($data, 'system_prompt', '');
  122. $prompt = getProp($data, 'prompt', '');
  123. $images = getProp($data, 'images', []); // 支持多张图片
  124. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  125. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  126. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  127. $isGeminiModel = in_array($model, $this->gemini_text_models);
  128. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  129. Utils::throwError('20003:仅Gemini模型支持视频输入');
  130. }
  131. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  132. $uid = Site::getUid();
  133. $chargeModality = '';
  134. $chargePoints = 0;
  135. $hasImageMedia = !empty($images) || !empty($imageUrls)
  136. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  137. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  138. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  139. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  140. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  141. $pricingModel = $this->geminiMultimodalPricingModel($model);
  142. if ($pricingModel !== '') {
  143. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  144. if ($chargePoints > 0) {
  145. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  146. }
  147. }
  148. }
  149. // 如果没有提供messages,则根据system_prompt、content和images构建
  150. if (empty($messages)) {
  151. $messages = [];
  152. // 添加系统提示词
  153. if (!empty($systemPrompt)) {
  154. $messages[] = [
  155. 'role' => 'system',
  156. 'content' => $systemPrompt
  157. ];
  158. }
  159. // 构建用户消息内容(支持文本+图片)
  160. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  161. $userMessage = [
  162. 'role' => 'user',
  163. 'content' => []
  164. ];
  165. // 添加文本内容
  166. if (!empty($prompt)) {
  167. $userMessage['content'][] = [
  168. 'type' => 'text',
  169. 'text' => $prompt
  170. ];
  171. }
  172. // 处理上传的图片文件
  173. if (!empty($images)) {
  174. if (!is_array($images)) {
  175. $images = [$images];
  176. }
  177. foreach ($images as $image) {
  178. $imageBase64 = $this->processImageToBase64($image);
  179. if ($imageBase64) {
  180. $userMessage['content'][] = [
  181. 'type' => 'image_url',
  182. 'image_url' => [
  183. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  184. ]
  185. ];
  186. }
  187. }
  188. }
  189. // 处理图片URL
  190. if (!empty($imageUrls)) {
  191. if (!is_array($imageUrls)) {
  192. $imageUrls = [$imageUrls];
  193. }
  194. foreach ($imageUrls as $url) {
  195. if (!empty($url)) {
  196. $userMessage['content'][] = [
  197. 'type' => 'image_url',
  198. 'image_url' => [
  199. 'url' => $url
  200. ]
  201. ];
  202. }
  203. }
  204. }
  205. // 处理上传的视频文件(仅 Gemini)
  206. if (!empty($videos) && $isGeminiModel) {
  207. if (!is_array($videos)) {
  208. $videos = [$videos];
  209. }
  210. foreach ($videos as $video) {
  211. $inlineData = $this->processMediaToInlineData($video);
  212. if ($inlineData) {
  213. $userMessage['content'][] = [
  214. 'type' => 'video',
  215. 'inline_data' => $inlineData
  216. ];
  217. }
  218. }
  219. }
  220. // 处理视频URL(仅 Gemini)
  221. if (!empty($videoUrls) && $isGeminiModel) {
  222. if (!is_array($videoUrls)) {
  223. $videoUrls = [$videoUrls];
  224. }
  225. foreach ($videoUrls as $url) {
  226. if (!empty($url)) {
  227. $userMessage['content'][] = [
  228. 'type' => 'video_url',
  229. 'video_url' => ['url' => $url]
  230. ];
  231. }
  232. }
  233. }
  234. // 如果只有文本内容,简化为字符串格式
  235. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  236. $userMessage['content'] = $userMessage['content'][0]['text'];
  237. }
  238. $messages[] = $userMessage;
  239. }
  240. }
  241. // 验证messages不为空
  242. if (empty($messages)) {
  243. Utils::throwError('20003:请提供有效的对话内容');
  244. }
  245. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  246. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  247. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  248. if ($model === 'deepseek-chat') {
  249. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  250. $model = 'deepseek-v4-flash';
  251. $thinkingMode = 'disabled';
  252. } elseif ($model === 'deepseek-reasoner') {
  253. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  254. $model = 'deepseek-v4-flash';
  255. $thinkingMode = 'enabled';
  256. }
  257. // 构建请求参数
  258. $post_data = [
  259. 'model' => $model,
  260. 'messages' => $messages,
  261. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  262. 'temperature' => getProp($data, 'temperature', 1),
  263. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  264. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  265. 'thinking' => ['type' => $thinkingMode],
  266. 'stream' => true // 启用流式输出
  267. ];
  268. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  269. // 添加可选参数
  270. if (isset($data['top_p'])) {
  271. $post_data['top_p'] = $data['top_p'];
  272. }
  273. if (isset($data['response_format'])) {
  274. $post_data['response_format'] = $data['response_format'];
  275. }
  276. // 根据模型类型选择调用方法
  277. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  278. // DeepSeek 官方模型使用 DeepSeek API
  279. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  280. } else if (in_array($model, $this->gpt_text_models)) {
  281. // GPT 模型使用 TokenRouter API
  282. $streamGenerator = $this->gpt54StreamResponse($post_data);
  283. } else if (in_array($model, $this->gemini_text_models)) {
  284. // Gemini 模型使用 Gemini API
  285. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  286. } else if (in_array($model, $this->valid_text_models)) {
  287. // 火山引擎支持的模型使用火山引擎 API
  288. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  289. } else {
  290. Utils::throwError('20003:不支持的模型: ' . $model);
  291. }
  292. if ($chargePoints > 0) {
  293. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  294. }
  295. // 纯文本(不扣积分):流式生成成功后仅记录 token 使用明细
  296. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  297. }
  298. /**
  299. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  300. *
  301. * @param \Generator $generator
  302. * @param int $uid
  303. * @param string $model
  304. * @return \Generator
  305. */
  306. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model): \Generator
  307. {
  308. $recorded = false;
  309. foreach ($generator as $chunk) {
  310. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  311. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  312. 'model' => $model,
  313. 'source' => 'generateText',
  314. ], $model);
  315. $recorded = true;
  316. }
  317. yield $chunk;
  318. }
  319. }
  320. /**
  321. * 流式生成成功后再按 Gemini 多模态规则扣费
  322. *
  323. * @param \Generator $generator
  324. * @param int $uid
  325. * @param string $model
  326. * @param int $points
  327. * @param string $modality
  328. * @return \Generator
  329. */
  330. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  331. {
  332. $charged = false;
  333. foreach ($generator as $chunk) {
  334. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  335. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  336. if ($fullContent !== '') {
  337. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  338. $charged = true;
  339. }
  340. }
  341. yield $chunk;
  342. }
  343. }
  344. /**
  345. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  346. *
  347. * @param int $uid
  348. * @param string $model
  349. * @param int $points
  350. * @param string $modality
  351. * @param mixed $usage
  352. * @return void
  353. */
  354. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  355. {
  356. $result = $this->pointsService->recordChatCharge(
  357. $uid,
  358. $points,
  359. $this->pointsService->getTokensFromUsage($usage),
  360. [
  361. 'model' => $model,
  362. 'modality' => $modality,
  363. 'source' => 'generateText',
  364. ],
  365. '',
  366. $model
  367. );
  368. if (empty($result['charged'])) {
  369. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  370. }
  371. }
  372. /**
  373. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  374. *
  375. * @param string $model
  376. * @return string
  377. */
  378. private function geminiMultimodalPricingModel(string $model): string
  379. {
  380. $map = [
  381. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  382. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  383. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  384. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  385. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  386. ];
  387. return $map[$model] ?? '';
  388. }
  389. /**
  390. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  391. *
  392. * @param array $messages
  393. * @param array $mediaTypes
  394. * @return bool
  395. */
  396. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  397. {
  398. foreach ($messages as $message) {
  399. $content = getProp($message, 'content', '');
  400. if (!is_array($content)) {
  401. continue;
  402. }
  403. foreach ($content as $part) {
  404. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  405. return true;
  406. }
  407. }
  408. }
  409. return false;
  410. }
  411. public function createGenerateText($data) {
  412. $file = getProp($data, 'file');
  413. $episode_num = getProp($data, 'episode_num');
  414. $uid = Site::getUid();
  415. $cpid = Site::getCpid();
  416. if (!$file) {
  417. Utils::throwError('20003:请上传文件');
  418. }
  419. // 提取文件内容
  420. $content = $this->extractFileContent($file);
  421. if (!$content) {
  422. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  423. }
  424. // 拆分章节并校验章节总数、标题连续性
  425. if ($episode_num) {
  426. $this->validateGenerateTextChapters($content, (int)$episode_num);
  427. }
  428. // 获取原始文件名(不含扩展名)作为script_name
  429. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  430. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  431. // 字节安全剥离,不依赖服务器locale设置
  432. $originalName = $file->getClientOriginalName();
  433. $extension = $file->getClientOriginalExtension();
  434. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  435. ? substr($originalName, 0, -strlen($extension) - 1)
  436. : $originalName;
  437. if ($script_name === '') {
  438. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  439. }
  440. // 如果同一用户的剧本名存在则提示
  441. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  442. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  443. }
  444. // 插入数据到mp_scripts表
  445. $script_id = DB::table('mp_scripts')->insertGetId([
  446. 'script_name' => $script_name,
  447. 'user_id' => $uid,
  448. 'cpid' => $cpid,
  449. 'content' => $content,
  450. 'created_at' => date('Y-m-d H:i:s'),
  451. 'updated_at' => date('Y-m-d H:i:s')
  452. ]);
  453. return [
  454. 'script_id' => $script_id,
  455. 'script_name' => $script_name
  456. ];
  457. }
  458. /**
  459. * AI对话调用成功后的积分扣费(返回结果前调用)
  460. *
  461. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  462. *
  463. * @param int $uid
  464. * @param int $tokens
  465. * @param array $chargeInfo
  466. * @return void
  467. */
  468. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  469. {
  470. $result = $this->pointsService->recordChatCharge(
  471. $uid,
  472. PointsService::CHAT_CHARGE_POINTS,
  473. $tokens,
  474. $chargeInfo
  475. );
  476. if (empty($result['charged'])) {
  477. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  478. }
  479. }
  480. /**
  481. * 安全获取当前登录用户ID
  482. *
  483. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  484. *
  485. * @return int
  486. */
  487. private function getCurrentUid(): int
  488. {
  489. try {
  490. return (int)Site::getUid();
  491. } catch (\Throwable $e) {
  492. return 0;
  493. }
  494. }
  495. /**
  496. * 记录文生文 token 使用明细(仅记录,不扣积分)
  497. *
  498. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  499. *
  500. * @param int $uid 用户ID(0 时跳过)
  501. * @param int $tokens 消耗 token 数
  502. * @param array $chargeInfo 计费/来源信息(model、source 等)
  503. * @param string $apiType API 类型/模型标识
  504. * @return void
  505. */
  506. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  507. {
  508. try {
  509. $this->pointsService->recordTokenOnlyDetail(
  510. $uid,
  511. $tokens,
  512. $chargeInfo,
  513. MpUserPointsDetail::TYPE_CHAT,
  514. $apiType,
  515. ''
  516. );
  517. } catch (\Throwable $e) {
  518. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  519. 'uid' => $uid,
  520. 'source' => $chargeInfo['source'] ?? '',
  521. ]);
  522. }
  523. }
  524. /**
  525. * 拆分剧本内容并校验章节总数与标题连续性
  526. *
  527. * @param string $content
  528. * @param int $episodeNum
  529. * @return void
  530. */
  531. private function validateGenerateTextChapters($content, $episodeNum)
  532. {
  533. $chapters = splitContent($content);
  534. if (count($chapters) !== $episodeNum) {
  535. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  536. }
  537. if (empty($chapters)) {
  538. return;
  539. }
  540. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  541. $numbers = [];
  542. $unparsedIndex = null;
  543. foreach ($chapters as $index => $chapter) {
  544. $num = $this->parseChapterNumber($chapter['title']);
  545. if ($num === null) {
  546. $unparsedIndex = $index;
  547. break;
  548. }
  549. $numbers[] = $num;
  550. }
  551. if ($unparsedIndex === null) {
  552. $expected = 1;
  553. foreach ($numbers as $index => $num) {
  554. if ($num !== $expected) {
  555. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  556. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  557. }
  558. $expected++;
  559. }
  560. return;
  561. }
  562. // 标题格式无法用正则确认时,交给模型分析
  563. $titles = array_column($chapters, 'title');
  564. $aiResult = $this->validateChapterSequenceByAI($titles);
  565. if ($aiResult['valid'] === false) {
  566. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  567. if (isset($chapters[$badIndex - 1])) {
  568. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  569. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  570. }
  571. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  572. }
  573. if ($aiResult['valid'] === null) {
  574. if (isset($chapters[$unparsedIndex])) {
  575. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  576. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  577. }
  578. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  579. }
  580. }
  581. /**
  582. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  583. *
  584. * @param string $title
  585. * @return int|null
  586. */
  587. private function parseChapterNumber($title)
  588. {
  589. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  590. return null;
  591. }
  592. return $this->convertChineseNumber($match[1]);
  593. }
  594. /**
  595. * 中文数字转阿拉伯数字(支持到千)
  596. *
  597. * @param string $numStr
  598. * @return int
  599. */
  600. private function convertChineseNumber($numStr)
  601. {
  602. if (preg_match('/^\d+$/', $numStr)) {
  603. return (int)$numStr;
  604. }
  605. $map = [
  606. '零' => 0,
  607. '一' => 1,
  608. '二' => 2,
  609. '两' => 2,
  610. '三' => 3,
  611. '四' => 4,
  612. '五' => 5,
  613. '六' => 6,
  614. '七' => 7,
  615. '八' => 8,
  616. '九' => 9
  617. ];
  618. $total = 0;
  619. $section = 0;
  620. $length = mb_strlen($numStr);
  621. for ($i = 0; $i < $length; $i++) {
  622. $char = mb_substr($numStr, $i, 1);
  623. if (isset($map[$char])) {
  624. $section = $map[$char];
  625. } elseif ($char === '十') {
  626. $total += $section === 0 ? 10 : $section * 10;
  627. $section = 0;
  628. } elseif ($char === '百') {
  629. $total += $section === 0 ? 100 : $section * 100;
  630. $section = 0;
  631. } elseif ($char === '千') {
  632. $total += $section === 0 ? 1000 : $section * 1000;
  633. $section = 0;
  634. }
  635. }
  636. return $total + $section;
  637. }
  638. /**
  639. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  640. *
  641. * @param array $titles
  642. * @return array{valid: bool|null, invalid_index: int|null}
  643. */
  644. private function validateChapterSequenceByAI($titles)
  645. {
  646. $titleLines = [];
  647. foreach (array_slice($titles, 0, 200) as $index => $title) {
  648. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  649. }
  650. $result = [
  651. 'valid' => null,
  652. 'invalid_index' => null
  653. ];
  654. $post_data = [
  655. 'model' => 'deepseek-v4-flash',
  656. 'messages' => [
  657. [
  658. 'role' => 'system',
  659. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  660. ],
  661. [
  662. 'role' => 'user',
  663. 'content' => implode("\n", $titleLines),
  664. ],
  665. ],
  666. 'temperature' => 0,
  667. 'frequency_penalty' => 0,
  668. 'presence_penalty' => 0,
  669. 'stream' => false,
  670. ];
  671. try {
  672. $result = $this->chatOnly($post_data, 8);
  673. $content = trim((string)($result['fullContent'] ?? ''));
  674. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  675. $result['valid'] = strtolower($match[1]) === 'true';
  676. }
  677. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  678. $result['invalid_index'] = (int)$match[1];
  679. }
  680. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  681. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  682. 'model' => 'deepseek-v4-flash',
  683. 'source' => 'validateChapterSequenceByAI',
  684. ], 'deepseek-v4-flash');
  685. } catch (\Exception $e) {
  686. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  687. }
  688. return $result;
  689. }
  690. /**
  691. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  692. *
  693. * @param array $data 请求参数
  694. * @return array 返回结果数组
  695. */
  696. public function newGenerateText($data) {
  697. // 获取请求参数
  698. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  699. $messages = getProp($data, 'messages', []);
  700. $systemPrompt = getProp($data, 'system_prompt', '');
  701. $prompt = getProp($data, 'prompt', '');
  702. $images = getProp($data, 'images', []); // 支持多张图片
  703. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  704. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  705. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  706. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  707. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  708. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  709. $generateTaskId = 0;
  710. $uid = Site::getUid();
  711. if ($script_id > 0) {
  712. $existingTask = DB::table('mp_script_generate_tasks')
  713. ->where('uid', $uid)
  714. ->where('script_id', $script_id)
  715. ->orderByDesc('id')
  716. ->first();
  717. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  718. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  719. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  720. }
  721. }
  722. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  723. $originalContent = '';
  724. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  725. if ($script_id > 0) {
  726. $script = DB::table('mp_scripts')
  727. ->where('id', $script_id)
  728. ->where('is_deleted', 0)
  729. ->first();
  730. if (!$script) {
  731. Utils::throwError('20003:剧本不存在或已删除');
  732. }
  733. $originalContent = $script->content ?? '';
  734. if (empty($originalContent)) {
  735. Utils::throwError('20003:剧本内容为空');
  736. }
  737. $hasValidScript = true;
  738. // 将剧本内容添加到提示词前面
  739. if (!empty($originalContent)) {
  740. if (!empty($prompt)) {
  741. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  742. } else {
  743. $prompt = "原文内容:\n" . $originalContent;
  744. }
  745. }
  746. }
  747. // 新增: 如果提供了template_id,从数据库获取template_prompt
  748. if ($templateId > 0) {
  749. $template = DB::table('mp_prompt_templates')
  750. ->where('id', $templateId)
  751. ->where('is_deleted', 0)
  752. ->first();
  753. if (!$template) {
  754. Utils::throwError('20003:模板不存在或已删除');
  755. }
  756. $templatePrompt = $template->template_prompt ?? '';
  757. // 将模板提示词和用户输入的prompt组合
  758. // 模板为准,用户输入作为补充要求
  759. if (!empty($templatePrompt)) {
  760. if (!empty($prompt)) {
  761. $prompt = $templatePrompt . "\n\n" . $prompt;
  762. } else {
  763. $prompt = $templatePrompt;
  764. }
  765. }
  766. }
  767. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  768. if (empty($messages)) {
  769. $messages = [];
  770. // 添加系统提示词
  771. if (!empty($systemPrompt)) {
  772. $messages[] = [
  773. 'role' => 'system',
  774. 'content' => $systemPrompt
  775. ];
  776. }
  777. // 构建用户消息内容(支持文本+图片)
  778. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  779. $userMessage = [
  780. 'role' => 'user',
  781. 'content' => []
  782. ];
  783. // 添加文本内容
  784. if (!empty($prompt)) {
  785. $userMessage['content'][] = [
  786. 'type' => 'text',
  787. 'text' => $prompt
  788. ];
  789. }
  790. // 处理上传的图片文件
  791. if (!empty($images)) {
  792. if (!is_array($images)) {
  793. $images = [$images];
  794. }
  795. foreach ($images as $image) {
  796. $imageBase64 = $this->processImageToBase64($image);
  797. if ($imageBase64) {
  798. $userMessage['content'][] = [
  799. 'type' => 'image_url',
  800. 'image_url' => [
  801. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  802. ]
  803. ];
  804. }
  805. }
  806. }
  807. // 处理图片URL
  808. if (!empty($imageUrls)) {
  809. if (!is_array($imageUrls)) {
  810. $imageUrls = [$imageUrls];
  811. }
  812. foreach ($imageUrls as $url) {
  813. if (!empty($url)) {
  814. $userMessage['content'][] = [
  815. 'type' => 'image_url',
  816. 'image_url' => [
  817. 'url' => $url
  818. ]
  819. ];
  820. }
  821. }
  822. }
  823. // 如果只有文本内容,简化为字符串格式
  824. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  825. $userMessage['content'] = $userMessage['content'][0]['text'];
  826. }
  827. $messages[] = $userMessage;
  828. }
  829. }
  830. // 验证messages不为空
  831. if (empty($messages)) {
  832. Utils::throwError('20003:请提供有效的对话内容');
  833. }
  834. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  835. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  836. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  837. if ($model === 'deepseek-chat') {
  838. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  839. $model = 'deepseek-v4-flash';
  840. $thinkingMode = 'disabled';
  841. } elseif ($model === 'deepseek-reasoner') {
  842. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  843. $model = 'deepseek-v4-flash';
  844. $thinkingMode = 'enabled';
  845. }
  846. // 构建请求参数(非流式)
  847. $post_data = [
  848. 'model' => $model,
  849. 'messages' => $messages,
  850. 'temperature' => getProp($data, 'temperature', 1),
  851. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  852. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  853. 'thinking' => ['type' => $thinkingMode],
  854. 'stream' => false // 非流式输出
  855. ];
  856. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  857. // 添加可选参数
  858. if (isset($data['top_p'])) {
  859. $post_data['top_p'] = $data['top_p'];
  860. }
  861. // 新增: 根据response_format设置响应格式
  862. if ($responseFormat === 'json') {
  863. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  864. $hasJsonKeyword = false;
  865. foreach ($post_data['messages'] as $message) {
  866. if (isset($message['content'])) {
  867. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  868. if (stripos($content, 'json') !== false) {
  869. $hasJsonKeyword = true;
  870. break;
  871. }
  872. }
  873. }
  874. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  875. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  876. if (!$hasJsonKeyword) {
  877. $lastMessageIndex = count($post_data['messages']) - 1;
  878. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  879. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  880. // 如果content是字符串,直接追加
  881. if (is_string($lastContent)) {
  882. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  883. }
  884. // 如果content是数组(包含文本和图片),在文本部分追加
  885. else if (is_array($lastContent)) {
  886. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  887. if ($contentPart['type'] === 'text') {
  888. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  889. break;
  890. }
  891. }
  892. }
  893. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  894. }
  895. }
  896. // 设置response_format参数(所有支持的模型)
  897. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  898. // DeepSeek模型
  899. $post_data['response_format'] = ['type' => 'json_object'];
  900. } else if (in_array($model, $this->gpt_text_models)) {
  901. // GPT模型
  902. $post_data['response_format'] = ['type' => 'json_object'];
  903. } else if (in_array($model, $this->valid_text_models)) {
  904. // 火山引擎模型
  905. $post_data['response_format'] = ['type' => 'json_object'];
  906. }
  907. }
  908. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  909. if ($script_id > 0) {
  910. $uid = Site::getUid();
  911. // 创建新的生成任务
  912. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  913. 'uid' => $uid,
  914. 'script_id' => $script_id,
  915. 'sequence' => $sequence,
  916. 'status' => 'processing',
  917. 'prompt' => getProp($data, 'prompt', ''),
  918. 'started_at' => date('Y-m-d H:i:s'),
  919. 'created_at' => date('Y-m-d H:i:s'),
  920. 'updated_at' => date('Y-m-d H:i:s')
  921. ]);
  922. }
  923. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  924. if ($hasValidScript) {
  925. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  926. }
  927. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  928. try {
  929. $aiResult = null;
  930. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  931. // DeepSeek 官方模型使用现有的 chatOnly 方法
  932. $result = $this->chatOnly($post_data);
  933. // 记录实际使用的模型
  934. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  935. $aiResult = [
  936. 'content' => $result['fullContent'],
  937. 'reasoning_content' => $result['fullReasoningContent'],
  938. 'usage' => $result['usage'],
  939. 'model' => $model,
  940. 'finish_reason' => 'stop'
  941. ];
  942. } else if (in_array($model, $this->gpt_text_models)) {
  943. // GPT 模型使用现有的 gpt54ChatOnly 方法
  944. $result = $this->gpt54ChatOnly($post_data);
  945. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  946. $aiResult = [
  947. 'content' => $result['fullContent'],
  948. 'reasoning_content' => '',
  949. 'usage' => $result['usage'],
  950. 'model' => $model,
  951. 'finish_reason' => 'stop'
  952. ];
  953. } else if (in_array($model, $this->gemini_text_models)) {
  954. // Gemini 模型使用 Gemini API(非流式)
  955. $result = $this->geminiChatOnly($post_data, $model);
  956. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  957. $aiResult = [
  958. 'content' => $result['fullContent'],
  959. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  960. 'usage' => $result['usage'],
  961. 'model' => $model,
  962. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  963. ];
  964. } else if (in_array($model, $this->valid_text_models)) {
  965. // 火山引擎支持的模型使用火山引擎 API(非流式)
  966. $post_data['stream'] = false;
  967. $result = $this->volcEngineChatCompletion($post_data);
  968. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  969. 'requested_model' => $model,
  970. 'result_keys' => array_keys($result),
  971. 'has_fullContent' => isset($result['fullContent']),
  972. 'has_content' => isset($result['content'])
  973. ]);
  974. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  975. $aiResult = [
  976. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  977. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  978. 'usage' => $result['usage'] ?? [],
  979. 'model' => $model,
  980. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  981. ];
  982. } else {
  983. Utils::throwError('20003:不支持的模型: ' . $model);
  984. }
  985. } catch (\Exception $e) {
  986. // 生成失败,更新任务状态
  987. if ($generateTaskId) {
  988. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  989. 'status' => 'failed',
  990. 'error_message' => $e->getMessage(),
  991. 'completed_at' => date('Y-m-d H:i:s'),
  992. 'updated_at' => date('Y-m-d H:i:s')
  993. ]);
  994. }
  995. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  996. }
  997. // 生成成功,更新任务状态
  998. if ($generateTaskId && $aiResult) {
  999. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1000. 'status' => 'success',
  1001. 'result' => getProp($aiResult, 'content', ''),
  1002. 'completed_at' => date('Y-m-d H:i:s'),
  1003. 'updated_at' => date('Y-m-d H:i:s')
  1004. ]);
  1005. $aiResult['generate_task_id'] = $generateTaskId;
  1006. }
  1007. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1008. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1009. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1010. 'model' => $model,
  1011. 'script_id' => $script_id,
  1012. 'sequence' => $sequence,
  1013. 'source' => 'newGenerateText',
  1014. ]);
  1015. }
  1016. // 新增: 如果提供了script_id,保存对话记录
  1017. if ($script_id > 0 && $aiResult) {
  1018. try {
  1019. $uid = Site::getUid();
  1020. $now = now();
  1021. // 获取用户原始的prompt(不包含剧本内容)
  1022. $originalPrompt = getProp($data, 'prompt', '');
  1023. $recordsToInsert = [
  1024. [
  1025. 'uid' => $uid,
  1026. 'script_id' => $script_id,
  1027. 'sequence' => $sequence,
  1028. 'role' => 'user',
  1029. 'content' => $originalPrompt,
  1030. 'created_at' => $now,
  1031. 'updated_at' => $now,
  1032. ],
  1033. [
  1034. 'uid' => $uid,
  1035. 'script_id' => $script_id,
  1036. 'sequence' => $sequence,
  1037. 'role' => 'assistant',
  1038. 'content' => $aiResult['content'],
  1039. 'created_at' => $now,
  1040. 'updated_at' => $now,
  1041. ]
  1042. ];
  1043. DB::table('mp_script_records')->insert($recordsToInsert);
  1044. // 获取刚插入的记录ID(假设按插入顺序返回)
  1045. $insertedRecords = DB::table('mp_script_records')
  1046. ->where('uid', $uid)
  1047. ->where('script_id', $script_id)
  1048. ->where('sequence', $sequence)
  1049. ->orderBy('id', 'desc')
  1050. ->limit(2)
  1051. ->get()
  1052. ->map(function ($record) {
  1053. return [
  1054. 'rid' => $record->id,
  1055. 'script_id' => $record->script_id,
  1056. 'sequence' => $record->sequence,
  1057. 'role' => $record->role,
  1058. 'content' => $record->content,
  1059. 'created_at' => $record->created_at,
  1060. ];
  1061. })
  1062. ->reverse()
  1063. ->values()
  1064. ->toArray();
  1065. // 将记录信息添加到返回结果中
  1066. $aiResult['records'] = $insertedRecords;
  1067. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1068. } catch (\Exception $e) {
  1069. // 记录错误但不影响主流程
  1070. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1071. }
  1072. }
  1073. return $aiResult;
  1074. }
  1075. /**
  1076. * 通用 Gemini 文生文方法(支持流式和非流式)
  1077. *
  1078. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1079. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1080. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1081. * system_prompt 系统提示词(可选)
  1082. * prompt 用户提示词(可选)
  1083. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1084. * image_urls 图片/视频URL列表(可选,同上)
  1085. * temperature 温度(可选,默认 1)
  1086. * top_p 核采样(可选)
  1087. * max_tokens 最大输出 token(可选,默认 8192)
  1088. * response_format text/json(可选)
  1089. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1090. * thinking_budget 思考预算(可选,默认 20)
  1091. * stream 是否流式(可选,默认 false)
  1092. *
  1093. * @param array $data 请求参数
  1094. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1095. */
  1096. public function geminiGenerateText($data) {
  1097. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1098. $isStream = (bool)getProp($data, 'stream', false);
  1099. if (!in_array($model, $this->gemini_text_models)) {
  1100. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1101. }
  1102. $requestData = $this->buildGeminiRequestBody($data, $model);
  1103. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1104. if ($isStream) {
  1105. // 流式返回生成器
  1106. return $this->geminiStreamResponse($requestData, $model);
  1107. }
  1108. // 非流式
  1109. return $this->geminiChatOnly($requestData, $model);
  1110. }
  1111. /**
  1112. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1113. */
  1114. private function geminiMediaMaxBytes() {
  1115. return 14 * 1024 * 1024;
  1116. }
  1117. /**
  1118. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1119. */
  1120. private function buildGeminiRequestBody($data, $model) {
  1121. $messages = getProp($data, 'messages', []);
  1122. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1123. if (empty($messages)) {
  1124. $systemPrompt = getProp($data, 'system_prompt', '');
  1125. $prompt = getProp($data, 'prompt', '');
  1126. $images = getProp($data, 'images', []);
  1127. $imageUrls = getProp($data, 'image_urls', []);
  1128. $messages = [];
  1129. if (!empty($systemPrompt)) {
  1130. $messages[] = [
  1131. 'role' => 'system',
  1132. 'content' => $systemPrompt
  1133. ];
  1134. }
  1135. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1136. $userMessage = ['role' => 'user', 'content' => []];
  1137. if (!empty($prompt)) {
  1138. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1139. }
  1140. if (!empty($images)) {
  1141. if (!is_array($images)) {
  1142. $images = [$images];
  1143. }
  1144. foreach ($images as $image) {
  1145. $inlineData = $this->processMediaToInlineData($image);
  1146. if ($inlineData) {
  1147. $userMessage['content'][] = [
  1148. 'type' => 'image',
  1149. 'inline_data' => $inlineData
  1150. ];
  1151. }
  1152. }
  1153. }
  1154. if (!empty($imageUrls)) {
  1155. if (!is_array($imageUrls)) {
  1156. $imageUrls = [$imageUrls];
  1157. }
  1158. foreach ($imageUrls as $url) {
  1159. if (!empty($url)) {
  1160. $inlineData = $this->processMediaToInlineData($url);
  1161. if ($inlineData) {
  1162. $userMessage['content'][] = [
  1163. 'type' => 'image',
  1164. 'inline_data' => $inlineData
  1165. ];
  1166. }
  1167. }
  1168. }
  1169. }
  1170. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1171. $userMessage['content'] = $userMessage['content'][0]['text'];
  1172. }
  1173. $messages[] = $userMessage;
  1174. }
  1175. }
  1176. if (empty($messages)) {
  1177. Utils::throwError('20003:请提供有效的对话内容');
  1178. }
  1179. // 转换为 Gemini contents 格式
  1180. $systemInstruction = '';
  1181. $contents = [];
  1182. foreach ($messages as $message) {
  1183. $role = getProp($message, 'role', 'user');
  1184. $content = getProp($message, 'content', '');
  1185. if ($role === 'system') {
  1186. if (is_array($content)) {
  1187. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1188. } else {
  1189. $systemInstruction = (string)$content;
  1190. }
  1191. continue;
  1192. }
  1193. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1194. $parts = [];
  1195. if (is_array($content)) {
  1196. foreach ($content as $part) {
  1197. $partType = getProp($part, 'type', 'text');
  1198. if ($partType === 'text') {
  1199. $text = (string)getProp($part, 'text', '');
  1200. if ($text !== '') {
  1201. $parts[] = ['text' => $text];
  1202. }
  1203. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1204. if (in_array($partType, ['image_url', 'video_url'])) {
  1205. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1206. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1207. } elseif (isset($part['inline_data'])) {
  1208. // 已处理过的 inline_data 直接使用
  1209. $parts[] = ['inline_data' => $part['inline_data']];
  1210. continue;
  1211. } else {
  1212. $url = '';
  1213. }
  1214. $inlineData = $this->processMediaToInlineData($url);
  1215. if ($inlineData) {
  1216. $parts[] = ['inline_data' => $inlineData];
  1217. }
  1218. }
  1219. }
  1220. } else {
  1221. $text = (string)$content;
  1222. if ($text !== '') {
  1223. $parts[] = ['text' => $text];
  1224. }
  1225. }
  1226. if (!empty($parts)) {
  1227. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1228. }
  1229. }
  1230. if (empty($contents)) {
  1231. Utils::throwError('20003:请提供有效的对话内容');
  1232. }
  1233. // 构建生成配置
  1234. $generationConfig = [];
  1235. if (getProp($data, 'temperature', null) !== null) {
  1236. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1237. }
  1238. if (getProp($data, 'top_p', null) !== null) {
  1239. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1240. }
  1241. if (getProp($data, 'frequency_penalty', null) !== null) {
  1242. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1243. }
  1244. if (getProp($data, 'presence_penalty', null) !== null) {
  1245. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1246. }
  1247. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1248. if ($maxOutputTokens <= 0) {
  1249. $maxOutputTokens = 8192;
  1250. }
  1251. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1252. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1253. $maxOutputTokens = 32768;
  1254. }
  1255. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1256. // response_format 映射:text -> text/plain,json -> application/json
  1257. $responseFormat = getProp($data, 'response_format', 'text');
  1258. if (is_array($responseFormat)) {
  1259. $responseFormat = getProp($responseFormat, 'type', 'text');
  1260. }
  1261. if (in_array($responseFormat, ['json', 'json_object'])) {
  1262. $generationConfig['responseMimeType'] = 'application/json';
  1263. } else {
  1264. $generationConfig['responseMimeType'] = 'text/plain';
  1265. }
  1266. $requestData = [
  1267. 'contents' => $contents,
  1268. 'generationConfig' => $generationConfig,
  1269. ];
  1270. if ($systemInstruction !== '') {
  1271. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1272. }
  1273. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1274. $thinkingMode = getProp($data, 'thinking', null);
  1275. if (is_array($thinkingMode)) {
  1276. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1277. }
  1278. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1279. if ($thinkingMode === null) {
  1280. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1281. }
  1282. if ($thinkingMode === 'enabled') {
  1283. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1284. if ($thinkingBudget <= 0) {
  1285. $thinkingBudget = 20;
  1286. }
  1287. $requestData['generationConfig']['thinkingConfig'] = [
  1288. 'thinkingBudget' => $thinkingBudget
  1289. ];
  1290. } elseif ($defaultThinking) {
  1291. // 该模型仅支持思考模式,传 0 会返回 400
  1292. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1293. } else {
  1294. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1295. }
  1296. return $requestData;
  1297. }
  1298. /**
  1299. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1300. *
  1301. * 模型名 -> env 变量名映射:
  1302. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1303. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1304. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1305. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1306. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1307. */
  1308. private function getGeminiApiKey($model) {
  1309. $map = [
  1310. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1311. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1312. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1313. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1314. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1315. ];
  1316. if (isset($map[$model])) {
  1317. $key = env($map[$model]);
  1318. if (!empty($key)) {
  1319. return $key;
  1320. }
  1321. }
  1322. return env('GEMINI_API_KEY', '');
  1323. }
  1324. /**
  1325. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1326. */
  1327. private function geminiChatOnly($requestData, $model) {
  1328. $apiKey = $this->getGeminiApiKey($model);
  1329. if (empty($apiKey)) {
  1330. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1331. }
  1332. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1333. if (isset($requestData['messages'])) {
  1334. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1335. }
  1336. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1337. . '/models/' . $model . ':generateContent';
  1338. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1339. $headers = [
  1340. 'Authorization' => 'Bearer ' . $apiKey,
  1341. 'Content-Type' => 'application/json'
  1342. ];
  1343. $maxRetries = $this->gptRetryTimes();
  1344. $interval = $this->gptRetryInterval();
  1345. $attempt = 0;
  1346. while (true) {
  1347. try {
  1348. $response = $client->post($url, [
  1349. 'json' => $requestData,
  1350. 'headers' => $headers
  1351. ]);
  1352. $responseArr = json_decode($response->getBody()->getContents(), true);
  1353. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1354. $fullContent = $this->extractGeminiContent($responseArr);
  1355. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1356. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1357. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1358. ? $responseArr['candidates'][0]['finishReason']
  1359. : '';
  1360. return [
  1361. 'fullContent' => $fullContent,
  1362. 'fullReasoningContent' => $fullReasoningContent,
  1363. 'usage' => $usage,
  1364. 'finish_reason' => $finishReason
  1365. ];
  1366. } catch (\Exception $e) {
  1367. $retryable = true;
  1368. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1369. $status = $e->getResponse()->getStatusCode();
  1370. $retryable = $status >= 500 || $status == 429;
  1371. }
  1372. if (!$retryable || $attempt >= $maxRetries) {
  1373. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1374. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1375. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1376. }
  1377. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1378. 'retry' => $attempt + 1,
  1379. 'max_retries' => $maxRetries,
  1380. 'error' => $e->getMessage()
  1381. ]);
  1382. sleep($interval);
  1383. $attempt++;
  1384. }
  1385. }
  1386. }
  1387. /**
  1388. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1389. */
  1390. private function geminiStreamResponse($requestData, $model) {
  1391. $apiKey = $this->getGeminiApiKey($model);
  1392. if (empty($apiKey)) {
  1393. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1394. }
  1395. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1396. if (isset($requestData['messages'])) {
  1397. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1398. }
  1399. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1400. . '/models/' . $model . ':generateContent?alt=sse';
  1401. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1402. $headers = [
  1403. 'Authorization' => 'Bearer ' . $apiKey,
  1404. 'Content-Type' => 'application/json'
  1405. ];
  1406. try {
  1407. $response = $client->post($url, [
  1408. 'json' => $requestData,
  1409. 'headers' => $headers,
  1410. 'stream' => true
  1411. ]);
  1412. $body = $response->getBody();
  1413. $fullContent = '';
  1414. $fullReasoningContent = '';
  1415. $usage = [];
  1416. $buffer = '';
  1417. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1418. while (!$body->eof()) {
  1419. $chunk = $body->read(1024);
  1420. $buffer .= $chunk;
  1421. $lines = explode("\n", $buffer);
  1422. $buffer = array_pop($lines);
  1423. foreach ($lines as $line) {
  1424. $line = trim($line);
  1425. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1426. continue;
  1427. }
  1428. $data = substr($line, 6);
  1429. if ($data === '[DONE]') {
  1430. break 2;
  1431. }
  1432. try {
  1433. $json = json_decode($data, true);
  1434. if (json_last_error() !== JSON_ERROR_NONE) {
  1435. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1436. continue;
  1437. }
  1438. // 思考内容(thoughts)
  1439. $thoughts = $this->extractGeminiThoughts($json);
  1440. if ($thoughts !== '') {
  1441. $fullReasoningContent .= $thoughts;
  1442. yield [
  1443. 'type' => 'reasoning',
  1444. 'content' => $thoughts,
  1445. 'full_reasoning' => $fullReasoningContent
  1446. ];
  1447. }
  1448. // 回答内容
  1449. $partText = $this->extractGeminiContent($json);
  1450. if ($partText !== '') {
  1451. $fullContent .= $partText;
  1452. yield [
  1453. 'type' => 'content',
  1454. 'content' => $partText,
  1455. ];
  1456. }
  1457. // 使用统计
  1458. if (isset($json['usageMetadata'])) {
  1459. $usage = $json['usageMetadata'];
  1460. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1461. }
  1462. } catch (\Exception $e) {
  1463. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1464. continue;
  1465. }
  1466. }
  1467. }
  1468. dLog('deepseek')->info('Gemini流式读取完成', [
  1469. 'content_length' => strlen($fullContent),
  1470. 'reasoning_length' => strlen($fullReasoningContent)
  1471. ]);
  1472. yield [
  1473. 'type' => 'done',
  1474. 'full_content' => $fullContent,
  1475. 'full_reasoning' => $fullReasoningContent,
  1476. 'usage' => $usage
  1477. ];
  1478. } catch (\Exception $e) {
  1479. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1480. yield [
  1481. 'type' => 'error',
  1482. 'msg' => $e->getMessage(),
  1483. 'code' => $e->getCode()
  1484. ];
  1485. }
  1486. }
  1487. /**
  1488. * 从 Gemini 响应中提取回答文本
  1489. */
  1490. private function extractGeminiContent($responseArr) {
  1491. $text = '';
  1492. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1493. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1494. if (isset($part['text'])) {
  1495. $text .= $part['text'];
  1496. }
  1497. }
  1498. }
  1499. return $text;
  1500. }
  1501. /**
  1502. * 从 Gemini 响应中提取思考内容
  1503. */
  1504. private function extractGeminiReasoningContent($responseArr) {
  1505. $reasoning = '';
  1506. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1507. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1508. if (isset($thought['text'])) {
  1509. $reasoning .= $thought['text'];
  1510. }
  1511. }
  1512. }
  1513. return $reasoning;
  1514. }
  1515. /**
  1516. * 从 Gemini 流式响应中提取本次增量思考内容
  1517. */
  1518. private function extractGeminiThoughts($responseArr) {
  1519. $thoughts = '';
  1520. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1521. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1522. if (isset($thought['text'])) {
  1523. $thoughts .= $thought['text'];
  1524. }
  1525. }
  1526. }
  1527. return $thoughts;
  1528. }
  1529. /**
  1530. * 提取消息数组中的纯文本
  1531. */
  1532. private function extractGeminiTextFromParts($parts) {
  1533. $text = '';
  1534. if (is_array($parts)) {
  1535. foreach ($parts as $part) {
  1536. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1537. $text .= (string)getProp($part, 'text', '');
  1538. }
  1539. }
  1540. }
  1541. return $text;
  1542. }
  1543. /**
  1544. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1545. *
  1546. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1547. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1548. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1549. *
  1550. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1551. * @return array|null ['mime_type' => string, 'data' => string]
  1552. */
  1553. private function processMediaToInlineData($media) {
  1554. if (empty($media)) {
  1555. return null;
  1556. }
  1557. $localPath = null;
  1558. $isTempFile = false;
  1559. try {
  1560. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1561. if (is_string($media) && strpos($media, 'data:') === 0) {
  1562. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1563. return [
  1564. 'mime_type' => $matches[1],
  1565. 'data' => $matches[2]
  1566. ];
  1567. }
  1568. return null;
  1569. }
  1570. // 2. 获取本地文件路径
  1571. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1572. $localPath = $this->downloadMediaToTemp($media);
  1573. $isTempFile = true;
  1574. } elseif (is_string($media)) {
  1575. $localPath = $media;
  1576. } else {
  1577. // Laravel UploadedFile 对象
  1578. $localPath = $media->getRealPath();
  1579. }
  1580. if (!$localPath || !file_exists($localPath)) {
  1581. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1582. return null;
  1583. }
  1584. $fileSize = filesize($localPath);
  1585. $maxBytes = $this->geminiMediaMaxBytes();
  1586. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1587. $mimeType = $this->detectMediaMime($localPath);
  1588. $isVideo = strpos($mimeType, 'video/') === 0;
  1589. $needCompress = $fileSize > $maxBytes;
  1590. $duration = 0;
  1591. if ($isVideo) {
  1592. $duration = $this->getMediaDuration($localPath);
  1593. if ($duration > 300) {
  1594. $needCompress = true;
  1595. }
  1596. }
  1597. $finalPath = $localPath;
  1598. $compressedPath = null;
  1599. if ($needCompress && $this->ffmpegAvailable()) {
  1600. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1601. if ($compressed && file_exists($compressed)) {
  1602. $compressedPath = $compressed;
  1603. if (filesize($compressed) < $fileSize || $isVideo) {
  1604. $finalPath = $compressed;
  1605. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1606. } else {
  1607. @unlink($compressed);
  1608. $compressedPath = null;
  1609. }
  1610. }
  1611. }
  1612. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1613. $finalSize = filesize($finalPath);
  1614. if ($finalSize > $maxBytes) {
  1615. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1616. 'path' => $localPath,
  1617. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1618. 'limit_mb' => 14
  1619. ]);
  1620. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1621. }
  1622. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1623. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1624. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1625. }
  1626. $data = base64_encode(file_get_contents($finalPath));
  1627. return [
  1628. 'mime_type' => $mimeType,
  1629. 'data' => $data
  1630. ];
  1631. } catch (\App\Exceptions\ApiException $e) {
  1632. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1633. throw $e;
  1634. } catch (\Exception $e) {
  1635. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1636. return null;
  1637. } finally {
  1638. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1639. @unlink($compressedPath);
  1640. }
  1641. if ($isTempFile && $localPath && file_exists($localPath)) {
  1642. @unlink($localPath);
  1643. }
  1644. }
  1645. }
  1646. /**
  1647. * 下载远程多媒体到临时目录
  1648. *
  1649. * @return string|null 本地临时文件路径
  1650. */
  1651. private function downloadMediaToTemp($url) {
  1652. try {
  1653. $tempDir = storage_path('app/temp/gemini');
  1654. if (!is_dir($tempDir)) {
  1655. mkdir($tempDir, 0775, true);
  1656. }
  1657. $extension = 'tmp';
  1658. $pathInfo = parse_url($url, PHP_URL_PATH);
  1659. if ($pathInfo) {
  1660. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1661. if ($ext && strlen($ext) <= 10) {
  1662. $extension = strtolower($ext);
  1663. }
  1664. }
  1665. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1666. $client = new Client(['timeout' => 300, 'verify' => false]);
  1667. $response = $client->get($url, ['sink' => $tmpFile]);
  1668. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1669. @unlink($tmpFile);
  1670. return null;
  1671. }
  1672. return $tmpFile;
  1673. } catch (\Exception $e) {
  1674. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1675. return null;
  1676. }
  1677. }
  1678. /**
  1679. * 检测多媒体文件 MIME 类型
  1680. */
  1681. private function detectMediaMime($filePath) {
  1682. $imageInfo = @getimagesize($filePath);
  1683. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1684. return $imageInfo['mime'];
  1685. }
  1686. // 视频按扩展名粗略判断
  1687. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1688. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1689. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1690. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1691. if (isset($videoExts[$ext])) {
  1692. return $videoExts[$ext];
  1693. }
  1694. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1695. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1696. if (isset($imageExts[$ext])) {
  1697. return $imageExts[$ext];
  1698. }
  1699. return 'application/octet-stream';
  1700. }
  1701. /**
  1702. * 获取多媒体时长(秒),非视频或失败返回 0
  1703. */
  1704. private function getMediaDuration($filePath) {
  1705. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1706. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1707. $output = trim((string)shell_exec($cmd));
  1708. $duration = (float)$output;
  1709. return $duration > 0 ? $duration : 0;
  1710. }
  1711. /**
  1712. * 检查 ffmpeg 是否可用
  1713. */
  1714. private function ffmpegAvailable() {
  1715. static $available = null;
  1716. if ($available !== null) {
  1717. return $available;
  1718. }
  1719. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1720. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1721. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1722. $available = false;
  1723. return $available;
  1724. }
  1725. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1726. $output = shell_exec($cmd);
  1727. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1728. return $available;
  1729. }
  1730. /**
  1731. * 使用 ffmpeg 压缩多媒体文件
  1732. *
  1733. * @param string $inputFile 输入文件路径
  1734. * @param bool $isVideo 是否为视频
  1735. * @param float $duration 视频时长(秒),非视频传 0
  1736. * @return string|null 压缩后的文件路径,失败返回 null
  1737. */
  1738. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1739. try {
  1740. $tempDir = storage_path('app/temp/gemini');
  1741. if (!is_dir($tempDir)) {
  1742. mkdir($tempDir, 0775, true);
  1743. }
  1744. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1745. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1746. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1747. if ($isVideo) {
  1748. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1749. $speedFactor = 1.0;
  1750. if ($duration > 300) {
  1751. $speedFactor = $duration / 300;
  1752. }
  1753. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1754. $finalDuration = $duration / max(1.0, $speedFactor);
  1755. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1756. $targetBitrate = max(300, min(6000, $targetBitrate));
  1757. $filters = [];
  1758. $filters[] = 'scale=min(1280,iw):-2';
  1759. $filters[] = 'fps=24';
  1760. if ($speedFactor > 1.0) {
  1761. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1762. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1763. $fullCount = (int)ceil($speedFactor / 2.0);
  1764. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1765. if ($lastTempo < 0.5) {
  1766. $fullCount++;
  1767. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1768. }
  1769. for ($i = 0; $i < $fullCount; $i++) {
  1770. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1771. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1772. }
  1773. }
  1774. $filterStr = implode(',', $filters);
  1775. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1776. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1777. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1778. } else {
  1779. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1780. $imageInfo = @getimagesize($inputFile);
  1781. $scaleW = 2048;
  1782. $scaleH = 2048;
  1783. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1784. if ($imageInfo[0] >= $imageInfo[1]) {
  1785. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1786. $scaleW = 2048;
  1787. } else {
  1788. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1789. $scaleH = 2048;
  1790. }
  1791. }
  1792. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1793. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1794. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1795. }
  1796. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1797. $output = shell_exec($cmd);
  1798. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1799. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1800. 'input' => $inputFile,
  1801. 'output' => $output
  1802. ]);
  1803. @unlink($outputFile);
  1804. return null;
  1805. }
  1806. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1807. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1808. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1809. ]);
  1810. return $outputFile;
  1811. } catch (\Exception $e) {
  1812. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1813. return null;
  1814. }
  1815. }
  1816. /**
  1817. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1818. *
  1819. * @param array $data
  1820. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1821. */
  1822. public function getScriptGenerateTasks($data) {
  1823. $uid = Site::getUid();
  1824. return DB::table('mp_script_generate_tasks as t')
  1825. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1826. ->where('t.uid', $uid)
  1827. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1828. ->orderByDesc('t.id')
  1829. ->paginate(15);
  1830. }
  1831. public function saveScriptChatHistory($data) {
  1832. $uid = Site::getUid();
  1833. $rid = getProp($data, 'rid');
  1834. $script_id = getProp($data, 'script_id');
  1835. $sequence = getProp($data, 'sequence', 0);
  1836. $content = getProp($data, 'content');
  1837. if (!$rid) {
  1838. Utils::throwError('20003:请选择对话记录ID');
  1839. }
  1840. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1841. if (!$record) {
  1842. Utils::throwError('20003:对话记录不存在');
  1843. }
  1844. if (!$script_id) {
  1845. Utils::throwError('20003:请选择剧本');
  1846. }
  1847. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1848. if (!$script) {
  1849. Utils::throwError('20003:剧本不存在');
  1850. }
  1851. // 批量插入数据
  1852. return DB::table('mp_script_records')->where('id', $rid)->update([
  1853. 'content' => $content,
  1854. 'updated_at' => date('Y-m-d H:i:s')
  1855. ]);
  1856. }
  1857. /**
  1858. * 获取剧本的历史对话记录
  1859. *
  1860. * @param array $data 请求参数
  1861. * @return array 返回历史记录数组
  1862. */
  1863. public function getScriptChatHistory($data) {
  1864. $uid = Site::getUid();
  1865. $script_id = getProp($data, 'script_id');
  1866. $rid = getProp($data, 'rid');
  1867. $sequence = getProp($data, 'sequence', null);
  1868. if (!$script_id) {
  1869. Utils::throwError('20003:请提供剧本ID');
  1870. }
  1871. // 验证剧本是否存在
  1872. $script = DB::table('mp_scripts')
  1873. ->where('id', $script_id)
  1874. ->where('is_deleted', 0)
  1875. ->first();
  1876. if (!$script) {
  1877. Utils::throwError('20003:剧本不存在');
  1878. }
  1879. // 构建查询
  1880. $query = DB::table('mp_script_records')
  1881. ->where('script_id', $script_id);
  1882. // ->where('uid', $uid);
  1883. // 如果提供了 sequence,则过滤指定剧集
  1884. if ($sequence !== null) {
  1885. $query->where('sequence', $sequence);
  1886. }
  1887. // 记录ID筛选
  1888. if ($rid) {
  1889. $query->where('id', $rid);
  1890. }
  1891. // 查询记录并按 id 正序排序
  1892. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1893. ->orderBy('created_at', 'asc')
  1894. ->orderBy('id', 'asc')
  1895. ->get()
  1896. ->map(function ($record) {
  1897. return [
  1898. 'rid' => $record->id,
  1899. 'script_id' => $record->script_id,
  1900. 'sequence' => $record->sequence,
  1901. 'role' => $record->role,
  1902. 'content' => $record->content,
  1903. 'products' => $record->products ? json_decode($record->products) : [],
  1904. 'created_at' => $record->created_at,
  1905. ];
  1906. })
  1907. ->toArray();
  1908. return $records;
  1909. }
  1910. /**
  1911. * 处理图片转换为base64
  1912. *
  1913. * @param mixed $image 图片文件对象或文件路径
  1914. * @return string|null base64编码的图片数据
  1915. */
  1916. private function processImageToBase64($image) {
  1917. try {
  1918. // 获取文件路径
  1919. if (is_string($image)) {
  1920. $filePath = $image;
  1921. } else {
  1922. // Laravel UploadedFile 对象
  1923. $filePath = $image->getRealPath();
  1924. }
  1925. if (!file_exists($filePath)) {
  1926. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1927. return null;
  1928. }
  1929. // 验证是否为图片文件
  1930. $imageInfo = @getimagesize($filePath);
  1931. if ($imageInfo === false) {
  1932. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1933. return null;
  1934. }
  1935. // 读取图片并转换为base64
  1936. $imageData = file_get_contents($filePath);
  1937. $base64Image = base64_encode($imageData);
  1938. dLog('deepseek')->info('图片转换成功', [
  1939. 'size' => strlen($imageData),
  1940. 'type' => $imageInfo['mime']
  1941. ]);
  1942. return $base64Image;
  1943. } catch (\Exception $e) {
  1944. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1945. return null;
  1946. }
  1947. }
  1948. private function getArtStylePromptMappings($art_style='')
  1949. {
  1950. $arr = [
  1951. '唯美真人风格' => [
  1952. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1953. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1954. ],
  1955. '真人古风风格' => [
  1956. 'aliases' => ['真人古风风格', '真人古风'],
  1957. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1958. ],
  1959. '日系动漫风格' => [
  1960. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1961. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1962. ],
  1963. '国漫风格' => [
  1964. 'aliases' => ['国漫风格', '国漫'],
  1965. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1966. ],
  1967. 'Q版卡通风格' => [
  1968. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1969. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1970. ],
  1971. '简约扁平风格' => [
  1972. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1973. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1974. ],
  1975. '武侠风格' => [
  1976. 'aliases' => ['武侠风格', '武侠'],
  1977. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1978. ],
  1979. '古风仙侠风格' => [
  1980. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1981. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1982. ],
  1983. '新中式水墨风格' => [
  1984. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1985. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1986. ],
  1987. '写实插画风格' => [
  1988. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1989. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1990. ],
  1991. '3D卡通风格' => [
  1992. 'aliases' => ['3D卡通风格', '3D卡通'],
  1993. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1994. ],
  1995. '条漫风格' => [
  1996. 'aliases' => ['条漫风格', '条漫'],
  1997. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1998. ],
  1999. '赛博朋克风格' => [
  2000. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2001. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2002. ],
  2003. '暗黑悬疑风格' => [
  2004. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2005. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2006. ],
  2007. '治愈清新风格' => [
  2008. 'aliases' => ['治愈清新风格', '治愈清新'],
  2009. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2010. ],
  2011. '3D真人风格' => [
  2012. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2013. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2014. ],
  2015. ];
  2016. if($art_style) {
  2017. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2018. }
  2019. return $arr;
  2020. $arr = [
  2021. '唯美真人风格' => [
  2022. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2023. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2024. 2. 色彩色调
  2025. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2026. 3. 画质精度
  2027. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2028. 4. 画面观感
  2029. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2030. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2031. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2032. ],
  2033. '真人古风风格' => [
  2034. 'aliases' => ['真人古风风格', '真人古风'],
  2035. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2036. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2037. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2038. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2039. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2040. ],
  2041. '日系动漫风格' => [
  2042. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2043. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2044. 正向提示词(中文)
  2045. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2046. 必须遵守规则
  2047. • 全程保持日系动漫风格,不混入其他画风
  2048. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2049. • 画面适配所选画面比例,构图居中,主体突出
  2050. • 线条干净、色彩统一,不杂乱、不突兀
  2051. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2052. ],
  2053. '国漫风格' => [
  2054. 'aliases' => ['国漫风格', '国漫'],
  2055. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2056. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2057. 必须遵守规则
  2058. • 严格保持国漫画风,不串风格、不混画风
  2059. • 角色形象统一,不随意改变五官、身材、服饰
  2060. • 画面构图稳定,适合漫剧叙事展示
  2061. • 色调统一,不出现脏色、杂色
  2062. 禁止/避免词汇
  2063. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2064. ],
  2065. 'Q版卡通风格' => [
  2066. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2067. 'prompt' => "风格说明
  2068. 头大身小,造型可爱圆润,简约干净
  2069. 正向提示词(中文)
  2070. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2071. 必须遵守规则
  2072. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2073. • 角色造型统一,表情可爱,不诡异
  2074. • 画面简洁清爽,无多余复杂元素
  2075. • 色彩明亮柔和,不刺眼
  2076. 禁止/避免词汇
  2077. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2078. ],
  2079. '简约扁平风格' => [
  2080. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2081. 'prompt' => "风格说明
  2082. 色块简洁、无复杂渐变,现代极简风
  2083. 正向提示词(中文)
  2084. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2085. 必须遵守规则
  2086. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2087. • 构图简洁,主体突出,无多余装饰
  2088. • 色彩统一、干净,不杂乱
  2089. 禁止/避免词汇
  2090. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2091. ],
  2092. '武侠风格' => [
  2093. 'aliases' => ['武侠风格', '武侠'],
  2094. 'prompt' => "风格说明
  2095. 江湖气息,线条硬朗,动作感强
  2096. 正向提示词(中文)
  2097. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2098. 必须遵守规则
  2099. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2100. • 角色形象、服饰、身材比例统一
  2101. • 画面动作自然,不扭曲、不畸形
  2102. 禁止/避免词汇
  2103. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2104. ],
  2105. '古风仙侠风格' => [
  2106. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2107. 'prompt' => "风格说明
  2108. 飘逸汉服、云雾仙气、唯美空灵
  2109. 正向提示词(中文)
  2110. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2111. 必须遵守规则
  2112. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2113. • 角色服饰、发型、形象前后一致
  2114. • 场景仙气飘逸,色调清雅统一
  2115. • 画面唯美柔和,不阴暗、不诡异
  2116. 禁止/避免词汇
  2117. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2118. ],
  2119. '新中式水墨风格' => [
  2120. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2121. 'prompt' => "风格说明
  2122. 淡墨渲染,毛笔笔触,留白意境
  2123. 正向提示词(中文)
  2124. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2125. 必须遵守规则
  2126. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2127. • 色调淡雅统一,不浓艳杂乱
  2128. • 画面干净有意境,不堆砌元素
  2129. 禁止/避免词汇
  2130. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2131. ],
  2132. '写实插画风格' => [
  2133. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2134. 'prompt' => "风格说明
  2135. 接近真人比例,光影真实,质感细腻
  2136. 正向提示词(中文)
  2137. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2138. 必须遵守规则
  2139. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2140. • 角色五官、身材、服饰高度统一
  2141. • 画面清晰、光影自然、不扭曲
  2142. 禁止/避免词汇
  2143. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2144. ],
  2145. '3D卡通风格' => [
  2146. 'aliases' => ['3D卡通风格', '3D卡通'],
  2147. 'prompt' => "风格说明
  2148. 3D建模质感,柔和渲染,圆润可爱
  2149. 正向提示词(中文)
  2150. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2151. 必须遵守规则
  2152. • 保持3D卡通统一质感,不出现2D杂乱线条
  2153. • 角色模型、比例、形象前后一致
  2154. • 画面干净,不模糊、不穿模
  2155. 禁止/避免词汇
  2156. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2157. ],
  2158. '条漫风格' => [
  2159. 'aliases' => ['条漫风格', '条漫'],
  2160. 'prompt' => "风格说明
  2161. 纵向分镜,上下滑动阅读,轻量化
  2162. 正向提示词(中文)
  2163. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2164. 必须遵守规则
  2165. • 保持条漫纵向阅读逻辑,构图简洁
  2166. • 画风统一,不混写实、3D、水墨
  2167. • 画面干净,不杂乱
  2168. 禁止/避免词汇
  2169. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2170. ],
  2171. '赛博朋克风格' => [
  2172. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2173. 'prompt' => "风格说明
  2174. 霓虹灯光、未来都市、暗色调、科技机械
  2175. 正向提示词(中文)
  2176. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2177. 必须遵守规则
  2178. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2179. • 色调以暗调+霓虹为主,色彩统一
  2180. • 画面科技感强,不杂乱
  2181. 禁止/避免词汇
  2182. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2183. ],
  2184. '暗黑悬疑风格' => [
  2185. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2186. 'prompt' => "风格说明
  2187. 低饱和、冷色调、阴影重、神秘压抑
  2188. 正向提示词(中文)
  2189. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2190. 必须遵守规则
  2191. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2192. • 画面氛围压抑神秘,但不低俗、不血腥
  2193. • 角色形象统一,不崩坏
  2194. 禁止/避免词汇
  2195. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2196. ],
  2197. '治愈清新风格' => [
  2198. 'aliases' => ['治愈清新风格', '治愈清新'],
  2199. 'prompt' => "风格说明
  2200. 马卡龙色系、柔光、温暖干净
  2201. 正向提示词(中文)
  2202. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2203. 必须遵守规则
  2204. • 保持治愈清新统一色调,不阴暗、不诡异
  2205. • 画面柔和干净,无杂乱元素
  2206. • 角色形象柔和可爱,不狰狞
  2207. 禁止/避免词汇
  2208. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2209. ],
  2210. ];
  2211. return $arr;
  2212. }
  2213. public function getArtStylePromptByInput($inputArtStyle): string
  2214. {
  2215. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2216. if ($normalizedInput === '') {
  2217. return '';
  2218. }
  2219. return $this->getArtStylePromptMappings($normalizedInput);
  2220. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2221. // foreach ($mapping['aliases'] as $alias) {
  2222. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2223. // if ($normalizedAlias === '') {
  2224. // continue;
  2225. // }
  2226. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2227. // return $mapping['prompt'];
  2228. // }
  2229. // }
  2230. // }
  2231. return '';
  2232. }
  2233. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2234. $stylePrefixes = [
  2235. '唯美真人风格' => [
  2236. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2237. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2238. ],
  2239. '真人古风风格' => [
  2240. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2241. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2242. ],
  2243. '日系动漫风格' => [
  2244. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2245. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2246. ],
  2247. '国漫风格' => [
  2248. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2249. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2250. ],
  2251. 'Q版卡通风格' => [
  2252. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2253. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2254. ],
  2255. '简约扁平风格' => [
  2256. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2257. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2258. ],
  2259. '武侠风格' => [
  2260. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2261. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2262. ],
  2263. '古风仙侠风格' => [
  2264. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2265. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2266. ],
  2267. '新中式水墨风格' => [
  2268. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2269. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2270. ],
  2271. '写实插画风格' => [
  2272. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2273. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2274. ],
  2275. '3D卡通风格' => [
  2276. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2277. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2278. ],
  2279. '条漫风格' => [
  2280. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2281. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2282. ],
  2283. '赛博朋克风格' => [
  2284. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2285. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2286. ],
  2287. '暗黑悬疑风格' => [
  2288. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2289. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2290. ],
  2291. '治愈清新风格' => [
  2292. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2293. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2294. ]
  2295. ];
  2296. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2297. }
  2298. private function normalizeArtStyleInput($value): string
  2299. {
  2300. $value = trim((string)$value);
  2301. if ($value === '') {
  2302. return '';
  2303. }
  2304. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2305. return mb_strtolower($value, 'UTF-8');
  2306. }
  2307. private function replaceArtStyleSection(string $content, string $artStyle): string
  2308. {
  2309. if ($content === '' || $artStyle === '') {
  2310. return $content;
  2311. }
  2312. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2313. if (!preg_match($pattern, $content)) {
  2314. return $content;
  2315. }
  2316. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2317. }
  2318. /**
  2319. * DeepSeek流式输出处理方法
  2320. *
  2321. * @param array $post_data DeepSeek API请求参数
  2322. * @return \Generator 返回生成器,用于流式输出
  2323. */
  2324. private function unwrapJsonWrappedContent($content) {
  2325. $trimmed = ltrim((string)$content);
  2326. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2327. return $content;
  2328. }
  2329. $decoded = json_decode($trimmed, true);
  2330. if (!is_array($decoded)) {
  2331. return $content;
  2332. }
  2333. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2334. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2335. return $decoded[$key];
  2336. }
  2337. }
  2338. return $content;
  2339. }
  2340. private function deepSeekStreamResponse($post_data) {
  2341. // 设置最大输出tokens
  2342. $post_data['max_tokens'] = 300000;
  2343. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2344. $post_data['stream_options'] = ['include_usage' => true];
  2345. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2346. $response = $client->post($this->url, [
  2347. 'json' => $post_data,
  2348. 'headers' => $this->headers,
  2349. 'stream' => true // 启用流式响应
  2350. ]);
  2351. $body = $response->getBody();
  2352. $fullContent = '';
  2353. $fullReasoningContent = '';
  2354. $usage = [];
  2355. $buffer = '';
  2356. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2357. // 逐行读取流式响应
  2358. while (!$body->eof()) {
  2359. $chunk = $body->read(1024); // 每次读取 1KB
  2360. $buffer .= $chunk;
  2361. // 按行分割
  2362. $lines = explode("\n", $buffer);
  2363. // 保留最后一个不完整的行
  2364. $buffer = array_pop($lines);
  2365. foreach ($lines as $line) {
  2366. $line = trim($line);
  2367. // 跳过空行
  2368. if (empty($line)) {
  2369. continue;
  2370. }
  2371. // 检查是否是 SSE 数据行
  2372. if (strpos($line, 'data: ') !== 0) {
  2373. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2374. continue;
  2375. }
  2376. $data = substr($line, 6); // 移除 "data: " 前缀
  2377. if ($data === '[DONE]') {
  2378. dLog('deepseek')->info('收到结束标记');
  2379. break 2; // 跳出两层循环
  2380. }
  2381. try {
  2382. $json = json_decode($data, true);
  2383. if (json_last_error() !== JSON_ERROR_NONE) {
  2384. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2385. continue;
  2386. }
  2387. if (isset($json['choices'][0]['delta'])) {
  2388. $delta = $json['choices'][0]['delta'];
  2389. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2390. if (isset($delta['reasoning_content'])) {
  2391. $fullReasoningContent .= $delta['reasoning_content'];
  2392. yield [
  2393. 'type' => 'reasoning',
  2394. 'content' => $delta['reasoning_content'],
  2395. 'full_reasoning' => $fullReasoningContent
  2396. ];
  2397. }
  2398. // 处理最终回答内容
  2399. if (isset($delta['content'])) {
  2400. $fullContent .= $delta['content'];
  2401. yield [
  2402. 'type' => 'content',
  2403. 'content' => $delta['content'],
  2404. ];
  2405. }
  2406. }
  2407. // 获取使用统计信息
  2408. if (isset($json['usage'])) {
  2409. $usage = $json['usage'];
  2410. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2411. }
  2412. } catch (\Exception $e) {
  2413. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2414. continue;
  2415. }
  2416. }
  2417. }
  2418. dLog('deepseek')->info('流式读取完成', [
  2419. 'content_length' => strlen($fullContent),
  2420. 'reasoning_length' => strlen($fullReasoningContent)
  2421. ]);
  2422. yield [
  2423. 'type' => 'done',
  2424. 'full_content' => $fullContent,
  2425. 'full_reasoning' => $fullReasoningContent,
  2426. 'usage' => $usage
  2427. ];
  2428. }
  2429. /**
  2430. * GPT 重试次数(env 可配置,默认 5 次)
  2431. */
  2432. private function gptRetryTimes()
  2433. {
  2434. return (int)env('GPT_RETRY_TIMES', 5);
  2435. }
  2436. /**
  2437. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2438. */
  2439. private function gptRetryInterval()
  2440. {
  2441. return (int)env('GPT_RETRY_INTERVAL', 10);
  2442. }
  2443. /**
  2444. * 判断 GPT 请求异常是否可重试
  2445. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2446. */
  2447. private function isGptRetryableException(\Exception $e)
  2448. {
  2449. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2450. return false;
  2451. }
  2452. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2453. $status = $e->getResponse()->getStatusCode();
  2454. return $status >= 500 || $status == 429;
  2455. }
  2456. return true;
  2457. }
  2458. /**
  2459. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2460. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2461. */
  2462. private function checkGptServiceAvailable()
  2463. {
  2464. $apiKey = env('GPT_54_API_KEY');
  2465. if (empty($apiKey)) {
  2466. return false;
  2467. }
  2468. try {
  2469. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2470. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2471. 'headers' => [
  2472. 'Authorization' => 'Bearer ' . $apiKey,
  2473. 'Content-Type' => 'application/json'
  2474. ]
  2475. ]);
  2476. $status = $response->getStatusCode();
  2477. return $status < 500 && $status != 429;
  2478. } catch (\Exception $e) {
  2479. return false;
  2480. }
  2481. }
  2482. /**
  2483. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2484. * 全部失败抛出友好错误
  2485. */
  2486. private function ensureGptServiceAvailable()
  2487. {
  2488. $maxRetries = $this->gptRetryTimes();
  2489. $interval = $this->gptRetryInterval();
  2490. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2491. if ($this->checkGptServiceAvailable()) {
  2492. return;
  2493. }
  2494. if ($attempt < $maxRetries) {
  2495. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2496. 'retry' => $attempt + 1,
  2497. 'max_retries' => $maxRetries
  2498. ]);
  2499. sleep($interval);
  2500. }
  2501. }
  2502. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2503. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2504. 'max_retries' => $maxRetries,
  2505. 'interval' => $interval
  2506. ]);
  2507. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2508. }
  2509. /**
  2510. * GPT 流式输出处理方法
  2511. *
  2512. * @param array $post_data GPT API请求参数
  2513. * @return \Generator 返回生成器,用于流式输出
  2514. */
  2515. private function gpt54StreamResponse($post_data) {
  2516. $apiKey = env('GPT_54_API_KEY');
  2517. if (empty($apiKey)) {
  2518. Utils::throwError('20003:GPT API Key未配置');
  2519. }
  2520. // 先探活,服务不可用时自动重试
  2521. $this->ensureGptServiceAvailable();
  2522. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2523. $headers = [
  2524. 'Authorization' => 'Bearer ' . $apiKey,
  2525. 'Content-Type' => 'application/json',
  2526. 'Accept' => 'text/event-stream'
  2527. ];
  2528. // 移除 thinking 参数,GPT-5.4 不支持
  2529. if (isset($post_data['thinking'])) {
  2530. unset($post_data['thinking']);
  2531. }
  2532. if (isset($post_data['reasoning_effort'])) {
  2533. unset($post_data['reasoning_effort']);
  2534. }
  2535. // 中转站不识别 response_format,可能被误转成 JSON 输出模式
  2536. if (isset($post_data['response_format'])) {
  2537. unset($post_data['response_format']);
  2538. }
  2539. $post_data['max_completion_tokens'] = 100000;
  2540. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2541. $post_data['stream_options'] = ['include_usage' => true];
  2542. $maxRetries = $this->gptRetryTimes();
  2543. $interval = $this->gptRetryInterval();
  2544. $attempt = 0;
  2545. while (true) {
  2546. $fullContent = '';
  2547. $usage = [];
  2548. $buffer = '';
  2549. $suspectJsonWrap = false;
  2550. $pendingContent = '';
  2551. try {
  2552. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2553. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2554. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2555. 'json' => $post_data,
  2556. 'headers' => $headers,
  2557. 'stream' => true // 启用流式响应
  2558. ]);
  2559. $body = $response->getBody();
  2560. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2561. // 逐行读取流式响应
  2562. while (!$body->eof()) {
  2563. $chunk = $body->read(1024); // 每次读取 1KB
  2564. $buffer .= $chunk;
  2565. // 按行分割
  2566. $lines = explode("\n", $buffer);
  2567. // 保留最后一个不完整的行
  2568. $buffer = array_pop($lines);
  2569. foreach ($lines as $line) {
  2570. $line = trim($line);
  2571. // 跳过空行
  2572. if (empty($line)) {
  2573. continue;
  2574. }
  2575. // 检查是否是 SSE 数据行
  2576. if (strpos($line, 'data: ') !== 0) {
  2577. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2578. continue;
  2579. }
  2580. $data = substr($line, 6); // 移除 "data: " 前缀
  2581. if ($data === '[DONE]') {
  2582. dLog('deepseek')->info('收到结束标记');
  2583. break 2; // 跳出 foreach 和流读取循环
  2584. }
  2585. try {
  2586. $json = json_decode($data, true);
  2587. if (json_last_error() !== JSON_ERROR_NONE) {
  2588. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2589. continue;
  2590. }
  2591. if (isset($json['choices'][0]['delta'])) {
  2592. $delta = $json['choices'][0]['delta'];
  2593. // 处理回答内容
  2594. if (isset($delta['content'])) {
  2595. $fullContent .= $delta['content'];
  2596. $trimmed = ltrim($fullContent);
  2597. if (!$suspectJsonWrap && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2598. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2599. $suspectJsonWrap = true;
  2600. }
  2601. if (!$suspectJsonWrap) {
  2602. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2603. $chunkSize = 256;
  2604. $chunkLength = mb_strlen($delta['content']);
  2605. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2606. yield [
  2607. 'type' => 'content',
  2608. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2609. ];
  2610. }
  2611. } else {
  2612. $pendingContent .= $delta['content'];
  2613. }
  2614. }
  2615. }
  2616. // 获取使用统计信息
  2617. if (isset($json['usage'])) {
  2618. $usage = $json['usage'];
  2619. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2620. }
  2621. } catch (\Exception $e) {
  2622. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2623. continue;
  2624. }
  2625. }
  2626. }
  2627. dLog('deepseek')->info('流式读取完成', [
  2628. 'content_length' => strlen($fullContent)
  2629. ]);
  2630. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  2631. if ($suspectJsonWrap) {
  2632. $decoded = json_decode(trim($fullContent), true);
  2633. $unwrapped = null;
  2634. if (is_array($decoded)) {
  2635. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2636. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2637. $unwrapped = $decoded[$key];
  2638. break;
  2639. }
  2640. }
  2641. }
  2642. if ($unwrapped !== null) {
  2643. $fullContent = $unwrapped;
  2644. $chunkSize = 256;
  2645. $contentLength = mb_strlen($fullContent);
  2646. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  2647. yield [
  2648. 'type' => 'content',
  2649. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  2650. ];
  2651. }
  2652. } elseif ($pendingContent !== '') {
  2653. // 误判:补发暂缓内容,避免内容丢失
  2654. yield [
  2655. 'type' => 'content',
  2656. 'content' => $pendingContent,
  2657. ];
  2658. }
  2659. }
  2660. yield [
  2661. 'type' => 'done',
  2662. 'full_content' => $fullContent,
  2663. 'full_reasoning' => '',
  2664. 'usage' => $usage
  2665. ];
  2666. return;
  2667. } catch (\Exception $e) {
  2668. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2669. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2670. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2671. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2672. throw $e;
  2673. }
  2674. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2675. 'retry' => $attempt + 1,
  2676. 'max_retries' => $maxRetries,
  2677. 'error' => $e->getMessage()
  2678. ]);
  2679. sleep($interval);
  2680. $attempt++;
  2681. }
  2682. }
  2683. }
  2684. // 与推理模型对话
  2685. public function chatWithReasoner($data) {
  2686. $content = getProp($data, 'content');
  2687. $model = getProp($data, 'model', 'r1');
  2688. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2689. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2690. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2691. if ($model == 'r1') {
  2692. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2693. $thinkingMode = 'disabled';
  2694. } else {
  2695. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2696. $thinkingMode = 'disabled';
  2697. }
  2698. // 获取可选情感(根据音色可支持情感选)
  2699. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2700. $emotion_list = [];
  2701. foreach ($timbre_emotion as $emotion) {
  2702. $tmp = explode(',', $emotion);
  2703. $emotion_list = array_merge($emotion_list, $tmp);
  2704. }
  2705. $emotion_list = array_unique($emotion_list);
  2706. $emotion_str = implode('、', $emotion_list);
  2707. // // 获取可选情感
  2708. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2709. // $emotion_str = implode('、', $emotion_list);
  2710. // 是否启用情感
  2711. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2712. if ($enable_emotion) {
  2713. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2714. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2715. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2716. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2717. }else {
  2718. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2719. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2720. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2721. }
  2722. $messages = [
  2723. [
  2724. 'role' => 'system',
  2725. 'content' => $sys_content
  2726. ],
  2727. [
  2728. 'role' => 'user',
  2729. 'content' => $content
  2730. ]
  2731. ];
  2732. $post_data = [
  2733. 'model' => $model,
  2734. 'messages' => $messages,
  2735. // 'max_tokens' => 8192,
  2736. 'temperature' => 1,
  2737. 'frequency_penalty' => 0,
  2738. 'presence_penalty' => 0,
  2739. 'thinking' => ['type' => $thinkingMode],
  2740. 'response_format' => [
  2741. 'type' => 'text'
  2742. ],
  2743. 'stream' => false
  2744. ];
  2745. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2746. // 根据模型类型选择调用方法
  2747. $fullContent = '';
  2748. $usage = [];
  2749. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2750. // DeepSeek 官方模型使用 DeepSeek API
  2751. $chatResult = $this->chatOnly($post_data);
  2752. } else if (in_array($model, $this->gpt_text_models)) {
  2753. // GPT-5.4 模型使用 TokenRouter API
  2754. $chatResult = $this->gpt54ChatOnly($post_data);
  2755. } else {
  2756. // 其他模型使用火山引擎API
  2757. $chatResult = $this->volcEngineChatCompletion($post_data);
  2758. }
  2759. if (is_array($chatResult)) {
  2760. $fullContent = $chatResult['fullContent'];
  2761. $usage = $chatResult['usage'];
  2762. }
  2763. // 处理获取到的剧本数据
  2764. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2765. $result = [
  2766. 'origin_content' => $fullContent,
  2767. 'roles' => getProp($script_content, 'roles'),
  2768. 'words' => getProp($script_content, 'words'),
  2769. ];
  2770. // 仅记录 token 使用明细(不扣积分)
  2771. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  2772. 'model' => $model,
  2773. 'source' => 'chatWithReasoner',
  2774. ], $model);
  2775. return $result;
  2776. }
  2777. public function resetParagraphAudio($data) {
  2778. $bid = getProp($data, 'bid');
  2779. $cid = getProp($data, 'cid');
  2780. $version_id = getProp($data, 'version_id');
  2781. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2782. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2783. 'generate_status' => '待制作',
  2784. 'updated_at' => date('Y-m-d H:i:s')
  2785. ]);
  2786. }
  2787. public function saveParagraphAudio($data) {
  2788. $bid = getProp($data, 'bid');
  2789. $cid = getProp($data, 'cid');
  2790. $version_id = getProp($data, 'version_id');
  2791. $sequence = getProp($data, 'sequence');
  2792. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2793. // 获取所有情感
  2794. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2795. $emotion_list = array_flip($emotion_list);
  2796. // 获取音色支持情感
  2797. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2798. $timbre_emotion = explode(',', $timbre_emotion);
  2799. $emotion = getProp($data, 'emotion');
  2800. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2801. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2802. $list = [
  2803. 'bid' => $bid,
  2804. 'cid' => $cid,
  2805. 'version_id' => $version_id,
  2806. 'sequence' => $sequence,
  2807. 'role' => getProp($data, 'role'),
  2808. 'gender' => getProp($data, 'gender'),
  2809. 'text' => trim(getProp($data, 'text')),
  2810. 'emotion' => $emotion,
  2811. 'emotion_type' => $emotion_type,
  2812. 'voice_type' => getProp($data, 'voice_type'),
  2813. 'voice_name' => getProp($data, 'voice_name'),
  2814. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2815. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2816. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2817. 'pitch' => getProp($data, 'pitch', 0),
  2818. // 'paragraph_audio_url' => '',
  2819. 'generate_status' => '制作中',
  2820. 'error_msg' => '',
  2821. 'updated_at' => date('Y-m-d H:i:s')
  2822. ];
  2823. $continue = false;
  2824. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2825. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2826. $list['generate_status'] = '制作成功';
  2827. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2828. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2829. $continue = true;
  2830. }
  2831. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2832. if ($id) {
  2833. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2834. }else {
  2835. $list['created_at'] = date('Y-m-d H:i:s');
  2836. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2837. $boolen = $id ? true : false;
  2838. }
  2839. // 如果更新成功则加入查询队列
  2840. if ($boolen) {
  2841. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2842. Redis::sadd($redis_key, $id);
  2843. }
  2844. if ($boolen && !$continue) {
  2845. $boolen = false;
  2846. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2847. // 根据ID通过API通知合成音频
  2848. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2849. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2850. $response = $result->getBody()->getContents();
  2851. $response_arr = json_decode($response, true);
  2852. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2853. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2854. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2855. Utils::throwError('20003:通知火山生成段落音频失败');
  2856. }
  2857. $boolen = true;
  2858. }
  2859. return $boolen;
  2860. }
  2861. public function insertAudioEffect($data) {
  2862. $audio_id = getProp($data, 'audio_id');
  2863. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2864. $bid = getProp($chapter_audio, 'bid');
  2865. $version_id = getProp($chapter_audio, 'version_id');
  2866. $cid = getProp($chapter_audio, 'cid');
  2867. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2868. $audio_effect_json = getProp($data, 'audio_effect_json');
  2869. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2870. try {
  2871. DB::beginTransaction();
  2872. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2873. if (!$count) {
  2874. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2875. }else {
  2876. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2877. }
  2878. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2879. 'audio_effect_status' => '添加中',
  2880. 'audio_effect_json' => $audio_effect_json,
  2881. 'updated_at' => date('Y-m-d H:i:s')
  2882. ]);
  2883. if (!$boolen1) {
  2884. DB::rollBack();
  2885. Utils::throwError('20003:更新生成数据失败');
  2886. }
  2887. $id = DB::table('mp_audio_tasks')->insertGetId([
  2888. 'audio_id' => $audio_id,
  2889. 'generate_status' => '执行中',
  2890. 'generate_json' => json_encode([], 256),
  2891. 'bid' => $bid,
  2892. 'book_name' => getProp($chapter_audio, 'book_name'),
  2893. 'version_id' => $version_id,
  2894. 'version_name' => getProp($chapter_audio, 'version_name'),
  2895. 'cid' => $cid,
  2896. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2897. 'task_name' => $task_name,
  2898. 'created_at' => date('Y-m-d H:i:s'),
  2899. 'updated_at' => date('Y-m-d H:i:s')
  2900. ]);
  2901. if (!$id) {
  2902. DB::rollBack();
  2903. Utils::throwError('20003:创建任务失败');
  2904. }
  2905. }catch (\Exception $e) {
  2906. DB::rollBack();
  2907. Utils::throwError('20003:'.$e->getMessage());
  2908. }
  2909. DB::commit();
  2910. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2911. // 根据ID通过API通知合成音频
  2912. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2913. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2914. $response = $result->getBody()->getContents();
  2915. $response_arr = json_decode($response, true);
  2916. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2917. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2918. Log::info('通知火山插入音效失败: '.$error_msg);
  2919. Utils::throwError('20003:通知火山插入音效失败');
  2920. }
  2921. return true;
  2922. }
  2923. public function insertBgm($data) {
  2924. $audio_id = getProp($data, 'audio_id');
  2925. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2926. $bid = getProp($chapter_audio, 'bid');
  2927. $version_id = getProp($chapter_audio, 'version_id');
  2928. $cid = getProp($chapter_audio, 'cid');
  2929. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2930. $bgm_json = getProp($data, 'bgm_json');
  2931. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2932. if (!$bgm_json) {
  2933. $bgm_json = getProp($data, 'audio_effect_json');
  2934. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2935. }
  2936. try {
  2937. DB::beginTransaction();
  2938. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2939. if (!$count) {
  2940. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2941. }else {
  2942. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2943. }
  2944. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2945. 'bgm_status' => '添加中',
  2946. 'bgm_json' => $bgm_json,
  2947. 'updated_at' => date('Y-m-d H:i:s')
  2948. ]);
  2949. if (!$boolen1) {
  2950. DB::rollBack();
  2951. Utils::throwError('20003:更新生成数据失败');
  2952. }
  2953. $id = DB::table('mp_audio_tasks')->insertGetId([
  2954. 'audio_id' => $audio_id,
  2955. 'generate_status' => '执行中',
  2956. 'generate_json' => json_encode([], 256),
  2957. 'bid' => $bid,
  2958. 'book_name' => getProp($chapter_audio, 'book_name'),
  2959. 'version_id' => $version_id,
  2960. 'version_name' => getProp($chapter_audio, 'version_name'),
  2961. 'cid' => $cid,
  2962. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2963. 'task_name' => $task_name,
  2964. 'created_at' => date('Y-m-d H:i:s'),
  2965. 'updated_at' => date('Y-m-d H:i:s')
  2966. ]);
  2967. if (!$id) {
  2968. DB::rollBack();
  2969. Utils::throwError('20003:创建任务失败');
  2970. }
  2971. }catch (\Exception $e) {
  2972. DB::rollBack();
  2973. Utils::throwError('20003:'.$e->getMessage());
  2974. }
  2975. DB::commit();
  2976. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2977. // 根据ID通过API通知合成音频
  2978. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2979. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2980. $response = $result->getBody()->getContents();
  2981. $response_arr = json_decode($response, true);
  2982. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2983. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2984. Log::info('通知火山插入bgm失败: '.$error_msg);
  2985. Utils::throwError('20003:通知火山插入bgm失败');
  2986. }
  2987. return true;
  2988. }
  2989. public function getParagraphAudios($data) {
  2990. $bid = getProp($data, 'bid');
  2991. $cid = getProp($data, 'cid');
  2992. $version_id = getProp($data, 'version_id');
  2993. $sequence = getProp($data, 'sequence');
  2994. // 获取已生成的音频
  2995. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2996. if ($sequence) $query->where('sequence', $sequence);
  2997. $paragraph_audios = $query->orderBy('sequence')->get();
  2998. $result = [];
  2999. foreach($paragraph_audios as $item) {
  3000. $result[] = [
  3001. 'sequence' => getProp($item, 'sequence'),
  3002. 'role' => getProp($item, 'role'),
  3003. 'gender' => getProp($item, 'gender'),
  3004. 'text' => trim(getProp($item, 'text')),
  3005. 'emotion' => getProp($item, 'emotion'),
  3006. 'emotion_type' => getProp($item, 'emotion_type'),
  3007. 'voice_type' => getProp($item, 'voice_type'),
  3008. 'voice_name' => getProp($item, 'voice_name'),
  3009. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3010. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3011. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3012. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3013. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3014. ];
  3015. }
  3016. return $result;
  3017. }
  3018. // 新增合成任务
  3019. public function addGenerateTask($data) {
  3020. $bid = getProp($data, 'bid');
  3021. $cid = getProp($data, 'cid');
  3022. $version_id = getProp($data, 'version_id');
  3023. $generate_json = getProp($data, 'generate_json');
  3024. // 获取已生成的音频
  3025. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3026. $paragraph_list = [];
  3027. foreach($paragraph_audios as $item) {
  3028. $paragraph_list[getProp($item, 'sequence')] = [
  3029. 'role' => getProp($item, 'role'),
  3030. 'gender' => getProp($item, 'gender'),
  3031. 'text' => trim(getProp($item, 'text')),
  3032. 'emotion' => getProp($item, 'emotion'),
  3033. 'emotion_type' => getProp($item, 'emotion_type'),
  3034. 'voice_type' => getProp($item, 'voice_type'),
  3035. 'voice_name' => getProp($item, 'voice_name'),
  3036. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3037. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3038. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3039. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3040. ];
  3041. }
  3042. // 更新角色-音色信息
  3043. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3044. $existed_role_info = json_decode($existed_role_info, true);
  3045. if (!$existed_role_info) $existed_role_info = [];
  3046. // 获取情感信息
  3047. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3048. $emotion_list = array_flip($emotion_list);
  3049. // 获取音色对应情感组
  3050. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3051. $timbre_emotion_list = [];
  3052. foreach($timbre_emotions as $item) {
  3053. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3054. }
  3055. // 构造生成音频的json
  3056. $words = json_decode($generate_json, true);
  3057. // 最终合成前的参数组
  3058. $mp_chapter_paragraph_audios = [];
  3059. $sequence = 1;
  3060. $complete_paragraph_sequences = [];
  3061. foreach($words as &$word) {
  3062. 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:参数格式有误');
  3063. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3064. $role = getProp($word, 'role');
  3065. $word['gender'] = (int)$word['gender'];
  3066. // 判断音色对应情感是否支持,不支持则调整为中性
  3067. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3068. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3069. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3070. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3071. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3072. }else {
  3073. $word['emotion'] = '中性';
  3074. $word['emotion_type'] = 'neutral';
  3075. }
  3076. $existed_role_info[$role] = [
  3077. 'timbre_type' => $word['voice_type'],
  3078. 'timbre_name' => $word['voice_name'],
  3079. 'emotion' => $word['emotion'],
  3080. 'emotion_type' => $word['emotion_type'],
  3081. 'speed_ratio' => $word['speed_ratio'],
  3082. 'loudness_ratio'=> $word['loudness_ratio'],
  3083. 'emotion_scale' => $word['emotion_scale'],
  3084. 'pitch' => $word['pitch']
  3085. ];
  3086. $word['paragraph_audio_url'] = '';
  3087. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3088. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3089. // 如果音频存在并且参数都未改变则使用已生成的音频
  3090. if (getProp($paragraph, 'paragraph_audio_url')) {
  3091. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3092. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3093. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3094. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3095. // {
  3096. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3097. // }
  3098. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3099. }
  3100. $tmp = $word;
  3101. // 组装章节分句音频数据
  3102. // $tmp['sequence'] = getProp($word, 'sequence');
  3103. // $tmp['text'] = getProp($word, 'text');
  3104. // $tmp['emotion'] = getProp($word, 'emotion');
  3105. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3106. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3107. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3108. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3109. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3110. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3111. $tmp['bid'] = $bid;
  3112. $tmp['version_id'] = $version_id;
  3113. $tmp['cid'] = $cid;
  3114. $tmp['sequence'] = $sequence;
  3115. $tmp['created_at'] = date('Y-m-d H:i:s');
  3116. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3117. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3118. $mp_chapter_paragraph_audios[] = $tmp;
  3119. $complete_paragraph_sequences[] = $sequence;
  3120. $sequence++;
  3121. }
  3122. $generate_json = json_encode($words, 256);
  3123. // 判断是否有未生成字幕的段落
  3124. $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();
  3125. if ($no_subtitle_sequences) {
  3126. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3127. }
  3128. try {
  3129. DB::beginTransaction();
  3130. $role_info = json_encode($existed_role_info, 256);
  3131. $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')]);
  3132. if (!$boolen) {
  3133. DB::rollBack();
  3134. Utils::throwError('20003:更新角色信息失败');
  3135. }
  3136. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3137. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3138. if (!$count) {
  3139. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3140. }else {
  3141. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3142. }
  3143. $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')]);
  3144. if (!$boolen1) {
  3145. DB::rollBack();
  3146. Utils::throwError('20003:更新生成数据失败');
  3147. }
  3148. $id = DB::table('mp_audio_tasks')->insertGetId([
  3149. 'audio_id' => getProp($chapter_audio, 'id'),
  3150. 'generate_status' => '执行中',
  3151. 'generate_json' => $generate_json,
  3152. 'bid' => $bid,
  3153. 'book_name' => getProp($chapter_audio, 'book_name'),
  3154. 'version_id' => $version_id,
  3155. 'version_name' => getProp($chapter_audio, 'version_name'),
  3156. 'cid' => $cid,
  3157. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3158. 'task_name' => $task_name,
  3159. 'created_at' => date('Y-m-d H:i:s'),
  3160. 'updated_at' => date('Y-m-d H:i:s')
  3161. ]);
  3162. if (!$id) {
  3163. DB::rollBack();
  3164. Utils::throwError('20003:创建任务失败');
  3165. }
  3166. // 删除不在段落序号范围内的其他数据
  3167. if ($complete_paragraph_sequences) {
  3168. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3169. }
  3170. // // 删除章节分句音频数据并重新插入
  3171. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3172. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3173. // if (!$boolen3) {
  3174. // DB::rollBack();
  3175. // Utils::throwError('20003:更新章节分句音频失败');
  3176. // }
  3177. } catch (\Exception $e) {
  3178. DB::rollBack();
  3179. Utils::throwError('20003:'.$e->getMessage());
  3180. }
  3181. DB::commit();
  3182. // 通知火山生成音频
  3183. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3184. // 根据ID通过API通知合成音频
  3185. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3186. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3187. $response = $result->getBody()->getContents();
  3188. $response_arr = json_decode($response, true);
  3189. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3190. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3191. Log::info('通知火山生成音频失败: '.$error_msg);
  3192. Utils::throwError('20003:通知火山生成音频失败');
  3193. }
  3194. return true;
  3195. }
  3196. public function timbreList($data) {
  3197. $gender = getProp($data, 'gender');
  3198. $timbre_name = getProp($data, 'voice_name');
  3199. $category_id = getProp($data, 'category_id');
  3200. $age_stage = getProp($data, 'age_stage');
  3201. $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');
  3202. if ($gender) {
  3203. $query->where('gender', $gender);
  3204. }
  3205. if ($timbre_name) {
  3206. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3207. }
  3208. if ($category_id) {
  3209. $query->where(function ($query) use ($category_id) {
  3210. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3211. });
  3212. }
  3213. if ($age_stage) {
  3214. $query->where('age_stage', $age_stage);
  3215. }
  3216. $list = $query->get()->map(function ($value) {
  3217. $value = (array)$value;
  3218. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3219. return $value;
  3220. })->toArray();
  3221. return $list;
  3222. }
  3223. // 生成火山临时token
  3224. public function setStsToken() {
  3225. // ************* 配置参数 *************
  3226. $method = 'GET';
  3227. $service = 'sts';
  3228. $host = 'open.volcengineapi.com';
  3229. $region = env('VOLC_REGION');
  3230. $endpoint = 'https://open.volcengineapi.com';
  3231. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3232. $access_key = env('VOLC_AK');
  3233. $secret_key = env('VOLC_SK');
  3234. // 获取缓存中的token,如果没有则请求接口
  3235. $token = Redis::get('volc_sts_token');
  3236. if (!$token) {
  3237. // 查询参数
  3238. $query_parameters = [
  3239. 'Action' => 'AssumeRole',
  3240. 'RoleSessionName' => 'user@zw',
  3241. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3242. 'Version' => '2018-01-01'
  3243. ];
  3244. // 生成URL编码的查询字符串
  3245. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3246. // 获取签名头信息
  3247. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3248. // 构建完整URL
  3249. $request_url = $endpoint . '?' . $request_parameters;
  3250. $client = new Client(['verify' => false]);
  3251. $response = $client->get($request_url, ['headers' => $headers]);
  3252. $response_arr = json_decode($response->getBody()->getContents(), true);
  3253. $result = [
  3254. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3255. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3256. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3257. 'Region' => env('VOLC_REGION'),
  3258. 'Endpoint' => env('VOLC_END_POINT'),
  3259. 'Bucket' => env('VOLC_BUCKET'),
  3260. ];
  3261. // 缓存token
  3262. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3263. return $result;
  3264. } else {
  3265. return json_decode($token, true);
  3266. }
  3267. // $response = $response['Response'];
  3268. // $access_key = $response['Credentials']['AccessKeyId'];
  3269. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3270. // $security_token = $response['Credentials']['SecurityToken'];
  3271. // $expiration = $response['Credentials']['Expiration'];
  3272. // dd($response_arr);
  3273. }
  3274. public function emotionGroups($data) {
  3275. $id = getProp($data, 'group_id');
  3276. $group_name = getProp($data, 'group_name');
  3277. $voice_type = getProp($data, 'voice_type');
  3278. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3279. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3280. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3281. if ($group_name) {
  3282. $query->where('group_name', 'like', "%{$group_name}%");
  3283. }
  3284. if ($id) {
  3285. $query->where('id', $id);
  3286. }
  3287. if ($voice_type) {
  3288. $query->where('voice_type', $voice_type);
  3289. }
  3290. return $query->orderBy('id')->get()->map(function ($value) {
  3291. return (array)$value;
  3292. })->toArray();
  3293. }
  3294. private function sign($key, $msg) {
  3295. return hash_hmac('sha256', $msg, $key, true);
  3296. }
  3297. // 生成签名密钥
  3298. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3299. $kDate = $this->sign($key, $dateStamp);
  3300. $kRegion = $this->sign($kDate, $regionName);
  3301. $kService = $this->sign($kRegion, $serviceName);
  3302. $kSigning = $this->sign($kService, 'request');
  3303. return $kSigning;
  3304. }
  3305. // 获取签名头信息
  3306. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3307. $contenttype = 'application/x-www-form-urlencoded';
  3308. $accept = 'application/json';
  3309. // 获取当前UTC时间
  3310. $t = new DateTime('now', new DateTimeZone('UTC'));
  3311. $xdate = $t->format('Ymd\THis\Z');
  3312. $datestamp = $t->format('Ymd');
  3313. // 1. 拼接规范请求串
  3314. $canonical_uri = '/';
  3315. $canonical_querystring = $request_parameters;
  3316. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3317. $signed_headers = 'content-type;host;x-date';
  3318. // 空请求体的SHA256哈希
  3319. $payload_hash = hash('sha256', '');
  3320. $canonical_request = implode("\n", [
  3321. $method,
  3322. $canonical_uri,
  3323. $canonical_querystring,
  3324. $canonical_headers,
  3325. $signed_headers,
  3326. $payload_hash
  3327. ]);
  3328. // 2. 拼接待签名字符串
  3329. $algorithm = 'HMAC-SHA256';
  3330. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3331. $hashed_canonical_request = hash('sha256', $canonical_request);
  3332. $string_to_sign = implode("\n", [
  3333. $algorithm,
  3334. $xdate,
  3335. $credential_scope,
  3336. $hashed_canonical_request
  3337. ]);
  3338. // 3. 计算签名
  3339. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3340. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3341. // 4. 添加签名到请求头
  3342. $authorization_header = sprintf(
  3343. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3344. $algorithm,
  3345. $access_key,
  3346. $credential_scope,
  3347. $signed_headers,
  3348. $signature
  3349. );
  3350. return [
  3351. 'Accept' => $accept,
  3352. 'Content-Type' => $contenttype,
  3353. 'X-Date' => $xdate,
  3354. 'Authorization' => $authorization_header
  3355. ];
  3356. }
  3357. // 文字合成语音(火山引擎)
  3358. public function tts($data) {
  3359. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3360. $headers = [
  3361. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3362. 'Content-Type' => 'application/json; charset=UTF-8'
  3363. ];
  3364. $post_data = [
  3365. 'app' => [
  3366. 'appid' => env('VOLC_APPID'),
  3367. 'token' => env('VOLC_TOKEN'),
  3368. 'cluster' => 'volcano_tts'
  3369. ],
  3370. 'user' => [
  3371. 'uid' => 'mp_audio'
  3372. ],
  3373. // 'audio' => [
  3374. // 'voice_type' =>
  3375. // ],
  3376. ];
  3377. }
  3378. public function scriptList($data) {
  3379. $uid = Site::getUid();
  3380. $script_id = getProp($data, 'script_id');
  3381. $script_name = getProp($data, 'script_name');
  3382. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3383. if ($script_id) {
  3384. $query->where('id', $script_id);
  3385. }
  3386. if ($script_name) {
  3387. $query->where('script_name', 'like', "%{$script_name}%");
  3388. }
  3389. return $query->orderBy('created_at', 'desc')->paginate(12);
  3390. }
  3391. public function scripts($data) {
  3392. $uid = Site::getUid();
  3393. $script_id = getProp($data, 'script_id');
  3394. $script_name = getProp($data, 'script_name');
  3395. $is_products = getProp($data, 'is_products');
  3396. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3397. if ($script_id) {
  3398. $query->where('id', $script_id);
  3399. }
  3400. if ($is_products !== '') {
  3401. $query->where('is_products', $is_products);
  3402. }
  3403. if ($script_name) {
  3404. $query->where('script_name', 'like', "%{$script_name}%");
  3405. }
  3406. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3407. return (array)$value;
  3408. })->toArray();
  3409. }
  3410. public function scriptInfo($data) {
  3411. $uid = Site::getUid();
  3412. $script_id = getProp($data, 'script_id');
  3413. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3414. // ->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();
  3415. ->selectRaw('id as script_id, script_name')->first();
  3416. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3417. $script = (array)$script;
  3418. // 获取分集组信息
  3419. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3420. ->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')
  3421. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3422. $value = (array)$value;
  3423. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3424. return (array)$value;
  3425. })->toArray();
  3426. $script['group'] = $groups;
  3427. return $script;
  3428. }
  3429. public function createScript($data) {
  3430. $script_name = getProp($data, 'script_name');
  3431. $uid = Site::getUid(); // 获取当前用户ID
  3432. $cpid = Site::getCpid(); // 获取当前公司组ID
  3433. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3434. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3435. $script_name .= '_'.date('YmdHis');
  3436. }
  3437. return DB::table('mp_scripts')->insertGetId([
  3438. 'script_name' => $script_name,
  3439. 'user_id' => $uid,
  3440. 'cpid' => $cpid,
  3441. 'created_at' => date('Y-m-d H:i:s'),
  3442. 'updated_at' => date('Y-m-d H:i:s')
  3443. ]);
  3444. }
  3445. public function editScript($data) {
  3446. $script_id = getProp($data, 'script_id');
  3447. $script_name = getProp($data, 'script_name');
  3448. $uid = Site::getUid(); // 获取当前用户ID
  3449. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3450. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3451. if ($id && (int)$id !== (int)$script_id) {
  3452. $script_name .= '_'.date('YmdHis');
  3453. }
  3454. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3455. 'script_name' => $script_name,
  3456. 'updated_at' => date('Y-m-d H:i:s')
  3457. ]);
  3458. }
  3459. public function delScript($data) {
  3460. $script_id = getProp($data, 'script_id');
  3461. $uid = Site::getUid(); // 获取当前用户ID
  3462. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3463. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3464. 'is_deleted' => 1,
  3465. 'updated_at' => date('Y-m-d H:i:s')
  3466. ]);
  3467. }
  3468. public function createEpisode($data) {
  3469. $script_id = getProp($data, 'script_id');
  3470. $group_name = getProp($data, 'group_name');
  3471. $remark = getProp($data, 'remark');
  3472. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3473. $uid = Site::getUid(); // 获取当前用户ID
  3474. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3475. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3476. $group_name .= '_'.date('YmdHis');
  3477. }
  3478. return DB::table('mp_script_episode_group')->insertGetId([
  3479. 'script_id' => $script_id,
  3480. 'group_name' => $group_name,
  3481. 'user_id' => $uid,
  3482. 'remark' => $remark,
  3483. 'created_at' => date('Y-m-d H:i:s'),
  3484. 'updated_at' => date('Y-m-d H:i:s')
  3485. ]);
  3486. }
  3487. public function editEpisode($data) {
  3488. $group_id = getProp($data, 'group_id');
  3489. $start_episode_number = getProp($data, 'start_episode_number');
  3490. $end_episode_number = getProp($data, 'end_episode_number');
  3491. $group_name = getProp($data, 'group_name');
  3492. $uid = Site::getUid(); // 获取当前用户ID
  3493. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3494. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3495. if ($id && (int)$id !== (int)$group_id) {
  3496. $group_name .= '_'.date('YmdHis');
  3497. }
  3498. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3499. 'group_name' => $group_name,
  3500. 'start_episode_number' => $start_episode_number,
  3501. 'end_episode_number' => $end_episode_number,
  3502. 'updated_at' => date('Y-m-d H:i:s')
  3503. ]);
  3504. }
  3505. public function delEpisode($data) {
  3506. $group_id = getProp($data, 'group_id');
  3507. $uid = Site::getUid(); // 获取当前用户ID
  3508. if (!$group_id) Utils::throwError('20003:请选择分集');
  3509. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3510. 'is_deleted' => 1,
  3511. 'updated_at' => date('Y-m-d H:i:s')
  3512. ]);
  3513. }
  3514. /**
  3515. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3516. *
  3517. * @param array $data 包含以下参数:
  3518. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3519. * - question: 用户问题(可选)
  3520. * - model: 使用的模型(r1 或 v3,默认 v3)
  3521. * @return \Generator 返回生成器,用于流式输出
  3522. */
  3523. public function generateEpisodes($data) {
  3524. $script_id = getProp($data, 'script_id');
  3525. $group_id = getProp($data, 'group_id');
  3526. // $file = getProp($data, 'file');
  3527. $file = '';
  3528. $content = getProp($data, 'content', '');
  3529. // $bid = getProp($data, 'bid', 0);
  3530. $bid = 0;
  3531. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3532. if (!$group) {
  3533. Utils::throwError('20003:剧本分集不存在');
  3534. }
  3535. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3536. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3537. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3538. $prompt = getProp($data, 'prompt');
  3539. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3540. $model = getProp($data, 'model');
  3541. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3542. Utils::throwError('20003:该模型不存在!');
  3543. }
  3544. // 检查是否存在重叠的剧集序号范围
  3545. $exists_groups = DB::table('mp_script_episode_group')
  3546. ->where('script_id', $script_id)
  3547. ->where('id', '<>', $group_id) // 排除当前组
  3548. ->where('is_deleted', 0)
  3549. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3550. // 检查新范围是否与现有范围重叠
  3551. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3552. // 新范围的开始在现有范围内
  3553. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3554. ->where('end_episode_number', '>=', $start_episode_sequence);
  3555. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3556. // 新范围的结束在现有范围内
  3557. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3558. ->where('end_episode_number', '>=', $end_episode_sequence);
  3559. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3560. // 新范围完全包含现有范围
  3561. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3562. ->where('end_episode_number', '<=', $end_episode_sequence);
  3563. });
  3564. })
  3565. ->select('start_episode_number', 'end_episode_number')
  3566. ->get();
  3567. if ($exists_groups->isNotEmpty()) {
  3568. $conflict_ranges = [];
  3569. foreach ($exists_groups as $group) {
  3570. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3571. }
  3572. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3573. }
  3574. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3575. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3576. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3577. if ($model === 'deepseek-chat') {
  3578. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3579. $model = 'deepseek-v4-flash';
  3580. $thinkingMode = 'disabled';
  3581. } elseif ($model === 'deepseek-reasoner') {
  3582. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3583. $model = 'deepseek-v4-flash';
  3584. $thinkingMode = 'enabled';
  3585. }
  3586. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3587. if (!$script) {
  3588. Utils::throwError('20003:剧本不存在');
  3589. }
  3590. $content = getProp($group, 'content');
  3591. if (!$file && !$content && !$bid) {
  3592. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3593. }
  3594. // 提取文件内容
  3595. if ($file) {
  3596. $content = $this->extractFileContent($file);
  3597. if (!$content) {
  3598. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3599. }
  3600. } elseif ($bid) {
  3601. $content = $this->getContentByBid($bid);
  3602. if (!$content) {
  3603. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3604. }
  3605. } elseif ($content) {
  3606. $content = filterContent($content);
  3607. } elseif ($prompt) {
  3608. $content = filterContent($prompt);
  3609. } else {
  3610. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3611. }
  3612. // 构建消息
  3613. $messages = [
  3614. $this->sys_message,
  3615. [
  3616. 'role' => 'user',
  3617. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3618. ]
  3619. ];
  3620. $post_data = [
  3621. 'model' => $model,
  3622. 'messages' => $messages,
  3623. // 'max_tokens' => 8192,
  3624. 'temperature' => 0.7,
  3625. 'frequency_penalty' => 0,
  3626. 'presence_penalty' => 0,
  3627. 'thinking' => ['type' => $thinkingMode],
  3628. 'response_format' => ['type' => 'text'],
  3629. 'stream' => true
  3630. ];
  3631. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3632. // 根据模型类型选择调用方法
  3633. $fullContent = '';
  3634. $fullReasoningContent = '';
  3635. $usage = [];
  3636. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3637. // DeepSeek 官方模型使用 DeepSeek API
  3638. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3639. } else if (in_array($model, $this->gpt_text_models)) {
  3640. // GPT-5.4 模型使用 TokenRouter API
  3641. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3642. } else if (in_array($model, $this->gemini_text_models)) {
  3643. // Gemini 模型使用 Gemini API
  3644. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3645. } else {
  3646. // 其他模型使用火山引擎API
  3647. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3648. }
  3649. // 处理流式输出
  3650. foreach ($streamGenerator as $chunk) {
  3651. if (isset($chunk['type'])) {
  3652. if ($chunk['type'] === 'done') {
  3653. // 最终结果
  3654. $fullContent = $chunk['full_content'];
  3655. $fullReasoningContent = $chunk['full_reasoning'];
  3656. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3657. } else {
  3658. // 逐块yield数据
  3659. yield $chunk;
  3660. }
  3661. }
  3662. }
  3663. dLog('deepseek')->info('完整内容: '.$fullContent);
  3664. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3665. // 处理完整内容并返回最终结果
  3666. $script_arr = [];
  3667. if ($fullContent) {
  3668. $script_arr = extractScriptContent($fullContent);
  3669. }
  3670. logDB('deepseek', 'info', '解析内容', $script_arr);
  3671. if (!$script_arr['episodes']) {
  3672. Utils::throwError('20003:未生成剧本相关信息');
  3673. // yield [
  3674. // 'type' => 'done',
  3675. // 'script' => $script_arr,
  3676. // 'msg' => '未生成剧本相关信息',
  3677. // 'answer' => $fullContent,
  3678. // 'reasoning' => $fullReasoningContent,
  3679. // 'usage' => $usage
  3680. // ];
  3681. // return ;
  3682. }
  3683. try {
  3684. DB::beginTransaction();
  3685. // // 返回前保存剧本内容
  3686. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3687. // 'content' => $content,
  3688. // 'updated_at' => date('Y-m-d H:i:s')
  3689. // ]);
  3690. // if (!$boolen) {
  3691. // Utils::throwError('20003:保存剧本内容失败');
  3692. // }
  3693. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3694. // 'start_episode_number' => $start_episode_sequence,
  3695. // 'end_episode_number' => $end_episode_sequence,
  3696. // 'updated_at' => date('Y-m-d H:i:s')
  3697. // ]);
  3698. // if (!$boolen1) {
  3699. // Utils::throwError('20003:保存分集失败');
  3700. // }
  3701. $episode_content = '';
  3702. $episodes = [];
  3703. foreach ($script_arr['episodes'] as $item) {
  3704. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3705. // $episodes[] = [
  3706. // 'script_id' => $script_id,
  3707. // 'episode_number' => $item['episode_number'],
  3708. // 'episode_name' => $item['episode_name'],
  3709. // 'episode_content' => $item['episode_content'],
  3710. // 'created_at' => date('Y-m-d H:i:s'),
  3711. // 'updated_at' => date('Y-m-d H:i:s'),
  3712. // ];
  3713. }
  3714. if ($episode_content) {
  3715. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3716. 'episode_content' => $episode_content,
  3717. 'updated_at' => date('Y-m-d H:i:s')
  3718. ]);
  3719. if (!$boolen2) {
  3720. Utils::throwError('20003:保存分集内容失败');
  3721. }
  3722. }else {
  3723. Utils::throwError('20003:分集剧本解析失败');
  3724. }
  3725. }catch (\Exception $e) {
  3726. DB::rollBack();
  3727. Utils::throwError('20003:'.$e->getMessage());
  3728. }
  3729. DB::commit();
  3730. // 仅记录 token 使用明细(不扣积分)
  3731. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3732. 'model' => $model,
  3733. 'script_id' => $script_id,
  3734. 'group_id' => $group_id,
  3735. 'source' => 'generateEpisodes',
  3736. ], $model);
  3737. yield [
  3738. 'type' => 'done',
  3739. 'script' => $script_arr,
  3740. 'episode_content' => $episode_content,
  3741. 'answer' => $fullContent,
  3742. 'reasoning' => $fullReasoningContent,
  3743. 'usage' => $usage
  3744. ];
  3745. }
  3746. public function chatWithFileStream($data) {
  3747. $script_id = getProp($data, 'script_id');
  3748. $group_id = getProp($data, 'group_id');
  3749. $file = getProp($data, 'file');
  3750. $content = getProp($data, 'content', '');
  3751. $bid = getProp($data, 'bid', 0);
  3752. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3753. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3754. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3755. $prompt = getProp($data, 'prompt');
  3756. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3757. if (!empty($prompt)) {
  3758. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3759. }
  3760. $question = getProp($data, 'question', $baseQuestion);
  3761. $model = getProp($data, 'model');
  3762. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3763. Utils::throwError('20003:该模型不存在!');
  3764. }
  3765. // 检查是否存在重叠的剧集序号范围
  3766. $exists_groups = DB::table('mp_script_episode_group')
  3767. ->where('script_id', $script_id)
  3768. ->where('id', '<>', $group_id)
  3769. ->where('is_deleted', 0)
  3770. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3771. // 检查新范围是否与现有范围重叠
  3772. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3773. // 新范围的开始在现有范围内
  3774. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3775. ->where('end_episode_number', '>=', $start_episode_sequence);
  3776. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3777. // 新范围的结束在现有范围内
  3778. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3779. ->where('end_episode_number', '>=', $end_episode_sequence);
  3780. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3781. // 新范围完全包含现有范围
  3782. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3783. ->where('end_episode_number', '<=', $end_episode_sequence);
  3784. });
  3785. })
  3786. ->select('start_episode_number', 'end_episode_number')
  3787. ->get();
  3788. if ($exists_groups->isNotEmpty()) {
  3789. $conflict_ranges = [];
  3790. foreach ($exists_groups as $group) {
  3791. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3792. }
  3793. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3794. }
  3795. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3796. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3797. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3798. if ($model === 'deepseek-chat') {
  3799. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3800. $model = 'deepseek-v4-flash';
  3801. $thinkingMode = 'disabled';
  3802. } elseif ($model === 'deepseek-reasoner') {
  3803. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3804. $model = 'deepseek-v4-flash';
  3805. $thinkingMode = 'enabled';
  3806. }
  3807. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3808. if (!$script) {
  3809. Utils::throwError('20003:剧本不存在');
  3810. }
  3811. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3812. if (!$group) {
  3813. Utils::throwError('20003:剧本分集不存在');
  3814. }
  3815. if (!$file && !$content && !$bid) {
  3816. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3817. }
  3818. // 提取文件内容
  3819. if ($file) {
  3820. $content = $this->extractFileContent($file);
  3821. if (!$content) {
  3822. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3823. }
  3824. } elseif ($bid) {
  3825. $content = $this->getContentByBid($bid);
  3826. if (!$content) {
  3827. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3828. }
  3829. } elseif ($content) {
  3830. $content = filterContent($content);
  3831. } elseif ($prompt) {
  3832. $content = filterContent($prompt);
  3833. } else {
  3834. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3835. }
  3836. // 构建消息
  3837. $messages = [
  3838. [
  3839. 'role' => 'system',
  3840. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3841. 强制要求:\n
  3842. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3843. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3844. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3845. 普通要求:\n
  3846. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3847. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3848. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3849. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3850. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3851. 示例如下:\n
  3852. ###剧本名:西昆仑
  3853. ###故事梗概
  3854. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3855. ###剧本亮点
  3856. 亮点1:绝境奇药,生死一线
  3857. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3858. 亮点2:结拜兄妹,化解尴尬
  3859. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3860. 亮点3:纤发夺命,情愫暗涌
  3861. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3862. ###人物关系
  3863. 阿雪与梁萧之间存在兄妹之情。
  3864. ###核心矛盾
  3865. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3866. ###主体列表
  3867. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3868. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3869. 阴阳球:天地异宝,能化生精气,救人于危难。
  3870. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3871. ###美术风格
  3872. 基础画风风格词:厚涂古风
  3873. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3874. ###场景列表
  3875. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3876. [
  3877. 'role' => 'user',
  3878. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3879. ]
  3880. ];
  3881. $post_data = [
  3882. 'model' => $model,
  3883. 'messages' => $messages,
  3884. // 'max_tokens' => 8192,
  3885. 'temperature' => 0.7,
  3886. 'frequency_penalty' => 0,
  3887. 'presence_penalty' => 0,
  3888. 'thinking' => ['type' => $thinkingMode],
  3889. 'response_format' => ['type' => 'text'],
  3890. 'stream' => true
  3891. ];
  3892. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3893. // 根据模型类型选择调用方法
  3894. $fullContent = '';
  3895. $fullReasoningContent = '';
  3896. $usage = [];
  3897. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3898. // DeepSeek 官方模型使用 DeepSeek API
  3899. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3900. } else if (in_array($model, $this->gpt_text_models)) {
  3901. // GPT-5.4 模型使用 TokenRouter API
  3902. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3903. } else if (in_array($model, $this->gemini_text_models)) {
  3904. // Gemini 模型使用 Gemini API
  3905. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3906. } else {
  3907. // 其他模型使用火山引擎API
  3908. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3909. }
  3910. // 处理流式输出
  3911. foreach ($streamGenerator as $chunk) {
  3912. if (isset($chunk['type'])) {
  3913. if ($chunk['type'] === 'done') {
  3914. // 最终结果
  3915. $fullContent = $chunk['full_content'];
  3916. $fullReasoningContent = $chunk['full_reasoning'];
  3917. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3918. } else {
  3919. // 逐块yield数据
  3920. yield $chunk;
  3921. }
  3922. }
  3923. }
  3924. dLog('deepseek')->info('完整内容: '.$fullContent);
  3925. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3926. // 处理完整内容并返回最终结果
  3927. $script_arr = [];
  3928. if ($fullContent) {
  3929. $script_arr = extractScriptContent($fullContent);
  3930. }
  3931. logDB('deepseek', 'info', '解析内容', $script_arr);
  3932. if (!$script_arr['roles']) {
  3933. Utils::throwError('20003:未生成剧本相关信息');
  3934. // yield [
  3935. // 'type' => 'done',
  3936. // 'script' => $script_arr,
  3937. // 'msg' => '未生成剧本相关信息',
  3938. // 'answer' => $fullContent,
  3939. // 'reasoning' => $fullReasoningContent,
  3940. // 'usage' => $usage
  3941. // ];
  3942. }
  3943. try {
  3944. DB::beginTransaction();
  3945. // // 返回前保存剧本内容
  3946. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3947. // 'content' => $content,
  3948. // 'status' => '解析完成',
  3949. // 'updated_at' => date('Y-m-d H:i:s')
  3950. // ]);
  3951. // if (!$boolen) {
  3952. // Utils::throwError('20003:保存剧本内容失败');
  3953. // }
  3954. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3955. 'start_episode_number' => $start_episode_sequence,
  3956. 'end_episode_number' => $end_episode_sequence,
  3957. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3958. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3959. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3960. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3961. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3962. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3963. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3964. 'status' => '解析完成',
  3965. 'content' => $content,
  3966. 'updated_at' => date('Y-m-d H:i:s')
  3967. ]);
  3968. if (!$boolen1) {
  3969. Utils::throwError('20003:保存分集失败');
  3970. }
  3971. // $episodes = [];
  3972. // foreach ($script_arr['episodes'] as $item) {
  3973. // $episodes[] = [
  3974. // 'script_id' => $script_id,
  3975. // 'episode_number' => $item['episode_number'],
  3976. // 'episode_name' => $item['episode_name'],
  3977. // 'episode_content' => $item['episode_content'],
  3978. // 'created_at' => date('Y-m-d H:i:s'),
  3979. // 'updated_at' => date('Y-m-d H:i:s'),
  3980. // ];
  3981. // }
  3982. // if ($episodes) {
  3983. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3984. // if (!$boolen2) {
  3985. // Utils::throwError('20003:保存分集内容失败');
  3986. // }
  3987. // }else {
  3988. // Utils::throwError('20003:分集剧本解析失败');
  3989. // }
  3990. }catch (\Exception $e) {
  3991. DB::rollBack();
  3992. Utils::throwError('20003:'.$e->getMessage());
  3993. }
  3994. DB::commit();
  3995. // 仅记录 token 使用明细(不扣积分)
  3996. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3997. 'model' => $model,
  3998. 'script_id' => $script_id,
  3999. 'group_id' => $group_id,
  4000. 'source' => 'chatWithFileStream',
  4001. ], $model);
  4002. yield [
  4003. 'type' => 'done',
  4004. 'script' => $script_arr,
  4005. 'answer' => $fullContent,
  4006. 'reasoning' => $fullReasoningContent,
  4007. 'usage' => $usage
  4008. ];
  4009. }
  4010. /**
  4011. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4012. *
  4013. * @param array $data 包含以下参数:
  4014. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4015. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4016. * - model: 使用的模型(r1 或 v3,默认 v3)
  4017. * @return array
  4018. */
  4019. public function chatWithFile($data) {
  4020. $script_id = getProp($data, 'script_id');
  4021. $file = getProp($data, 'file');
  4022. $content = getProp($data, 'content', '');
  4023. $bid = getProp($data, 'bid', 0);
  4024. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4025. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4026. $prompt = getProp($data, 'prompt');
  4027. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4028. if (!empty($prompt)) {
  4029. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4030. }
  4031. $question = getProp($data, 'question', $baseQuestion);
  4032. // 处理文本模型
  4033. $model = getProp($data, 'model');
  4034. if (!$model) {
  4035. // 用户没有输入,使用默认值
  4036. $model = 'doubao-seed-2-0-mini-260215';
  4037. }
  4038. // 验证模型是否在可用模型表中
  4039. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4040. $model = 'doubao-seed-2-0-mini-260215';
  4041. }
  4042. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4043. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4044. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4045. if ($model === 'deepseek-chat') {
  4046. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4047. $model = 'deepseek-v4-flash';
  4048. $thinkingMode = 'disabled';
  4049. } elseif ($model === 'deepseek-reasoner') {
  4050. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4051. $model = 'deepseek-v4-flash';
  4052. $thinkingMode = 'enabled';
  4053. }
  4054. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4055. if (!$script) {
  4056. Utils::throwError('20003:剧本不存在');
  4057. }
  4058. if (!$file && !$content && !$bid) {
  4059. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4060. }
  4061. // 提取文件内容
  4062. if ($file) {
  4063. $content = $this->extractFileContent($file);
  4064. if (!$content) {
  4065. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4066. }
  4067. } elseif ($bid) {
  4068. $content = $this->getContentByBid($bid);
  4069. if (!$content) {
  4070. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4071. }
  4072. } elseif ($content) {
  4073. $content = filterContent($content);
  4074. } elseif ($prompt) {
  4075. $content = filterContent($prompt);
  4076. } else {
  4077. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4078. }
  4079. // 构建消息
  4080. $messages = [
  4081. $this->sys_message,
  4082. [
  4083. 'role' => 'user',
  4084. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4085. ]
  4086. ];
  4087. $post_data = [
  4088. 'model' => $model,
  4089. 'messages' => $messages,
  4090. // 'max_tokens' => 8192,
  4091. 'temperature' => 0.7,
  4092. 'frequency_penalty' => 0,
  4093. 'presence_penalty' => 0,
  4094. 'thinking' => ['type' => $thinkingMode],
  4095. 'response_format' => ['type' => 'text'],
  4096. 'stream' => false
  4097. ];
  4098. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4099. // 根据模型类型选择调用方法
  4100. $fullContent = '';
  4101. $usage = [];
  4102. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4103. // DeepSeek 官方模型使用 DeepSeek API
  4104. $chatResult = $this->chatOnly($post_data);
  4105. } else if (in_array($model, $this->gpt_text_models)) {
  4106. // GPT-5.4 模型使用 TokenRouter API
  4107. $chatResult = $this->gpt54ChatOnly($post_data);
  4108. } else {
  4109. // 其他模型使用火山引擎API
  4110. $chatResult = $this->volcEngineChatCompletion($post_data);
  4111. }
  4112. if (is_array($chatResult)) {
  4113. $fullContent = $chatResult['fullContent'];
  4114. $usage = $chatResult['usage'];
  4115. }
  4116. $script_arr = [];
  4117. // 处理结果
  4118. if ($fullContent) {
  4119. $script_arr = extractScriptContent($fullContent);
  4120. }
  4121. // 返回前保存剧本内容
  4122. DB::table('mp_scripts')->where('id', $script_id)->update([
  4123. 'content' => $content,
  4124. 'updated_at' => date('Y-m-d H:i:s')
  4125. ]);
  4126. // 仅记录 token 使用明细(不扣积分)
  4127. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4128. 'model' => $model,
  4129. 'script_id' => $script_id,
  4130. 'source' => 'chatWithFile',
  4131. ], $model);
  4132. return [
  4133. 'script' => $script_arr,
  4134. 'answer' => $fullContent,
  4135. 'usage' => $usage
  4136. ];
  4137. }
  4138. public function getEpisodeContent($data) {
  4139. $group_id = getProp($data, 'group_id');
  4140. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4141. }
  4142. public function saveEpisodeContent($data) {
  4143. $script_id = getProp($data, 'script_id');
  4144. $group_id = getProp($data, 'group_id');
  4145. $start_episode_sequence = getProp($data, 'start_episode_number');
  4146. $end_episode_sequence = getProp($data, 'end_episode_number');
  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. $episode_content = getProp($data, 'episode_content');
  4178. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4179. 'content' => $episode_content,
  4180. 'start_episode_number' => $start_episode_sequence,
  4181. 'end_episode_number' => $end_episode_sequence,
  4182. 'updated_at' => date('Y-m-d H:i:s')
  4183. ]);
  4184. $script_arr =getProp($data, 'script', []);
  4185. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4186. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4187. $script_id = getProp($data, 'script_id');
  4188. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4189. try {
  4190. DB::beginTransaction();
  4191. $update_data = [
  4192. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4193. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4194. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4195. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4196. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4197. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4198. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4199. 'status' => 3,
  4200. 'start_episode_sequence' => $start_episode_sequence,
  4201. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4202. 'episode_num' => count($script_arr['episodes']),
  4203. 'updated_at' => date('Y-m-d H:i:s')
  4204. ];
  4205. // 保存剧本内容
  4206. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4207. if (!$boolen) {
  4208. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4209. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4210. Utils::throwError('20003:剧本内容保存失败');
  4211. }
  4212. // 保存分集内容
  4213. // 删除历史分集内容
  4214. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4215. $episodes = [];
  4216. $sequence = 1;
  4217. foreach ($script_arr['episodes'] as $episode) {
  4218. $segment_number = 1;
  4219. foreach($episode['segments'] as $segment) {
  4220. $episodes[] = [
  4221. 'script_id' => $script_id,
  4222. 'episode_number' => $episode['episode_number'],
  4223. 'title' => $episode['title'],
  4224. // 'content' => $episode['content'],
  4225. 'content' => '',
  4226. 'segment_number' => $segment_number,
  4227. 'segment_content' => $segment['segment_content'],
  4228. 'sequence' => $sequence,
  4229. 'created_at' => date('Y-m-d H:i:s'),
  4230. 'updated_at' => date('Y-m-d H:i:s')
  4231. ];
  4232. $sequence++;
  4233. $segment_number++;
  4234. }
  4235. }
  4236. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4237. if (!$boolen2) {
  4238. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4239. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4240. Utils::throwError('20003:分集内容保存失败');
  4241. }
  4242. } catch (\Exception $e) {
  4243. DB::rollBack();
  4244. Utils::throwError('20003:'.$e->getMessage());
  4245. }
  4246. DB::commit();
  4247. return true;
  4248. }
  4249. public function getBookContent($data) {
  4250. $bid = getProp($data, 'bid');
  4251. $start_sequence = getProp($data, 'start_sequence');
  4252. $end_sequence = getProp($data, 'end_sequence');
  4253. $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])
  4254. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4255. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4256. return $return_content;
  4257. }
  4258. public function exportScript($data) {
  4259. $filename = getProp($data, 'filename');
  4260. $script_id = getProp($data, 'script_id');
  4261. $group_id = getProp($data, 'group_id');
  4262. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4263. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4264. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4265. $script = (array)$script;
  4266. // 获取分集组信息
  4267. if ($group_id) {
  4268. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4269. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4270. ->get()->map(function($value) {
  4271. return (array)$value;
  4272. })->toArray();
  4273. }else {
  4274. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4275. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4276. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4277. return (array)$value;
  4278. })->toArray();
  4279. }
  4280. if (!$groups) Utils::throwError('20003:分集不存在');
  4281. $script['group'] = $groups;
  4282. $export_type = getProp($data, 'export_type', 'txt');
  4283. // 生成文件名
  4284. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4285. // 根据导出类型生成不同格式的文件
  4286. switch ($export_type) {
  4287. case 'txt':
  4288. return $this->exportScriptAsTxt($script, $filename);
  4289. case 'pdf':
  4290. return $this->exportScriptAsPdf($script, $filename);
  4291. default:
  4292. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4293. }
  4294. }
  4295. /**
  4296. * 导出剧本为TXT格式
  4297. */
  4298. private function exportScriptAsTxt($script, $filename) {
  4299. // 构建TXT内容
  4300. $content = $this->buildScriptContent($script);
  4301. // 设置响应头,直接下载
  4302. header('Content-Type: text/plain; charset=utf-8');
  4303. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4304. header('Content-Length: ' . strlen($content));
  4305. // 输出内容并结束
  4306. echo $content;
  4307. exit();
  4308. }
  4309. /**
  4310. * 导出剧本为PDF格式
  4311. */
  4312. private function exportScriptAsPdf($script, $filename) {
  4313. // 使用HTML转PDF的方式来更好地支持中文
  4314. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4315. // 创建PDF实例
  4316. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4317. // 设置文档信息
  4318. $pdf->SetCreator('剧本导出系统');
  4319. $pdf->SetAuthor('系统');
  4320. $pdf->SetTitle($script['script_name']);
  4321. $pdf->SetSubject('剧本导出');
  4322. // 设置边距
  4323. $pdf->SetMargins(15, 15, 15);
  4324. $pdf->SetAutoPageBreak(TRUE, 15);
  4325. // 添加页面
  4326. $pdf->AddPage();
  4327. // 注册并使用 simsun.ttf 字体
  4328. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4329. // 使用HTML内容生成PDF
  4330. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4331. // 直接输出PDF文件供下载
  4332. header('Content-Type: application/pdf');
  4333. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4334. // 直接输出PDF内容
  4335. $pdf->Output($filename . '.pdf', 'D');
  4336. exit();
  4337. }
  4338. /**
  4339. * 构建用于PDF的HTML内容
  4340. */
  4341. private function buildScriptHtmlForPdf($script) {
  4342. $html = '<style>
  4343. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4344. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4345. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4346. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4347. .info { margin-bottom: 8px; }
  4348. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4349. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4350. .segment { margin-bottom: 10px; margin-left: 20px; }
  4351. .episode-content { white-space: pre-wrap; }
  4352. </style>';
  4353. // 标题
  4354. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4355. // 处理分组数据
  4356. if (!empty($script['group']) && is_array($script['group'])) {
  4357. $groups = (array)$script['group'];
  4358. foreach ($groups as $group) {
  4359. $html .= '<div class="group">';
  4360. // 分组标题
  4361. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4362. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4363. // 故事梗概
  4364. if (!empty($group['intro'])) {
  4365. $html .= '<h3>故事梗概</h3>';
  4366. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4367. }
  4368. // 剧本亮点
  4369. if (!empty($group['highlights'])) {
  4370. $html .= '<h3>剧本亮点</h3>';
  4371. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4372. }
  4373. // 人物关系
  4374. if (!empty($group['role_relationship'])) {
  4375. $html .= '<h3>人物关系</h3>';
  4376. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4377. }
  4378. // 核心矛盾
  4379. if (!empty($group['core_contradiction'])) {
  4380. $html .= '<h3>核心矛盾</h3>';
  4381. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4382. }
  4383. // 主体列表
  4384. if (!empty($group['roles']) && is_array($group['roles'])) {
  4385. $html .= '<h3>主体列表</h3>';
  4386. $html .= '<ul>';
  4387. foreach ($group['roles'] as $role) {
  4388. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4389. }
  4390. $html .= '</ul>';
  4391. }
  4392. // 美术风格
  4393. if (!empty($group['art_style'])) {
  4394. $html .= '<h3>美术风格</h3>';
  4395. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4396. }
  4397. // 场景列表
  4398. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4399. $html .= '<h3>场景列表</h3>';
  4400. $html .= '<ul>';
  4401. foreach ($group['scenes'] as $scene) {
  4402. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4403. }
  4404. $html .= '</ul>';
  4405. }
  4406. // 分集剧本
  4407. if (!empty($group['episode_content'])) {
  4408. $html .= '<h3>分集剧本</h3>';
  4409. // 去除零宽字符和其他不可见字符
  4410. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4411. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4412. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4413. }
  4414. $html .= '</div>';
  4415. }
  4416. }
  4417. return $html;
  4418. }
  4419. /**
  4420. * 构建PDF内容
  4421. */
  4422. private function buildPdfContent($pdf, $script) {
  4423. // 标题
  4424. $pdf->SetFont('dejavusans', 'B', 18);
  4425. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4426. $pdf->Ln(5);
  4427. // 基本信息
  4428. $pdf->SetFont('dejavusans', '', 12);
  4429. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4430. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4431. $pdf->Ln(5);
  4432. // 剧本简介
  4433. if (!empty($script['intro'])) {
  4434. $pdf->SetFont('dejavusans', 'B', 14);
  4435. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4436. $pdf->SetFont('dejavusans', '', 12);
  4437. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4438. $pdf->Ln(3);
  4439. }
  4440. // 亮点
  4441. if (!empty($script['highlights'])) {
  4442. $pdf->SetFont('dejavusans', 'B', 14);
  4443. $pdf->Cell(0, 10, '亮点', 0, 1);
  4444. $pdf->SetFont('dejavusans', '', 12);
  4445. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4446. $pdf->Ln(3);
  4447. }
  4448. // 核心矛盾
  4449. if (!empty($script['core_contradiction'])) {
  4450. $pdf->SetFont('dejavusans', 'B', 14);
  4451. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4452. $pdf->SetFont('dejavusans', '', 12);
  4453. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4454. $pdf->Ln(3);
  4455. }
  4456. // 艺术风格
  4457. if (!empty($script['art_style'])) {
  4458. $pdf->SetFont('dejavusans', 'B', 14);
  4459. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4460. $pdf->SetFont('dejavusans', '', 12);
  4461. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4462. $pdf->Ln(3);
  4463. }
  4464. // 备注
  4465. if (!empty($script['remark'])) {
  4466. $pdf->SetFont('dejavusans', 'B', 14);
  4467. $pdf->Cell(0, 10, '备注', 0, 1);
  4468. $pdf->SetFont('dejavusans', '', 12);
  4469. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4470. $pdf->Ln(3);
  4471. }
  4472. // 角色列表
  4473. if (!empty($script['roles']) && is_array($script['roles'])) {
  4474. $pdf->SetFont('dejavusans', 'B', 14);
  4475. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4476. $pdf->SetFont('dejavusans', '', 12);
  4477. foreach ($script['roles'] as $index => $role) {
  4478. if (is_array($role) || is_object($role)) {
  4479. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4480. } else {
  4481. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4482. }
  4483. }
  4484. $pdf->Ln(3);
  4485. }
  4486. // 角色关系
  4487. if (!empty($script['role_relationship'])) {
  4488. $pdf->SetFont('dejavusans', 'B', 14);
  4489. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4490. $pdf->SetFont('dejavusans', '', 12);
  4491. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4492. $pdf->Ln(3);
  4493. }
  4494. // 场景列表
  4495. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4496. $pdf->SetFont('dejavusans', 'B', 14);
  4497. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4498. $pdf->SetFont('dejavusans', '', 12);
  4499. foreach ($script['scenes'] as $index => $scene) {
  4500. if (is_array($scene) || is_object($scene)) {
  4501. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4502. } else {
  4503. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4504. }
  4505. }
  4506. $pdf->Ln(5);
  4507. }
  4508. // 分集内容
  4509. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4510. $pdf->SetFont('dejavusans', 'B', 16);
  4511. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4512. $pdf->Ln(3);
  4513. foreach ($script['episodes'] as $episode) {
  4514. // 检查是否需要新页面
  4515. if ($pdf->GetY() > 250) {
  4516. $pdf->AddPage();
  4517. }
  4518. $pdf->SetFont('dejavusans', 'B', 14);
  4519. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4520. if (!empty($episode['title'])) {
  4521. $episodeTitle .= ':' . $episode['title'];
  4522. }
  4523. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4524. // 处理分段内容
  4525. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4526. $pdf->SetFont('dejavusans', '', 12);
  4527. foreach ($episode['segments'] as $segment) {
  4528. if (!empty($segment['segment_content'])) {
  4529. // 如果有分段编号,显示分段标题
  4530. if (!empty($segment['segment_number'])) {
  4531. $pdf->SetFont('dejavusans', 'B', 12);
  4532. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4533. $pdf->SetFont('dejavusans', '', 12);
  4534. }
  4535. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4536. $pdf->Ln(2);
  4537. }
  4538. }
  4539. }
  4540. $pdf->Ln(5);
  4541. }
  4542. }
  4543. }
  4544. /**
  4545. * 构建剧本文本内容
  4546. */
  4547. private function buildScriptContent($script) {
  4548. $content = '';
  4549. $groups = $script['group'];
  4550. $groups = (array)$groups;
  4551. foreach ($groups as $group) {
  4552. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4553. // 剧本基本信息
  4554. if (!empty($group['intro'])) {
  4555. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4556. }
  4557. if (!empty($group['highlights'])) {
  4558. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4559. }
  4560. if (!empty($group['role_relationship'])) {
  4561. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4562. }
  4563. if (!empty($group['core_contradiction'])) {
  4564. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4565. }
  4566. if (!empty($group['roles']) && is_array($group['roles'])) {
  4567. $content .= "###主体列表\n";
  4568. foreach ($group['roles'] as $role) {
  4569. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4570. }
  4571. $content .= "\n\n";
  4572. }
  4573. if (!empty($group['art_style'])) {
  4574. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4575. }
  4576. // 场景信息
  4577. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4578. $content .= "###场景列表\n";
  4579. foreach ($group['scenes'] as $scene) {
  4580. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4581. }
  4582. $content .= "\n\n";
  4583. }
  4584. // 分集内容
  4585. if (!empty($group['episode_content'])) {
  4586. $content .= "###分集剧本\n";
  4587. $content .= $group['episode_content'];
  4588. // foreach ($script['episodes'] as $episode) {
  4589. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4590. // // if (!empty($episode['episode_name'])) {
  4591. // // $content .= ":" . $episode['episode_name'];
  4592. // // }
  4593. // // $content .= "\n";
  4594. // $content .= $episode['episode_content'] . "\n\n";
  4595. // }
  4596. }
  4597. }
  4598. return $content;
  4599. }
  4600. /**
  4601. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4602. *
  4603. * @param array $data 包含以下参数:
  4604. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4605. * - question: 用户问题(可选)
  4606. * - model: 使用的模型(r1 或 v3,默认 v3)
  4607. * @return \Generator 返回生成器,用于流式输出
  4608. */
  4609. public function addChat($data) {
  4610. $uid = Site::getUid();
  4611. $anime_id = getProp($data, 'anime_id');
  4612. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4613. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4614. if (!$anime) Utils::throwError('20003:对话不存在');
  4615. $file = getProp($data, 'file');
  4616. $content = getProp($data, 'content', '');
  4617. $bid = getProp($data, 'bid', 0);
  4618. $script_id = getProp($data, 'script_id', 0);
  4619. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4620. $prompt = getProp($data, 'prompt');
  4621. $user_anime_name = getProp($anime, 'anime_name');
  4622. // 处理文本模型
  4623. $model = getProp($data, 'model');
  4624. if (!$model) {
  4625. // 用户没有输入,从anime表获取
  4626. $model = getProp($anime, 'model');
  4627. if (!$model) {
  4628. // anime表也没有,使用默认值
  4629. $model = 'doubao-seed-2-0-mini-260215';
  4630. }
  4631. }
  4632. // 验证模型是否在可用模型表中
  4633. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4634. $model = 'doubao-seed-2-0-mini-260215';
  4635. }
  4636. $is_multi = getProp($anime, 'is_multi');
  4637. $is_single = (int)$is_multi !== 1;
  4638. // 积分余额预检(仅单剧集模式收费)
  4639. if ($is_single) {
  4640. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4641. }
  4642. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4643. if ($prompt) {
  4644. $question .= "本次修改要求如下:\n{$prompt}";
  4645. }
  4646. // if (!$file && !$content && !$bid) {
  4647. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4648. // }
  4649. // 提取文件内容
  4650. if ($file) {
  4651. $content = $this->extractFileContent($file);
  4652. if (!$content) {
  4653. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4654. }
  4655. } elseif ($script_id) {
  4656. $content = $this->getContentByScriptId($script_id);
  4657. if (!$content) {
  4658. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4659. }
  4660. } elseif ($bid) {
  4661. $content = $this->getContentByBid($bid);
  4662. if (!$content) {
  4663. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4664. }
  4665. } elseif ($content) {
  4666. $content = filterContent($content);
  4667. } else {
  4668. $content = getProp($anime, 'content');
  4669. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4670. $need_generate_content = true;
  4671. }
  4672. }
  4673. // 美术风格
  4674. $input_art_style = getProp($data, 'art_style');
  4675. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4676. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4677. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4678. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4679. 中年女:邻居阿姨
  4680. 老年男:幽默大爷
  4681. 老年女:婆婆
  4682. 萌娃:奶气萌娃";
  4683. // 判断是否需要生成原文内容
  4684. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4685. // 如果需要生成原文内容,添加额外的要求
  4686. $content_generation_requirement = $need_generate_content
  4687. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4688. : "";
  4689. // 美术风格
  4690. if (!$mappedArtStyle) {
  4691. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4692. }else {
  4693. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4694. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4695. }else {
  4696. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4697. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4698. }
  4699. }
  4700. $systemPrompt = $is_single
  4701. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4702. 强制要求:
  4703. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4704. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4705. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4706. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4707. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4708. 普通要求:
  4709. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4710. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4711. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4712. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4713. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4714. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4715. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4716. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4717. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4718. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4719. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4720. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4721. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4722. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4723. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4724. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4725. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4726. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4727. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4728. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4729. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4730. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4731. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4732. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4733. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4734. 5.{$mappedArtStyle_prompt}\n\n
  4735. 示例如下:\n
  4736. ###剧本名:西昆仑
  4737. ###故事梗概
  4738. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4739. ###剧本亮点
  4740. 亮点1:绝境奇药,生死一线
  4741. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4742. 亮点2:结拜兄妹,化解尴尬
  4743. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4744. 亮点3:纤发夺命,情愫暗涌
  4745. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4746. ###人物关系
  4747. 阿雪与梁萧之间存在兄妹之情。
  4748. ###核心矛盾
  4749. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4750. ###主体列表
  4751. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4752. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4753. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4754. 姿态:站立。}{{甜心小美}}
  4755. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4756. 全景,正面拍摄,青年女性,亚洲人。
  4757. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4758. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4759. 姿态:站立。}{{阳光青年}}
  4760. ###美术风格
  4761. 基础画风风格词:厚涂古风
  4762. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4763. ###场景列表
  4764. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4765. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4766. 无人物。}
  4767. ###分镜剧本
  4768. ##第1幕:徐家老旧厨房 白天 室内
  4769. 分镜1
  4770. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4771. 场景:徐家老旧厨房
  4772. 构图设计:全景,低角度仰视
  4773. 运镜调度:手持拍摄
  4774. 配音角色:旁白
  4775. 出镜角色:许芸-校服装、徐母
  4776. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4777. 画面类型:普通画面
  4778. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4779. 分镜2
  4780. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4781. 场景:徐家老旧厨房
  4782. 构图设计:近景,徐母面部特写
  4783. 运镜调度:固定镜头
  4784. 配音角色:徐母
  4785. 出镜角色:徐母
  4786. 台词内容:问我夜不归宿死哪儿去了。
  4787. 画面类型:对口型
  4788. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4789. ##第2幕:徐家简陋客厅 黄昏 室内
  4790. 分镜3
  4791. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4792. 场景:徐家简陋客厅
  4793. 构图设计:全景,景深虚化
  4794. 运镜调度:固定镜头
  4795. 配音角色:旁白
  4796. 出镜角色:无
  4797. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4798. 画面类型:普通画面
  4799. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4800. 分镜4
  4801. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4802. 场景:徐家简陋客厅
  4803. 构图设计:特写,火车票
  4804. 运镜调度:固定镜头
  4805. 配音角色:旁白
  4806. 出镜角色:无
  4807. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4808. 画面类型:普通画面
  4809. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4810. "
  4811. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4812. 强制要求:\n
  4813. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4814. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4815. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4816. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4817. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4818. 普通要求:\n
  4819. 1.剧本名(必须生成)必须与文档内容高度相关
  4820. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4821. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4822. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4823. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4824. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4825. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4826. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4827. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4828. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4829. 4.{$mappedArtStyle_prompt}\n\n
  4830. 示例如下:\n
  4831. ###剧本名:西昆仑
  4832. ###故事梗概
  4833. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4834. ###剧本亮点
  4835. 亮点1:绝境奇药,生死一线
  4836. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4837. 亮点2:结拜兄妹,化解尴尬
  4838. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4839. 亮点3:纤发夺命,情愫暗涌
  4840. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4841. ###人物关系
  4842. 阿雪与梁萧之间存在兄妹之情。
  4843. ###核心矛盾
  4844. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4845. ###主体列表
  4846. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4847. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4848. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4849. 姿态:站立。}{{甜心小美}}
  4850. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4851. 全景,正面拍摄,青年女性,亚洲人。
  4852. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4853. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4854. 姿态:站立。}{{阳光青年}}
  4855. ###美术风格
  4856. 基础画风风格词:厚涂古风
  4857. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4858. ###场景列表
  4859. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4860. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4861. 无人物。}";
  4862. // 构建消息
  4863. $messages = [
  4864. [
  4865. 'role' => 'system',
  4866. 'content' => $systemPrompt
  4867. ],
  4868. [
  4869. 'role' => 'user',
  4870. 'content' => "以下是文档内容:
  4871. {$content}
  4872. 用户问题:
  4873. {$question}"
  4874. ]
  4875. ];
  4876. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4877. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4878. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4879. if ($model === 'deepseek-chat') {
  4880. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4881. $model = 'deepseek-v4-flash';
  4882. $thinkingMode = 'disabled';
  4883. } elseif ($model === 'deepseek-reasoner') {
  4884. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4885. $model = 'deepseek-v4-flash';
  4886. $thinkingMode = 'enabled';
  4887. }
  4888. $post_data = [
  4889. 'model' => $model,
  4890. 'messages' => $messages,
  4891. // 'max_tokens' => 8192,
  4892. 'temperature' => 0.7,
  4893. 'frequency_penalty' => 0,
  4894. 'presence_penalty' => 0,
  4895. 'response_format' => ['type' => 'text'],
  4896. 'thinking' => ['type'=>$thinkingMode],
  4897. 'stream' => true // 启用流式输出
  4898. ];
  4899. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4900. // 根据模型类型选择调用方法
  4901. $fullContent = '';
  4902. $fullReasoningContent = '';
  4903. $usage = [];
  4904. try {
  4905. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4906. // DeepSeek 官方模型使用 DeepSeek API
  4907. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4908. } else if (in_array($model, $this->gpt_text_models)) {
  4909. // GPT-5.4 模型使用 TokenRouter API
  4910. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4911. } else if (in_array($model, $this->gemini_text_models)) {
  4912. // Gemini 模型使用 Gemini API
  4913. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4914. } else {
  4915. // 其他模型使用火山引擎API
  4916. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4917. }
  4918. // 验证返回值类型
  4919. if (!is_iterable($streamGenerator)) {
  4920. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4921. dLog('deepseek')->error('addChat流式生成器无效', [
  4922. 'generator_type' => $errorType,
  4923. 'model' => $model,
  4924. 'anime_id' => $anime_id
  4925. ]);
  4926. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4927. 'type' => $errorType,
  4928. 'model' => $model
  4929. ]);
  4930. yield [
  4931. 'type' => 'error',
  4932. 'script' => [],
  4933. 'episode' => [],
  4934. 'answer' => '',
  4935. 'reasoning' => '',
  4936. 'usage' => [],
  4937. 'error' => '接口返回数据异常,请重新请求'
  4938. ];
  4939. return;
  4940. }
  4941. // 处理流式输出
  4942. foreach ($streamGenerator as $chunk) {
  4943. if (isset($chunk['type'])) {
  4944. if ($chunk['type'] === 'done') {
  4945. // 最终结果
  4946. $fullContent = $chunk['full_content'];
  4947. $fullReasoningContent = $chunk['full_reasoning'];
  4948. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4949. } else {
  4950. // 逐块yield数据
  4951. yield $chunk;
  4952. }
  4953. }
  4954. }
  4955. } catch (\Exception $e) {
  4956. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4957. 'model' => $model,
  4958. 'anime_id' => $anime_id,
  4959. 'trace' => $e->getTraceAsString()
  4960. ]);
  4961. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4962. 'error' => $e->getMessage(),
  4963. 'model' => $model
  4964. ]);
  4965. yield [
  4966. 'type' => 'error',
  4967. 'script' => [],
  4968. 'episode' => [],
  4969. 'answer' => '',
  4970. 'reasoning' => '',
  4971. 'usage' => [],
  4972. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4973. ];
  4974. return;
  4975. }
  4976. dLog('deepseek')->info('完整内容: '.$fullContent);
  4977. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4978. // 处理完整内容并返回最终结果
  4979. $script_arr = [];
  4980. if ($fullContent) {
  4981. $script_arr = handleScriptContent($fullContent);
  4982. dLog('deepseek')->info('解析内容', $script_arr);
  4983. logDB('deepseek', 'info', '解析内容', $script_arr);
  4984. }
  4985. if (empty($script_arr['roles'])) {
  4986. // 未生成剧本相关内容,保存对话记录并返回提示
  4987. dLog('deepseek')->info('未生成剧本相关的内容');
  4988. try {
  4989. DB::beginTransaction();
  4990. $now = date('Y-m-d H:i:s');
  4991. // 保存对话记录
  4992. $records = [
  4993. [
  4994. 'uid' => $uid,
  4995. 'anime_id' => $anime_id,
  4996. 'sequence' => 0,
  4997. 'role' => 'user',
  4998. 'content' => $prompt,
  4999. 'created_at' => $now,
  5000. 'updated_at' => $now
  5001. ],
  5002. [
  5003. 'uid' => $uid,
  5004. 'anime_id' => $anime_id,
  5005. 'sequence' => 0,
  5006. 'role' => 'assistant',
  5007. // 'content' => $fullContent,
  5008. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5009. 'created_at' => $now,
  5010. 'updated_at' => $now
  5011. ]
  5012. ];
  5013. DB::table('mp_anime_records')->insert($records);
  5014. DB::commit();
  5015. } catch (\Exception $e) {
  5016. DB::rollBack();
  5017. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5018. }
  5019. yield [
  5020. 'type' => 'done',
  5021. 'script' => [],
  5022. 'episode' => [],
  5023. 'answer' => $fullContent,
  5024. 'reasoning' => $fullReasoningContent,
  5025. 'usage' => $usage,
  5026. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5027. ];
  5028. return;
  5029. }
  5030. // 如果需要生成原文内容,从script_arr中提取
  5031. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5032. $content = $script_arr['content'];
  5033. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5034. if (!$content) {
  5035. yield [
  5036. 'type' => 'done',
  5037. 'script' => [],
  5038. 'episode' => [],
  5039. 'answer' => $fullContent,
  5040. 'reasoning' => $fullReasoningContent,
  5041. 'usage' => $usage,
  5042. 'error' => '未生成剧本内容,请调整提示词再试'
  5043. ];
  5044. return;
  5045. }
  5046. }
  5047. // 替换美术风格
  5048. if ($mappedArtStyle !== '') {
  5049. $script_arr['art_style'] = $mappedArtStyle;
  5050. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5051. }
  5052. // 新建动漫
  5053. if ($user_anime_name == '新剧本策划') {
  5054. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5055. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5056. // if (!$anime_name) {
  5057. // // 未识别到剧本名,保存对话记录并返回提示
  5058. // dLog('deepseek')->info('未能识别到剧本名称');
  5059. // try {
  5060. // DB::beginTransaction();
  5061. // $now = date('Y-m-d H:i:s');
  5062. // // 保存对话记录
  5063. // $records = [
  5064. // [
  5065. // 'uid' => $uid,
  5066. // 'anime_id' => $anime_id,
  5067. // 'sequence' => 0,
  5068. // 'role' => 'user',
  5069. // 'content' => $prompt,
  5070. // 'created_at' => $now,
  5071. // 'updated_at' => $now
  5072. // ],
  5073. // [
  5074. // 'uid' => $uid,
  5075. // 'anime_id' => $anime_id,
  5076. // 'sequence' => 0,
  5077. // 'role' => 'assistant',
  5078. // 'content' => '未能生成剧本名称,请重试',
  5079. // 'created_at' => $now,
  5080. // 'updated_at' => $now
  5081. // ]
  5082. // ];
  5083. // DB::table('mp_anime_records')->insert($records);
  5084. // DB::commit();
  5085. // } catch (\Exception $e) {
  5086. // DB::rollBack();
  5087. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5088. // }
  5089. // yield [
  5090. // 'type' => 'done',
  5091. // 'script' => [],
  5092. // 'episode' => [],
  5093. // 'answer' => $fullContent,
  5094. // 'reasoning' => $fullReasoningContent,
  5095. // 'usage' => $usage,
  5096. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5097. // ];
  5098. // return;
  5099. // }
  5100. // 确认对话名称唯一性
  5101. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5102. $anime_name = $anime_name . '_' . date('YmdHis');
  5103. }
  5104. }else {
  5105. $anime_name = $user_anime_name;
  5106. }
  5107. $table_data = [
  5108. 'user_id' => $uid,
  5109. 'anime_name' => $anime_name,
  5110. 'model' => $model,
  5111. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5112. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5113. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5114. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5115. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5116. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5117. 'art_style_type' => $input_art_style,
  5118. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5119. 'status' => '解析完成',
  5120. 'content' => $content,
  5121. 'is_multi' => $is_multi,
  5122. 'ace_mode' => $ace_mode,
  5123. 'generate_status' => '待执行',
  5124. 'updated_at' => date('Y-m-d H:i:s')
  5125. ];
  5126. if ($table_data['content']) {
  5127. $chapters = splitContent($table_data['content']);
  5128. $chapter_count = count($chapters);
  5129. if ($chapter_count > 0) {
  5130. $table_data['start_episode_sequence'] = 1;
  5131. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5132. }
  5133. }
  5134. // 如果有剧本ID则进行绑定
  5135. if ($script_id) {
  5136. $table_data['script_id'] = $script_id;
  5137. }
  5138. $single_episode = [];
  5139. try {
  5140. DB::beginTransaction();
  5141. $now = date('Y-m-d H:i:s');
  5142. // 更新动漫大纲
  5143. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5144. if (!$boolen) {
  5145. dLog('deepseek')->info('动漫保存失败', $table_data);
  5146. Utils::throwError('20003:动漫保存失败');
  5147. }
  5148. // 保存对话记录
  5149. $records = [
  5150. [
  5151. 'uid' => $uid,
  5152. 'anime_id' => $anime_id,
  5153. 'sequence' => 0,
  5154. 'role' => 'user',
  5155. 'content' => $prompt,
  5156. 'created_at' => date('Y-m-d H:i:s'),
  5157. 'updated_at' => date('Y-m-d H:i:s')
  5158. ],
  5159. [
  5160. 'uid' => $uid,
  5161. 'anime_id' => $anime_id,
  5162. 'sequence' => 0,
  5163. 'role' => 'assistant',
  5164. 'content' => $fullContent,
  5165. 'created_at' => date('Y-m-d H:i:s'),
  5166. 'updated_at' => date('Y-m-d H:i:s')
  5167. ]
  5168. ];
  5169. // 保存对话记录
  5170. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5171. if (!$boolen3) {
  5172. Utils::throwError('20003:对话记录保存失败');
  5173. }
  5174. if ($is_single) {
  5175. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5176. if (empty($episode_arr['acts'])) {
  5177. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5178. }
  5179. $saveResult = $this->saveEpisodeVersionData(
  5180. $anime_id,
  5181. 1,
  5182. $episode_arr,
  5183. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5184. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5185. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5186. null,
  5187. null,
  5188. false,
  5189. $content,
  5190. $now
  5191. );
  5192. $single_episode = $saveResult['episode'];
  5193. $episode_id = $saveResult['episode_id'];
  5194. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5195. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5196. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5197. 'props' => json_encode($saveResult['merged_props'], 256),
  5198. 'updated_at' => $now
  5199. ]);
  5200. if ($boolen5 === false) {
  5201. Utils::throwError('20003:单剧集主表资源同步失败');
  5202. }
  5203. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5204. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5205. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5206. $episode_record_content = '确认分镜大纲';
  5207. if ($content !== '') {
  5208. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5209. }
  5210. $episode_records = [
  5211. [
  5212. 'uid' => $uid,
  5213. 'anime_id' => $anime_id,
  5214. 'role' => 'user',
  5215. 'content' => $episode_record_content,
  5216. 'sequence' => 1,
  5217. 'episode_id' => $episode_id,
  5218. 'created_at' => $now,
  5219. 'updated_at' => $now
  5220. ],
  5221. [
  5222. 'uid' => $uid,
  5223. 'anime_id' => $anime_id,
  5224. 'role' => 'assistant',
  5225. 'content' => $fullContent,
  5226. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5227. 'sequence' => 1,
  5228. 'episode_id' => $episode_id,
  5229. 'created_at' => $now,
  5230. 'updated_at' => $now
  5231. ]
  5232. ];
  5233. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5234. if (!$boolen4) {
  5235. Utils::throwError('20003:单剧集分镜记录保存失败');
  5236. }
  5237. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5238. if ($is_single && !empty($single_episode)) {
  5239. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5240. 'anime_id' => $anime_id,
  5241. 'episode_id' => $episode_id ?? 0,
  5242. 'model' => $model,
  5243. 'source' => 'addChat',
  5244. ]);
  5245. }
  5246. }
  5247. }catch (\Exception $e) {
  5248. DB::rollBack();
  5249. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5250. yield [
  5251. 'type' => 'done',
  5252. 'answer' => $fullContent,
  5253. 'reasoning' => $fullReasoningContent,
  5254. 'usage' => $usage,
  5255. 'error' => $e->getMessage(),
  5256. ];
  5257. return;
  5258. }
  5259. DB::commit();
  5260. dLog('deepseek')->info('保存完毕');
  5261. if ($is_single && !empty($single_episode)) {
  5262. // $this->batchSetGlobalRoleImg([
  5263. // 'anime_id' => $anime_id,
  5264. // ]);
  5265. // $this->batchSetGlobalSceneImg([
  5266. // 'anime_id' => $anime_id,
  5267. // ]);
  5268. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5269. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5270. }
  5271. $table_data['anime_id'] = $anime_id;
  5272. $table_data['roles'] = json_decode($table_data['roles'], true);
  5273. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5274. // $table_data['episodes'] = $script_arr['episodes'];
  5275. unset($table_data['created_at']);
  5276. unset($table_data['updated_at']);
  5277. unset($table_data['status']);
  5278. dLog('deepseek')->info('开始返回');
  5279. yield [
  5280. 'type' => 'done',
  5281. 'script' => $table_data,
  5282. 'episode' => $single_episode,
  5283. 'answer' => $fullContent,
  5284. 'reasoning' => $fullReasoningContent,
  5285. 'usage' => $usage
  5286. ];
  5287. }
  5288. public function reGenerateAnime($data) {
  5289. $uid = Site::getUid();
  5290. $file = getProp($data, 'file');
  5291. $content = getProp($data, 'content', '');
  5292. $bid = getProp($data, 'bid', 0);
  5293. $script_id = getProp($data, 'script_id', 0);
  5294. $anime_id = getProp($data, 'anime_id');
  5295. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5296. if (!$anime) {
  5297. Utils::throwError('20003:该对话不存在');
  5298. }
  5299. $user_anime_name = getProp($anime, 'anime_name');
  5300. $prompt = getProp($data, 'prompt');
  5301. // 处理文本模型
  5302. $model = getProp($data, 'model');
  5303. if (!$model) {
  5304. // 用户没有输入,从anime表获取
  5305. $model = getProp($anime, 'model');
  5306. if (!$model) {
  5307. // anime表也没有,使用默认值
  5308. $model = 'doubao-seed-2-0-mini-260215';
  5309. }
  5310. }
  5311. // 验证模型是否在可用模型表中
  5312. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5313. $model = 'doubao-seed-2-0-mini-260215';
  5314. }
  5315. $is_multi = getProp($anime, 'is_multi', 1);
  5316. $is_single = (int)$is_multi !== 1;
  5317. // 积分余额预检(仅单剧集模式收费)
  5318. if ($is_single) {
  5319. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5320. }
  5321. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5322. if ($is_single) {
  5323. $episode_exists = DB::table('mp_anime_episodes')
  5324. ->where('anime_id', $anime_id)
  5325. ->where('sequence', 1)
  5326. ->exists();
  5327. if ($episode_exists) {
  5328. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5329. }
  5330. }
  5331. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5332. if ($prompt) {
  5333. $question .= "本次修改要求如下:\n{$prompt}";
  5334. }
  5335. // 提取文件内容
  5336. if ($file) {
  5337. $content = $this->extractFileContent($file);
  5338. if (!$content) {
  5339. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5340. }
  5341. } elseif ($script_id) {
  5342. $content = $this->getContentByScriptId($script_id);
  5343. if (!$content) {
  5344. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5345. }
  5346. } elseif ($bid) {
  5347. $content = $this->getContentByBid($bid);
  5348. if (!$content) {
  5349. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5350. }
  5351. } elseif ($content) {
  5352. $content = filterContent($content);
  5353. }else {
  5354. $content = filterContent(getProp($anime, 'content'));
  5355. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5356. $need_generate_content = true;
  5357. }
  5358. }
  5359. // 判断是否需要生成原文内容
  5360. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5361. // 如果需要生成原文内容,添加额外的要求
  5362. $content_generation_requirement = $need_generate_content
  5363. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5364. : "";
  5365. // 美术风格
  5366. $input_art_style = getProp($anime, 'art_style');
  5367. if (!$input_art_style) {
  5368. $input_art_style = getProp($data, 'art_style');
  5369. }
  5370. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5371. // 美术风格
  5372. if (!$mappedArtStyle) {
  5373. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5374. }else {
  5375. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5376. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5377. }else {
  5378. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5379. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5380. }
  5381. }
  5382. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5383. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5384. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5385. 中年女:邻居阿姨
  5386. 老年男:幽默大爷
  5387. 老年女:婆婆
  5388. 萌娃:奶气萌娃";
  5389. $system_message = ['role'=>'system', 'content'=>$is_single
  5390. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5391. 强制要求:
  5392. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5393. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5394. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5395. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5396. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5397. 普通要求:
  5398. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5399. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5400. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5401. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5402. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5403. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5404. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5405. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5406. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5407. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5408. 3.$mappedArtStyle_prompt\n\n
  5409. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5410. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5411. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5412. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5413. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5414. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5415. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5416. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5417. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5418. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5419. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5420. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5421. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5422. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5423. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5424. 示例如下:\n
  5425. ###剧本名:西昆仑
  5426. ###故事梗概
  5427. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5428. ###剧本亮点
  5429. 亮点1:绝境奇药,生死一线
  5430. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5431. 亮点2:结拜兄妹,化解尴尬
  5432. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5433. 亮点3:纤发夺命,情愫暗涌
  5434. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5435. ###人物关系
  5436. 阿雪与梁萧之间存在兄妹之情。
  5437. ###核心矛盾
  5438. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5439. ###主体列表
  5440. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5441. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5442. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5443. 姿态:站立。}{{甜心小美}}
  5444. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5445. 全景,正面拍摄,青年女性,亚洲人。
  5446. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5447. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5448. 姿态:站立。}{{阳光青年}}
  5449. ###美术风格
  5450. 基础画风风格词:厚涂古风
  5451. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5452. ###场景列表
  5453. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5454. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5455. 无人物。}
  5456. ###分镜剧本
  5457. ##第1幕:徐家老旧厨房 白天 室内
  5458. 分镜1
  5459. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5460. 场景:徐家老旧厨房
  5461. 构图设计:全景,低角度仰视
  5462. 运镜调度:手持拍摄
  5463. 配音角色:旁白
  5464. 出镜角色:许芸-校服装、徐母
  5465. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5466. 画面类型:普通画面
  5467. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5468. 分镜2
  5469. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5470. 场景:徐家老旧厨房
  5471. 构图设计:近景,徐母面部特写
  5472. 运镜调度:固定镜头
  5473. 配音角色:徐母
  5474. 出镜角色:徐母
  5475. 台词内容:问我夜不归宿死哪儿去了。
  5476. 画面类型:对口型
  5477. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5478. ##第2幕:徐家简陋客厅 黄昏 室内
  5479. 分镜3
  5480. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5481. 场景:徐家简陋客厅
  5482. 构图设计:全景,景深虚化
  5483. 运镜调度:固定镜头
  5484. 配音角色:旁白
  5485. 出镜角色:无
  5486. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5487. 画面类型:普通画面
  5488. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5489. 分镜4
  5490. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5491. 场景:徐家简陋客厅
  5492. 构图设计:特写,火车票
  5493. 运镜调度:固定镜头
  5494. 配音角色:旁白
  5495. 出镜角色:无
  5496. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5497. 画面类型:普通画面
  5498. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5499. "
  5500. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5501. 强制要求:\n
  5502. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5503. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5504. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5505. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5506. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5507. 普通要求:\n
  5508. 1.剧本名(必须生成)必须与文档内容高度相关
  5509. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5510. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5511. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5512. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5513. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5514. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5515. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5516. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5517. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5518. 4.$mappedArtStyle_prompt\n\n
  5519. 示例如下:\n
  5520. ###剧本名:西昆仑
  5521. ###故事梗概
  5522. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5523. ###剧本亮点
  5524. 亮点1:绝境奇药,生死一线
  5525. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5526. 亮点2:结拜兄妹,化解尴尬
  5527. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5528. 亮点3:纤发夺命,情愫暗涌
  5529. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5530. ###人物关系
  5531. 阿雪与梁萧之间存在兄妹之情。
  5532. ###核心矛盾
  5533. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5534. ###主体列表
  5535. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5536. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5537. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5538. 姿态:站立。}{{甜心小美}}
  5539. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5540. 全景,正面拍摄,青年女性,亚洲人。
  5541. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5542. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5543. 姿态:站立。}{{阳光青年}}
  5544. ###美术风格
  5545. 基础画风风格词:厚涂古风
  5546. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5547. ###场景列表
  5548. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5549. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5550. 无人物。}"];
  5551. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5552. $episode_count = $this->extractEpisodeNumber($prompt);
  5553. if ((int)getProp($anime, 'is_multi') !== 1) {
  5554. yield [
  5555. 'type' => 'done',
  5556. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5557. 'reasoning' => '',
  5558. 'usage' => []
  5559. ];
  5560. return;
  5561. }
  5562. if ($episode_count) {
  5563. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5564. $system_message = [
  5565. 'role' => 'system',
  5566. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5567. 强制要求:\n
  5568. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5569. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5570. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5571. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5572. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5573. 普通要求:\n
  5574. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5575. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5576. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5577. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5578. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5579. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5580. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5581. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5582. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5583. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5584. 示例如下:\n
  5585. ###剧本名:西昆仑
  5586. ###故事梗概
  5587. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5588. ###剧本亮点
  5589. 亮点1:绝境奇药,生死一线
  5590. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5591. 亮点2:结拜兄妹,化解尴尬
  5592. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5593. 亮点3:纤发夺命,情愫暗涌
  5594. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5595. ###人物关系
  5596. 阿雪与梁萧之间存在兄妹之情。
  5597. ###核心矛盾
  5598. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5599. ###主体列表
  5600. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5601. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5602. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5603. 姿态:站立。}{{甜心小美}}
  5604. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5605. 全景,正面拍摄,青年女性,亚洲人。
  5606. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5607. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5608. 姿态:站立。}{{阳光青年}}
  5609. ###美术风格
  5610. 基础画风风格词:厚涂古风
  5611. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5612. ###场景列表
  5613. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5614. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5615. 无人物。}
  5616. ###分集详细内容
  5617. ##第1章 重生
  5618. 我重生了。
  5619. 源于一个男人偏执的暗恋。
  5620. ##第2章 相救
  5621. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5622. 我眼睛扫向站在锅炉后的卞大伟。"
  5623. ];
  5624. // 构建消息
  5625. $messages = [
  5626. $system_message,
  5627. [
  5628. 'role' => 'user',
  5629. 'content' => "以下是文档内容:
  5630. {$content}
  5631. 用户问题:
  5632. {$question}"
  5633. ]
  5634. ];
  5635. }else {
  5636. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5637. // 构建消息
  5638. $messages = [
  5639. $system_message,
  5640. [
  5641. 'role' => 'user',
  5642. 'content' => "以下是文档内容:
  5643. {$content}
  5644. 用户问题:
  5645. {$question}"
  5646. ]
  5647. ];
  5648. }else {
  5649. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5650. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5651. return (array)$value;
  5652. })->toArray();
  5653. array_unshift($messages, $system_message);
  5654. $messages[] = [
  5655. 'role' => 'user',
  5656. 'content' => $prompt
  5657. ];
  5658. }
  5659. }
  5660. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5661. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5662. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5663. if ($model === 'deepseek-chat') {
  5664. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5665. $model = 'deepseek-v4-flash';
  5666. $thinkingMode = 'disabled';
  5667. } elseif ($model === 'deepseek-reasoner') {
  5668. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5669. $model = 'deepseek-v4-flash';
  5670. $thinkingMode = 'enabled';
  5671. }
  5672. $post_data = [
  5673. 'model' => $model,
  5674. 'messages' => $messages,
  5675. // 'max_tokens' => 8192,
  5676. 'temperature' => 0.7,
  5677. 'frequency_penalty' => 0,
  5678. 'presence_penalty' => 0,
  5679. 'response_format' => ['type' => 'text'],
  5680. 'thinking' => ['type' => $thinkingMode],
  5681. 'stream' => true // 启用流式输出
  5682. ];
  5683. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5684. // 根据模型类型选择调用方法
  5685. $fullContent = '';
  5686. $fullReasoningContent = '';
  5687. $usage = [];
  5688. // dd($post_data);
  5689. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5690. try {
  5691. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5692. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5693. } else if (in_array($model, $this->gpt_text_models)) {
  5694. // GPT-5.4 模型使用 TokenRouter API
  5695. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5696. } else if (in_array($model, $this->gemini_text_models)) {
  5697. // Gemini 模型使用 Gemini API
  5698. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5699. } else {
  5700. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5701. }
  5702. // 验证返回值类型
  5703. if (!is_iterable($streamGenerator)) {
  5704. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5705. dLog('deepseek')->error('方法名流式生成器无效', [
  5706. 'generator_type' => $errorType,
  5707. 'model' => $model,
  5708. // 添加其他上下文信息
  5709. ]);
  5710. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5711. 'type' => $errorType,
  5712. 'model' => $model
  5713. ]);
  5714. yield [
  5715. 'type' => 'error',
  5716. // 根据方法返回相应的空数据结构
  5717. 'answer' => '',
  5718. 'reasoning' => '',
  5719. 'usage' => [],
  5720. 'error' => '接口返回数据异常,请重新请求'
  5721. ];
  5722. return;
  5723. }
  5724. // 处理流式输出
  5725. foreach ($streamGenerator as $chunk) {
  5726. if (isset($chunk['type'])) {
  5727. if ($chunk['type'] === 'done') {
  5728. $fullContent = $chunk['full_content'];
  5729. $fullReasoningContent = $chunk['full_reasoning'];
  5730. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5731. } else {
  5732. yield $chunk;
  5733. }
  5734. }
  5735. }
  5736. } catch (\Exception $e) {
  5737. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5738. 'model' => $model,
  5739. 'trace' => $e->getTraceAsString()
  5740. ]);
  5741. logDB('deepseek', 'error', '方法名流式处理失败', [
  5742. 'error' => $e->getMessage(),
  5743. 'model' => $model
  5744. ]);
  5745. yield [
  5746. 'type' => 'error',
  5747. // 根据方法返回相应的空数据结构
  5748. 'answer' => '',
  5749. 'reasoning' => '',
  5750. 'usage' => [],
  5751. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5752. ];
  5753. return;
  5754. }
  5755. dLog('deepseek')->info('完整内容: '.$fullContent);
  5756. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5757. // 处理完整内容并返回最终结果
  5758. $script_arr = [];
  5759. if ($fullContent) {
  5760. $script_arr = handleScriptContent($fullContent);
  5761. dLog('deepseek')->info('解析内容', $script_arr);
  5762. logDB('deepseek', 'info', '解析内容', $script_arr);
  5763. }
  5764. if (empty($script_arr['roles'])) {
  5765. // 未生成剧本相关内容,保存对话记录并返回提示
  5766. dLog('deepseek')->info('未生成剧本相关的内容');
  5767. try {
  5768. $now = date('Y-m-d H:i:s');
  5769. // 保存对话记录
  5770. $records = [
  5771. [
  5772. 'uid' => $uid,
  5773. 'anime_id' => $anime_id,
  5774. 'sequence' => 0,
  5775. 'role' => 'user',
  5776. 'content' => $prompt,
  5777. 'created_at' => $now,
  5778. 'updated_at' => $now
  5779. ],
  5780. [
  5781. 'uid' => $uid,
  5782. 'anime_id' => $anime_id,
  5783. 'sequence' => 0,
  5784. 'role' => 'assistant',
  5785. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5786. 'created_at' => $now,
  5787. 'updated_at' => $now
  5788. ]
  5789. ];
  5790. DB::table('mp_anime_records')->insert($records);
  5791. } catch (\Exception $e) {
  5792. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5793. }
  5794. yield [
  5795. 'type' => 'done',
  5796. 'script' => [],
  5797. 'episode' => [],
  5798. 'answer' => $fullContent,
  5799. 'reasoning' => $fullReasoningContent,
  5800. 'usage' => $usage,
  5801. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5802. ];
  5803. return;
  5804. }
  5805. // 替换美术风格
  5806. if ($mappedArtStyle !== '') {
  5807. $script_arr['art_style'] = $mappedArtStyle;
  5808. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5809. }
  5810. if ($user_anime_name != '新剧本策划') {
  5811. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5812. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5813. // 确认对话名称唯一性
  5814. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5815. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5816. }
  5817. }else {
  5818. $anime_name = $user_anime_name;
  5819. }
  5820. $table_data = [
  5821. 'user_id' => $uid,
  5822. 'model' => $model,
  5823. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5824. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5825. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5826. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5827. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5828. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5829. 'art_style_type' => $input_art_style,
  5830. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5831. 'status' => '解析完成',
  5832. 'generate_status' => '待执行',
  5833. 'updated_at' => date('Y-m-d H:i:s')
  5834. ];
  5835. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5836. // 如果是修改集数,则将content内容更新(会改变原文)
  5837. if (isset($episode_count) && $episode_count > 0) {
  5838. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5839. $table_data['start_episode_sequence'] = 1;
  5840. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5841. }else {
  5842. // 如果需要生成原文内容,从script_arr中提取
  5843. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5844. $table_data['content'] = $script_arr['content'];
  5845. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5846. if (!$table_data['content']) {
  5847. yield [
  5848. 'type' => 'done',
  5849. 'script' => [],
  5850. 'episode' => [],
  5851. 'answer' => $fullContent,
  5852. 'reasoning' => $fullReasoningContent,
  5853. 'usage' => $usage,
  5854. 'error' => '未生成剧本内容,请调整提示词再试'
  5855. ];
  5856. return;
  5857. }
  5858. }
  5859. if (isset($table_data['content']) && $table_data['content']) {
  5860. $chapters = splitContent($table_data['content']);
  5861. $chapter_count = count($chapters);
  5862. if ($chapter_count > 0) {
  5863. $table_data['start_episode_sequence'] = 1;
  5864. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5865. }
  5866. }
  5867. }
  5868. $single_episode = [];
  5869. try {
  5870. DB::beginTransaction();
  5871. $now = date('Y-m-d H:i:s');
  5872. // 更新动漫大纲
  5873. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5874. if (!$boolen) {
  5875. dLog('deepseek')->info('对话修改失败', $table_data);
  5876. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5877. Utils::throwError('20003:对话修改失败');
  5878. }
  5879. // 保存对话记录
  5880. $records = [
  5881. [
  5882. 'uid' => $uid,
  5883. 'anime_id' => $anime_id,
  5884. 'sequence' => 0,
  5885. 'role' => 'user',
  5886. 'content' => $prompt,
  5887. 'created_at' => $now,
  5888. 'updated_at' => $now
  5889. ],
  5890. [
  5891. 'uid' => $uid,
  5892. 'anime_id' => $anime_id,
  5893. 'sequence' => 0,
  5894. 'role' => 'assistant',
  5895. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5896. 'content' => $fullContent,
  5897. 'created_at' => $now,
  5898. 'updated_at' => $now
  5899. ]
  5900. ];
  5901. // 保存对话记录
  5902. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5903. if (!$boolen3) {
  5904. Utils::throwError('20003:对话记录保存失败');
  5905. }
  5906. // 单剧集模式:生成并保存剧集信息
  5907. if ($is_single) {
  5908. $anime_name = getProp($anime, 'anime_name', '未命名');
  5909. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5910. if (empty($episode_arr['acts'])) {
  5911. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5912. }
  5913. $saveResult = $this->saveEpisodeVersionData(
  5914. $anime_id,
  5915. 1,
  5916. $episode_arr,
  5917. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5918. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5919. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5920. null,
  5921. null,
  5922. false,
  5923. $content,
  5924. $now
  5925. );
  5926. $single_episode = $saveResult['episode'];
  5927. $episode_id = $saveResult['episode_id'];
  5928. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5929. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5930. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5931. 'props' => json_encode($saveResult['merged_props'], 256),
  5932. 'updated_at' => $now
  5933. ]);
  5934. if ($boolen5 === false) {
  5935. Utils::throwError('20003:单剧集主表资源同步失败');
  5936. }
  5937. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5938. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5939. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5940. $episode_record_content = '确认分镜大纲';
  5941. if ($content !== '') {
  5942. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5943. }
  5944. $episode_records = [
  5945. [
  5946. 'uid' => $uid,
  5947. 'anime_id' => $anime_id,
  5948. 'role' => 'user',
  5949. 'content' => $episode_record_content,
  5950. 'sequence' => 1,
  5951. 'episode_id' => $episode_id,
  5952. 'created_at' => $now,
  5953. 'updated_at' => $now
  5954. ],
  5955. [
  5956. 'uid' => $uid,
  5957. 'anime_id' => $anime_id,
  5958. 'role' => 'assistant',
  5959. 'content' => $fullContent,
  5960. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5961. 'sequence' => 1,
  5962. 'episode_id' => $episode_id,
  5963. 'created_at' => $now,
  5964. 'updated_at' => $now
  5965. ]
  5966. ];
  5967. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5968. if (!$boolen4) {
  5969. Utils::throwError('20003:单剧集分镜记录保存失败');
  5970. }
  5971. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5972. if ($is_single && !empty($single_episode)) {
  5973. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5974. 'anime_id' => $anime_id,
  5975. 'episode_id' => $episode_id ?? 0,
  5976. 'model' => $model,
  5977. 'source' => 'reGenerateAnime',
  5978. ]);
  5979. }
  5980. }
  5981. }catch (\Exception $e) {
  5982. DB::rollBack();
  5983. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5984. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5985. yield [
  5986. 'type' => 'done',
  5987. 'answer' => $fullContent,
  5988. 'reasoning' => $fullReasoningContent,
  5989. 'usage' => $usage,
  5990. 'error' => $e->getMessage(),
  5991. ];
  5992. return;
  5993. }
  5994. DB::commit();
  5995. dLog('deepseek')->info('保存完毕');
  5996. if ($is_single && !empty($single_episode)) {
  5997. // $this->batchSetGlobalRoleImg([
  5998. // 'anime_id' => $anime_id,
  5999. // ]);
  6000. // $this->batchSetGlobalSceneImg([
  6001. // 'anime_id' => $anime_id,
  6002. // ]);
  6003. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6004. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6005. }
  6006. $table_data['anime_id'] = $anime_id;
  6007. $table_data['roles'] = json_decode($table_data['roles'], true);
  6008. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6009. unset($table_data['updated_at']);
  6010. unset($table_data['status']);
  6011. yield [
  6012. 'type' => 'done',
  6013. 'script' => $table_data,
  6014. 'episode' => $single_episode,
  6015. 'answer' => $fullContent,
  6016. 'reasoning' => $fullReasoningContent,
  6017. 'usage' => $usage
  6018. ];
  6019. }
  6020. public function chat($data) {
  6021. $uid = Site::getUid();
  6022. // 积分余额预检(不足直接报错)
  6023. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6024. $anime_id = getProp($data, 'anime_id');
  6025. $file = getProp($data, 'file');
  6026. $content = getProp($data, 'content', '');
  6027. $bid = getProp($data, 'bid', 0);
  6028. $script_id = getProp($data, 'script_id', 0);
  6029. $episode_number = getProp($data, 'episode_number', 1);
  6030. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6031. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6032. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6033. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6034. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6035. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6036. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6037. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6038. $roles = is_array($roles) ? $roles : [];
  6039. $scenes = is_array($scenes) ? $scenes : [];
  6040. // 获取最后一集序号
  6041. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6042. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6043. // 转换主体列表和场景列表的格式
  6044. // 获取参考主体或场景
  6045. if ((int)$episode_number === 1) {
  6046. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6047. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6048. }else {
  6049. $prev_episode_number = $episode_number - 1;
  6050. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6051. }
  6052. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6053. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6054. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6055. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6056. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6057. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6058. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6059. 中年女:邻居阿姨
  6060. 老年男:幽默大爷
  6061. 老年女:婆婆
  6062. 萌娃:奶气萌娃";
  6063. if ($roles_content) {
  6064. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6065. 主体范围:\n {$roles_content}\n
  6066. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6067. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6068. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6069. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6070. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6071. }else {
  6072. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6073. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6074. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6075. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6076. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6077. }
  6078. if ($scenes_content) {
  6079. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6080. 场景范围:\n {$scenes_content}\n
  6081. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6082. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6083. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6084. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6085. }else {
  6086. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6087. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6088. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6089. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6090. }
  6091. // 提取文件内容
  6092. if ($file) {
  6093. $uploaded_content = $this->extractFileContent($file);
  6094. if (!$uploaded_content) {
  6095. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6096. }
  6097. } elseif ($script_id) {
  6098. $uploaded_content = $this->getContentByScriptId($script_id);
  6099. if (!$uploaded_content) {
  6100. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6101. }
  6102. } elseif ($bid) {
  6103. $uploaded_content = $this->getContentByBid($bid);
  6104. if (!$uploaded_content) {
  6105. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6106. }
  6107. } elseif ($content) {
  6108. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6109. }
  6110. // elseif ($prompt) {
  6111. // $uploaded_content = filterContent($prompt);
  6112. // }
  6113. else {
  6114. $uploaded_content = '';
  6115. }
  6116. $input_art_style = getProp($anime, 'art_style');
  6117. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6118. // 美术风格
  6119. if (!$mappedArtStyle) {
  6120. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6121. }else {
  6122. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6123. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6124. }else {
  6125. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6126. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6127. }
  6128. }
  6129. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6130. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6131. // 强制要求:
  6132. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6133. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6134. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6135. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6136. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6137. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6138. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6139. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6140. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6141. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6142. // - 分镜要和场景列表、人物主体保持一致\n
  6143. // 普通要求:
  6144. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6145. // {$role_demo}
  6146. // {$scene_demo}
  6147. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6148. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6149. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6150. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6151. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6152. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6153. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6154. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6155. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6156. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6157. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6158. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6159. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6160. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6161. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6162. // 5.$mappedArtStyle_prompt\n\n
  6163. // 示例格式:\n
  6164. // 第1集:隐形的守护者
  6165. // ###故事梗概
  6166. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6167. // ###美术风格
  6168. // 基础画风风格词:韩漫二次元
  6169. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6170. // ###主体列表
  6171. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6172. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6173. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6174. // ###场景列表
  6175. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6176. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6177. // 无人物。}
  6178. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6179. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6180. // 无人物。}
  6181. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6182. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6183. // 无人物。}
  6184. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6185. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6186. // 无人物。}
  6187. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6188. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6189. // 无人物。}
  6190. // ###分镜剧本
  6191. // ##第1幕:徐家老旧厨房 白天 室内
  6192. // 分镜1
  6193. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6194. // 场景:徐家老旧厨房
  6195. // 构图设计:全景,低角度仰视
  6196. // 运镜调度:手持拍摄
  6197. // 配音角色:旁白
  6198. // 出镜角色:许芸-校服装、徐母
  6199. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6200. // 画面类型:普通画面
  6201. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6202. // 分镜2
  6203. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6204. // 场景:徐家老旧厨房
  6205. // 构图设计:近景,徐母面部特写
  6206. // 运镜调度:固定镜头
  6207. // 配音角色:徐母
  6208. // 出镜角色:徐母
  6209. // 台词内容:问我夜不归宿死哪儿去了。
  6210. // 画面类型:对口型
  6211. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6212. // ##第2幕:徐家简陋客厅 黄昏 室内
  6213. // 分镜3
  6214. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6215. // 场景:徐家简陋客厅
  6216. // 构图设计:全景,景深虚化
  6217. // 运镜调度:固定镜头
  6218. // 配音角色:旁白
  6219. // 出镜角色:无
  6220. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6221. // 画面类型:普通画面
  6222. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6223. // 分镜4
  6224. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6225. // 场景:徐家简陋客厅
  6226. // 构图设计:特写,火车票
  6227. // 运镜调度:固定镜头
  6228. // 配音角色:旁白
  6229. // 出镜角色:无
  6230. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6231. // 画面类型:普通画面
  6232. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6233. // \n\n";
  6234. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6235. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6236. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6237. 普通要求:
  6238. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6239. {$role_demo}
  6240. {$scene_demo}
  6241. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6242. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6243. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6244. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6245. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6246. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6247. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6248. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6249. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6250. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6251. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6252. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6253. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6254. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6255. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6256. 5.$mappedArtStyle_prompt
  6257. 6.《情绪-视听语言映射表》:
  6258. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6259. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6260. -----|---------|------------|----------------
  6261. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6262. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6263. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6264. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6265. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6266. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6267. -----|---------|------------|----------------
  6268. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6269. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6270. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6271. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6272. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6273. --------|---------|--------------|-------------
  6274. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6275. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6276. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6277. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6278. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6279. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6280. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6281. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6282. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6283. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6284. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6285. -----|---------|------------|------------
  6286. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6287. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6288. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6289. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6290. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6291. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6292. --------|---------|--------------|----------
  6293. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6294. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6295. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6296. 6.6 声音设计与潜意识影响 (Soundscape)
  6297. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6298. -----|---------|------------|------------------
  6299. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6300. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6301. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6302. 理论基石:
  6303. - The Five C's of Cinematography by Joseph V. Mascelli
  6304. - Film Art: An Introduction by David Bordwell
  6305. - Sight, Sound, Motion by Herbert Zettl
  6306. - Notes on the Cinematograph by Robert Bresson
  6307. \n\n
  6308. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6309. 示例格式:\n
  6310. 第1集:隐形的守护者
  6311. ###故事梗概
  6312. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6313. ###美术风格
  6314. 基础画风风格词:韩漫二次元
  6315. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6316. ###主体列表
  6317. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6318. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6319. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6320. ###场景列表
  6321. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6322. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6323. 无人物。}
  6324. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6325. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6326. 无人物。}
  6327. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6328. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6329. 无人物。}
  6330. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6331. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6332. 无人物。}
  6333. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6334. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6335. 无人物。}
  6336. ###分镜剧本
  6337. ##第1幕:徐家老旧厨房 白天 室内
  6338. 分镜1
  6339. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6340. 场景:徐家老旧厨房
  6341. 构图设计:全景,低角度仰视
  6342. 运镜调度:手持拍摄
  6343. 配音角色:旁白
  6344. 出镜角色:许芸-校服装、徐母
  6345. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6346. 画面类型:普通画面
  6347. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6348. 分镜2
  6349. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6350. 场景:徐家老旧厨房
  6351. 构图设计:近景,徐母面部特写
  6352. 运镜调度:固定镜头
  6353. 配音角色:徐母
  6354. 出镜角色:徐母
  6355. 台词内容:问我夜不归宿死哪儿去了。
  6356. 画面类型:对口型
  6357. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6358. ##第2幕:徐家简陋客厅 黄昏 室内
  6359. 分镜3
  6360. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6361. 场景:徐家简陋客厅
  6362. 构图设计:全景,景深虚化
  6363. 运镜调度:固定镜头
  6364. 配音角色:旁白
  6365. 出镜角色:无
  6366. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6367. 画面类型:普通画面
  6368. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6369. 分镜4
  6370. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6371. 场景:徐家简陋客厅
  6372. 构图设计:特写,火车票
  6373. 运镜调度:固定镜头
  6374. 配音角色:旁白
  6375. 出镜角色:无
  6376. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6377. 画面类型:普通画面
  6378. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6379. \n\n";
  6380. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6381. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6382. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6383. $prompt = $origin_prompt;
  6384. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6385. // 获取章节内容
  6386. $full_content = getProp($anime, 'content');
  6387. if ($uploaded_content) {
  6388. $full_content = $uploaded_content;
  6389. }
  6390. // 根据章节内容拆分章节
  6391. $chapters = splitContent($full_content);
  6392. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6393. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6394. $messages = [];
  6395. if ($prompt == '确认分镜大纲') {
  6396. // 暂时保留
  6397. $content = $chapter_content;
  6398. if ($is_single) $content = $full_content; // 单剧集使用全文
  6399. if (!$content) {
  6400. Utils::throwError('20003:章节内容无法获取,请确认');
  6401. }
  6402. $question = $is_single
  6403. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6404. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6405. // 构建消息
  6406. $messages[] =
  6407. [
  6408. 'role' => 'user',
  6409. 'content' => $question
  6410. ];
  6411. }else if ($prompt == '继续策划下一集') {
  6412. if ($is_single) {
  6413. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6414. }
  6415. $content = $chapter_content;
  6416. if (!$content) {
  6417. Utils::throwError('20003:章节内容无法获取,请确认');
  6418. }
  6419. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6420. // 获取上一集最后记录
  6421. $prev_sequence = $episode_number - 1;
  6422. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6423. // 构建消息
  6424. $messages[] =
  6425. [
  6426. 'role' => 'user',
  6427. 'content' => $question
  6428. ];
  6429. }else {
  6430. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6431. if (!$content) {
  6432. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6433. }
  6434. if (!$content) {
  6435. Utils::throwError('20003:章节内容无法获取,请确认');
  6436. }
  6437. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6438. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6439. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6440. if ($origin_prompt) {
  6441. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6442. }
  6443. $messages[] =
  6444. [
  6445. 'role' => 'user',
  6446. 'content' => $question
  6447. ];
  6448. }
  6449. // 处理文本模型
  6450. $model = getProp($data, 'model');
  6451. if (!$model) {
  6452. // 用户没有输入,从anime表获取
  6453. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6454. $model = getProp($anime, 'model');
  6455. if (!$model) {
  6456. // anime表也没有,使用默认值
  6457. $model = 'doubao-seed-2-0-mini-260215';
  6458. }
  6459. }
  6460. // 验证模型是否在可用模型表中
  6461. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6462. $model = 'doubao-seed-2-0-mini-260215';
  6463. }
  6464. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6465. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6466. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6467. if ($model === 'deepseek-chat') {
  6468. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6469. $model = 'deepseek-v4-flash';
  6470. $thinkingMode = 'disabled';
  6471. } elseif ($model === 'deepseek-reasoner') {
  6472. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6473. $model = 'deepseek-v4-flash';
  6474. $thinkingMode = 'enabled';
  6475. }
  6476. $post_data = [
  6477. 'model' => $model,
  6478. 'messages' => $messages,
  6479. // 'max_tokens' => 8192,
  6480. 'temperature' => 0.2,
  6481. 'frequency_penalty' => 0,
  6482. 'presence_penalty' => 0,
  6483. 'response_format' => ['type' => 'text'],
  6484. 'thinking' => ['type' => $thinkingMode],
  6485. 'stream' => true // 启用流式输出
  6486. ];
  6487. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6488. // 根据模型类型选择调用方法
  6489. $fullContent = '';
  6490. $fullReasoningContent = '';
  6491. $usage = [];
  6492. try {
  6493. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6494. // DeepSeek 官方模型使用 DeepSeek API
  6495. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6496. } else if (in_array($model, $this->gpt_text_models)) {
  6497. // GPT-5.4 模型使用 TokenRouter API
  6498. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6499. } else if (in_array($model, $this->gemini_text_models)) {
  6500. // Gemini 模型使用 Gemini API
  6501. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6502. } else {
  6503. // 其他模型使用火山引擎API
  6504. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6505. }
  6506. // 验证返回值类型
  6507. if (!is_iterable($streamGenerator)) {
  6508. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6509. dLog('deepseek')->error('chat流式生成器无效', [
  6510. 'generator_type' => $errorType,
  6511. 'model' => $model,
  6512. 'anime_id' => $anime_id,
  6513. 'episode_number' => $episode_number
  6514. ]);
  6515. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6516. 'type' => $errorType,
  6517. 'model' => $model
  6518. ]);
  6519. yield [
  6520. 'type' => 'error',
  6521. 'episode' => [],
  6522. 'answer' => '',
  6523. 'reasoning' => '',
  6524. 'usage' => [],
  6525. 'error' => '接口返回数据异常,请重新请求'
  6526. ];
  6527. return;
  6528. }
  6529. // 处理流式输出
  6530. foreach ($streamGenerator as $chunk) {
  6531. if (isset($chunk['type'])) {
  6532. if ($chunk['type'] === 'done') {
  6533. // 最终结果
  6534. $fullContent = $chunk['full_content'];
  6535. $fullReasoningContent = $chunk['full_reasoning'];
  6536. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6537. } else {
  6538. // 逐块yield数据
  6539. yield $chunk;
  6540. }
  6541. }
  6542. }
  6543. } catch (\Exception $e) {
  6544. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6545. 'model' => $model,
  6546. 'anime_id' => $anime_id,
  6547. 'episode_number' => $episode_number,
  6548. 'trace' => $e->getTraceAsString()
  6549. ]);
  6550. logDB('deepseek', 'error', 'chat流式处理失败', [
  6551. 'error' => $e->getMessage(),
  6552. 'model' => $model
  6553. ]);
  6554. yield [
  6555. 'type' => 'error',
  6556. 'episode' => [],
  6557. 'answer' => '',
  6558. 'reasoning' => '',
  6559. 'usage' => [],
  6560. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6561. ];
  6562. return;
  6563. }
  6564. dLog('deepseek')->info('完整内容: '.$fullContent);
  6565. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6566. // 处理完整内容并返回最终结果
  6567. $episode_arr = handleEpisodeContent($fullContent);
  6568. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6569. if (empty($episode_arr['acts'])) {
  6570. // 未生成剧本相关内容,保存对话记录并返回提示
  6571. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6572. try {
  6573. $now = date('Y-m-d H:i:s');
  6574. // 保存对话记录
  6575. $records = [
  6576. [
  6577. 'uid' => $uid,
  6578. 'anime_id' => $anime_id,
  6579. 'sequence' => $episode_number,
  6580. 'role' => 'user',
  6581. 'content' => $prompt,
  6582. 'created_at' => $now,
  6583. 'updated_at' => $now
  6584. ],
  6585. [
  6586. 'uid' => $uid,
  6587. 'anime_id' => $anime_id,
  6588. 'sequence' => $episode_number,
  6589. 'role' => 'assistant',
  6590. 'content' => $fullContent,
  6591. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6592. 'created_at' => $now,
  6593. 'updated_at' => $now
  6594. ]
  6595. ];
  6596. DB::table('mp_anime_records')->insert($records);
  6597. } catch (\Exception $e) {
  6598. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6599. }
  6600. yield [
  6601. 'type' => 'done',
  6602. 'episode' => [],
  6603. 'answer' => $fullContent,
  6604. 'reasoning' => $fullReasoningContent,
  6605. 'usage' => $usage,
  6606. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6607. ];
  6608. return;
  6609. }
  6610. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6611. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6612. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6613. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6614. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6615. $existing_props = is_array($existing_props) ? $existing_props : [];
  6616. $now = date('Y-m-d H:i:s');
  6617. try {
  6618. DB::beginTransaction();
  6619. $saveResult = $this->saveEpisodeVersionData(
  6620. $anime_id,
  6621. $episode_number,
  6622. $episode_arr,
  6623. $existing_roles,
  6624. $existing_scenes,
  6625. $existing_props,
  6626. $current_episode,
  6627. $base_episode,
  6628. $is_regenerate_version,
  6629. $content,
  6630. $now
  6631. );
  6632. $episode = $saveResult['episode'];
  6633. $episode_id = $saveResult['episode_id'];
  6634. $merged_roles = $saveResult['merged_roles'];
  6635. $merged_scenes = $saveResult['merged_scenes'];
  6636. $merged_props = $saveResult['merged_props'];
  6637. $record_content = $origin_prompt;
  6638. if ($uploaded_content !== '') {
  6639. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6640. }
  6641. $records = [
  6642. [
  6643. 'uid' => $uid,
  6644. 'anime_id' => $anime_id,
  6645. 'role' => 'user',
  6646. 'content' => $record_content,
  6647. 'sequence' => $episode_number,
  6648. 'episode_id' => $episode_id,
  6649. 'created_at' => $now,
  6650. 'updated_at' => $now
  6651. ],
  6652. [
  6653. 'uid' => $uid,
  6654. 'anime_id' => $anime_id,
  6655. 'role' => 'assistant',
  6656. 'content' => $fullContent,
  6657. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6658. 'sequence' => $episode_number,
  6659. 'episode_id' => $episode_id,
  6660. 'created_at' => $now,
  6661. 'updated_at' => $now
  6662. ]
  6663. ];
  6664. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6665. if (!$boolen4) {
  6666. Utils::throwError('20003:对话记录保存失败');
  6667. }
  6668. // 保存模型和内容到anime表
  6669. $update_anime_data = [
  6670. 'model' => $model,
  6671. 'updated_at' => $now
  6672. ];
  6673. if ($uploaded_content) {
  6674. $update_anime_data['content'] = $uploaded_content;
  6675. }
  6676. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6677. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6678. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6679. 'anime_id' => $anime_id,
  6680. 'episode_number' => $episode_number,
  6681. 'model' => $model,
  6682. 'source' => 'chat',
  6683. ]);
  6684. }catch (\Exception $e) {
  6685. DB::rollBack();
  6686. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6687. yield [
  6688. 'type' => 'done',
  6689. 'answer' => $fullContent,
  6690. 'reasoning' => $fullReasoningContent,
  6691. 'usage' => $usage,
  6692. 'error' => $e->getMessage(),
  6693. ];
  6694. return;
  6695. }
  6696. DB::commit();
  6697. if ($is_global_generate_pics) {
  6698. // // 批量生成全局角色图片
  6699. // $this->batchSetGlobalRoleImg([
  6700. // 'anime_id' => $anime_id,
  6701. // ], true);
  6702. // // 批量生成全局场景图片
  6703. // $this->batchSetGlobalSceneImg([
  6704. // 'anime_id' => $anime_id,
  6705. // ], true);
  6706. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6707. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6708. }
  6709. $episode['episode_id'] = $episode_id;
  6710. $episode['roles'] = $merged_roles;
  6711. $episode['scenes'] = $merged_scenes;
  6712. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6713. yield [
  6714. 'type' => 'done',
  6715. 'episode' => $episode,
  6716. 'answer' => $fullContent,
  6717. 'reasoning' => $fullReasoningContent,
  6718. 'usage' => $usage
  6719. ];
  6720. }
  6721. public function addChatForAce($data) {
  6722. $uid = Site::getUid();
  6723. $anime_id = getProp($data, 'anime_id');
  6724. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6725. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6726. if (!$anime) Utils::throwError('20003:对话不存在');
  6727. $file = getProp($data, 'file');
  6728. $content = getProp($data, 'content', '');
  6729. $bid = getProp($data, 'bid', 0);
  6730. $script_id = getProp($data, 'script_id', 0);
  6731. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6732. $prompt = getProp($data, 'prompt');
  6733. $is_multi = getProp($anime, 'is_multi');
  6734. $is_single = (int)$is_multi !== 1;
  6735. // 积分余额预检(仅单剧集模式收费)
  6736. if ($is_single) {
  6737. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6738. }
  6739. $extra_products = getProp($data, 'products', []);
  6740. if (!$extra_products) {
  6741. $extra_products = getProp($anime, 'extra_products');
  6742. if ($extra_products) {
  6743. $extra_products = json_decode($extra_products, true);
  6744. }else {
  6745. $extra_products = [];
  6746. }
  6747. }else {
  6748. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6749. }
  6750. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6751. $anime_script_id = getProp($anime, 'script_id');
  6752. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6753. $cpid = Site::getCpid();
  6754. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6755. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6756. ->where('mapping.script_id', $anime_script_id)
  6757. ->where('product.cpid', $cpid)
  6758. ->where('product.is_deleted', 0);
  6759. $mappings = $script_products_mappings->select(
  6760. 'mapping.product_id',
  6761. 'mapping.episode_number',
  6762. 'product.product_name',
  6763. 'product.type',
  6764. 'product.product',
  6765. 'product.pic_prompt',
  6766. 'product.url',
  6767. 'product.pic_task_id',
  6768. 'product.pic_task_status',
  6769. 'product.three_view_image_url'
  6770. )
  6771. ->get();
  6772. // 按 product_id 分组,合并 episode_number
  6773. $productMap = [];
  6774. foreach ($mappings as $item) {
  6775. $product_id = $item->product_id;
  6776. $product_name = $item->product_name;
  6777. // 处理product_name两边的符号
  6778. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6779. if (!isset($productMap[$product_id])) {
  6780. $productMap[$product_id] = [
  6781. 'product_id' => $product_id,
  6782. 'product_name' => $product_name,
  6783. 'type' => (int)$item->type,
  6784. 'product' => (int)$item->product,
  6785. 'pic_prompt' => $item->pic_prompt,
  6786. 'url' => $item->url,
  6787. 'pic_task_id' => $item->pic_task_id,
  6788. 'pic_task_status' => $item->pic_task_status,
  6789. 'episode_numbers' => [],
  6790. ];
  6791. }
  6792. // 添加 episode_number(去重)
  6793. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6794. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6795. }
  6796. }
  6797. // 将查询到的剧本资产合并到extra_products中
  6798. // 先构建extra_products的索引(以product_id为key,用于去重)
  6799. $extraProductsMap = [];
  6800. foreach ($extra_products as $item) {
  6801. $key = getProp($item, 'product_id');
  6802. if ($key) {
  6803. $extraProductsMap[$key] = $item;
  6804. }
  6805. }
  6806. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6807. foreach ($productMap as $product) {
  6808. $product_id = $product['product_id'];
  6809. // 如果不存在则添加(不带episode_number信息)
  6810. if (!isset($extraProductsMap[$product_id])) {
  6811. $extraProductsMap[$product_id] = [
  6812. 'product_id' => $product['product_id'],
  6813. 'product_name' => $product['product_name'],
  6814. 'type' => $product['type'],
  6815. 'product' => $product['product'],
  6816. 'pic_prompt' => $product['pic_prompt'],
  6817. 'url' => $product['url'],
  6818. 'pic_task_id' => $product['pic_task_id'],
  6819. 'pic_task_status' => $product['pic_task_status'],
  6820. ];
  6821. }
  6822. }
  6823. // 重新赋值给extra_products
  6824. $extra_products = array_values($extraProductsMap);
  6825. }
  6826. $user_anime_name = getProp($anime, 'anime_name');
  6827. // 处理提示词
  6828. if ($prompt && $extra_products) {
  6829. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6830. foreach($extra_products as $item) {
  6831. $product_name = getProp($item, 'product_name');
  6832. if ($product_name) {
  6833. // 替换 {product_name} 为 product_name
  6834. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6835. }
  6836. }
  6837. }
  6838. // 处理文本模型
  6839. $model = getProp($data, 'model');
  6840. if (!$model) {
  6841. // 用户没有输入,从anime表获取
  6842. $model = getProp($anime, 'model');
  6843. if (!$model) {
  6844. // anime表也没有,使用默认值
  6845. $model = 'deepseek-v4-pro';
  6846. }
  6847. }
  6848. // 验证模型是否在可用模型表中
  6849. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6850. $model = 'deepseek-v4-pro';
  6851. }
  6852. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6853. if ($prompt) {
  6854. $question .= "本次修改要求如下:\n{$prompt}";
  6855. }
  6856. // if (!$file && !$content && !$bid) {
  6857. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6858. // }
  6859. // 提取文件内容
  6860. if ($file) {
  6861. $content = $this->extractFileContent($file);
  6862. if (!$content) {
  6863. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6864. }
  6865. } elseif ($script_id) {
  6866. $content = $this->getContentByScriptId($script_id);
  6867. if (!$content) {
  6868. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6869. }
  6870. } elseif ($bid) {
  6871. $content = $this->getContentByBid($bid);
  6872. if (!$content) {
  6873. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6874. }
  6875. } elseif ($content) {
  6876. $content = filterContent($content);
  6877. } else {
  6878. $content = getProp($anime, 'content');
  6879. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6880. $need_generate_content = true;
  6881. }
  6882. }
  6883. // 美术风格
  6884. $input_art_style = getProp($data, 'art_style');
  6885. if (!$input_art_style) {
  6886. $mappedArtStyle = getProp($anime, 'art_style');
  6887. }else {
  6888. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6889. }
  6890. // 判断是否需要生成原文内容
  6891. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6892. // 如果需要生成原文内容,添加额外的要求
  6893. $content_generation_requirement = $need_generate_content
  6894. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6895. : "";
  6896. // 美术风格
  6897. if (!$mappedArtStyle) {
  6898. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6899. }else {
  6900. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6901. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6902. }else {
  6903. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6904. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6905. }
  6906. }
  6907. // 构建主体、场景和道具提示词
  6908. $extra_role_prompt = "\n";
  6909. $extra_scene_prompt = "\n";
  6910. $extra_prop_prompt = "\n";
  6911. $ref_products = []; // 参考资产
  6912. if ($extra_products) {
  6913. foreach($extra_products as $item) {
  6914. $product = getProp($item, 'product');
  6915. $product_name = getProp($item, 'product_name');
  6916. if ($product_name == '旁白') continue;
  6917. $ref_products[$product_name] = $item;
  6918. $pic_prompt = getProp($item, 'pic_prompt');
  6919. if ((int)$product === 1) {
  6920. // 拼接角色信息
  6921. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6922. } elseif ((int)$product === 2) {
  6923. // 拼接场景信息
  6924. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6925. } elseif ((int)$product === 3) {
  6926. // 拼接道具信息
  6927. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6928. }
  6929. }
  6930. // 优化提示词,融入剧本
  6931. if (!empty(trim($extra_role_prompt))) {
  6932. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6933. }
  6934. if (!empty(trim($extra_scene_prompt))) {
  6935. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6936. }
  6937. if (!empty(trim($extra_prop_prompt))) {
  6938. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6939. }
  6940. }
  6941. if ($anime_script_id && $is_single) {
  6942. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6943. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6944. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6945. }else {
  6946. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6947. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6948. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6949. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6950. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6951. {$extra_role_prompt}";
  6952. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6953. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6954. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6955. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6956. {$extra_scene_prompt}";
  6957. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6958. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6959. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6960. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6961. {$extra_prop_prompt}";
  6962. }
  6963. $systemPrompt = $is_single
  6964. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6965. 强制要求:
  6966. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6967. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6968. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6969. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6970. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6971. 普通要求:
  6972. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6973. $role_demo
  6974. $scene_demo
  6975. $prop_demo
  6976. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6977. 5.1片段分割逻辑(优先级从高到低):
  6978. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6979. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6980. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6981. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6982. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6983. - 片段数量格式为: 片段数量:8
  6984. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6985. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6986. 5.3分镜结构:每个分镜包含以下字段:
  6987. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6988. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6989. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6990. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6991. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6992. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6993. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6994. - 运镜:场景+画面描述+运镜
  6995. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6996. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6997. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6998. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6999. 6.{$mappedArtStyle_prompt}\n\n
  7000. 示例如下:\n
  7001. ###剧本名:西昆仑
  7002. ###故事梗概
  7003. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7004. ###剧本亮点
  7005. 亮点1:绝境奇药,生死一线
  7006. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7007. 亮点2:结拜兄妹,化解尴尬
  7008. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7009. 亮点3:纤发夺命,情愫暗涌
  7010. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7011. ###人物关系
  7012. 阿雪与梁萧之间存在兄妹之情。
  7013. ###核心矛盾
  7014. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7015. ###主体列表
  7016. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7017. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7018. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7019. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7020. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7021. 全景,正面拍摄,青年女性,亚洲人。
  7022. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7023. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7024. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7025. ###美术风格
  7026. 基础画风风格词:厚涂古风
  7027. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7028. ###场景列表
  7029. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7030. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7031. 无人物。}
  7032. ###分段剧本
  7033. 片段数量:8
  7034. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7035. ##片段1
  7036. 时长:12s
  7037. 分镜1
  7038. 出场角色:刀疤脸
  7039. 场景:边境小镇街道
  7040. 出场道具:酒杯-高脚杯
  7041. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7042. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7043. 配音台词:
  7044. 背景音效:
  7045. 分镜2
  7046. 出场角色:刀疤脸
  7047. 场景:悦来酒馆
  7048. 出场道具:酒杯-高脚杯
  7049. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7050. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7051. 配音台词:
  7052. 背景音效:
  7053. 分镜3
  7054. 出场角色:刀疤脸
  7055. 场景:悦来酒馆
  7056. 出场道具:酒杯-高脚杯
  7057. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7058. 运镜:从中景推向令牌特写。
  7059. 配音台词:
  7060. 背景音效:
  7061. 分镜4
  7062. 出场角色:刀疤脸
  7063. 场景:悦来酒馆
  7064. 出场道具:酒杯-高脚杯
  7065. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7066. 运镜:极速推向酒水溅起的瞬间。
  7067. 配音台词:
  7068. 背景音效:
  7069. 分镜5
  7070. 出场角色:刀疤脸
  7071. 场景:悦来酒馆
  7072. 出场道具:酒杯-高脚杯
  7073. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7074. 运镜:固定机位,利用倾斜构图制造压迫感。
  7075. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7076. 背景音效:
  7077. \n\n"
  7078. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7079. 强制要求:\n
  7080. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7081. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7082. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7083. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7084. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7085. 普通要求:\n
  7086. 1.剧本名(必须生成)必须与文档内容高度相关
  7087. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7088. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7089. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7090. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7091. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7092. {$extra_role_prompt}
  7093. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7094. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7095. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7096. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7097. {$extra_scene_prompt}
  7098. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7099. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7100. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7101. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7102. {$extra_prop_prompt}
  7103. 5.{$mappedArtStyle_prompt}\n\n
  7104. 示例如下:\n
  7105. ###剧本名:西昆仑
  7106. ###故事梗概
  7107. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7108. ###剧本亮点
  7109. 亮点1:绝境奇药,生死一线
  7110. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7111. 亮点2:结拜兄妹,化解尴尬
  7112. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7113. 亮点3:纤发夺命,情愫暗涌
  7114. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7115. ###人物关系
  7116. 阿雪与梁萧之间存在兄妹之情。
  7117. ###核心矛盾
  7118. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7119. ###主体列表
  7120. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7121. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7122. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7123. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7124. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7125. 全景,正面拍摄,青年女性,亚洲人。
  7126. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7127. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7128. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7129. ###美术风格
  7130. 基础画风风格词:厚涂古风
  7131. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7132. ###场景列表
  7133. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7134. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7135. 无人物。}
  7136. ###道具列表
  7137. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7138. // 构建消息
  7139. $messages = [
  7140. [
  7141. 'role' => 'system',
  7142. 'content' => $systemPrompt
  7143. ],
  7144. [
  7145. 'role' => 'user',
  7146. 'content' => "以下是文档内容:
  7147. {$content}
  7148. 用户问题:
  7149. {$question}"
  7150. ]
  7151. ];
  7152. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7153. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7154. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7155. if ($model === 'deepseek-chat') {
  7156. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7157. $model = 'deepseek-v4-flash';
  7158. $thinkingMode = 'disabled';
  7159. } elseif ($model === 'deepseek-reasoner') {
  7160. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7161. $model = 'deepseek-v4-flash';
  7162. $thinkingMode = 'enabled';
  7163. }
  7164. $post_data = [
  7165. 'model' => $model,
  7166. 'messages' => $messages,
  7167. // 'max_tokens' => 8192,
  7168. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7169. 'frequency_penalty' => 0,
  7170. 'presence_penalty' => 0,
  7171. 'response_format' => ['type' => 'text'],
  7172. 'thinking' => ['type'=>$thinkingMode],
  7173. 'stream' => true // 启用流式输出
  7174. ];
  7175. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7176. // 根据模型类型选择调用方法
  7177. $fullContent = '';
  7178. $fullReasoningContent = '';
  7179. $usage = [];
  7180. try {
  7181. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7182. // DeepSeek 官方模型使用 DeepSeek API
  7183. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7184. } else if (in_array($model, $this->gpt_text_models)) {
  7185. // GPT-5.4 模型使用 TokenRouter API
  7186. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7187. } else if (in_array($model, $this->gemini_text_models)) {
  7188. // Gemini 模型使用 Gemini API
  7189. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7190. } else {
  7191. // 其他模型使用火山引擎API
  7192. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7193. }
  7194. // 验证返回值类型
  7195. if (!is_iterable($streamGenerator)) {
  7196. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7197. dLog('deepseek')->error('addChat流式生成器无效', [
  7198. 'generator_type' => $errorType,
  7199. 'model' => $model,
  7200. 'anime_id' => $anime_id
  7201. ]);
  7202. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7203. 'type' => $errorType,
  7204. 'model' => $model
  7205. ]);
  7206. yield [
  7207. 'type' => 'error',
  7208. 'script' => [],
  7209. 'episode' => [],
  7210. 'answer' => '',
  7211. 'reasoning' => '',
  7212. 'usage' => [],
  7213. 'error' => '接口返回数据异常,请重新请求'
  7214. ];
  7215. return;
  7216. }
  7217. // 处理流式输出
  7218. foreach ($streamGenerator as $chunk) {
  7219. if (isset($chunk['type'])) {
  7220. if ($chunk['type'] === 'done') {
  7221. // 最终结果
  7222. $fullContent = $chunk['full_content'];
  7223. $fullReasoningContent = $chunk['full_reasoning'];
  7224. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7225. } else {
  7226. // 逐块yield数据
  7227. yield $chunk;
  7228. }
  7229. }
  7230. }
  7231. } catch (\Exception $e) {
  7232. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7233. 'model' => $model,
  7234. 'anime_id' => $anime_id,
  7235. 'trace' => $e->getTraceAsString()
  7236. ]);
  7237. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7238. 'error' => $e->getMessage(),
  7239. 'model' => $model
  7240. ]);
  7241. yield [
  7242. 'type' => 'error',
  7243. 'script' => [],
  7244. 'episode' => [],
  7245. 'answer' => '',
  7246. 'reasoning' => '',
  7247. 'usage' => [],
  7248. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7249. ];
  7250. return;
  7251. }
  7252. dLog('deepseek')->info('完整内容: '.$fullContent);
  7253. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7254. // 处理完整内容并返回最终结果
  7255. $script_arr = [];
  7256. if ($fullContent) {
  7257. $script_arr = handleScriptContentForAce($fullContent);
  7258. dLog('deepseek')->info('解析内容', $script_arr);
  7259. logDB('deepseek', 'info', '解析内容', $script_arr);
  7260. }
  7261. if (empty($script_arr['roles'])) {
  7262. // 未生成剧本相关内容,保存对话记录并返回提示
  7263. dLog('deepseek')->info('未生成剧本相关的内容');
  7264. try {
  7265. DB::beginTransaction();
  7266. $now = date('Y-m-d H:i:s');
  7267. // 保存对话记录
  7268. $records = [
  7269. [
  7270. 'uid' => $uid,
  7271. 'anime_id' => $anime_id,
  7272. 'sequence' => 0,
  7273. 'role' => 'user',
  7274. 'content' => $prompt,
  7275. 'created_at' => $now,
  7276. 'updated_at' => $now
  7277. ],
  7278. [
  7279. 'uid' => $uid,
  7280. 'anime_id' => $anime_id,
  7281. 'sequence' => 0,
  7282. 'role' => 'assistant',
  7283. // 'content' => $fullContent,
  7284. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7285. 'created_at' => $now,
  7286. 'updated_at' => $now
  7287. ]
  7288. ];
  7289. DB::table('mp_anime_records')->insert($records);
  7290. DB::commit();
  7291. } catch (\Exception $e) {
  7292. DB::rollBack();
  7293. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7294. }
  7295. yield [
  7296. 'type' => 'done',
  7297. 'script' => [],
  7298. 'episode' => [],
  7299. 'answer' => $fullContent,
  7300. 'reasoning' => $fullReasoningContent,
  7301. 'usage' => $usage,
  7302. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7303. ];
  7304. return;
  7305. }
  7306. // 如果需要生成原文内容,从script_arr中提取
  7307. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7308. $content = $script_arr['content'];
  7309. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7310. if (!$content) {
  7311. yield [
  7312. 'type' => 'done',
  7313. 'script' => [],
  7314. 'episode' => [],
  7315. 'answer' => $fullContent,
  7316. 'reasoning' => $fullReasoningContent,
  7317. 'usage' => $usage,
  7318. 'error' => '未生成剧本内容,请调整提示词再试'
  7319. ];
  7320. return;
  7321. }
  7322. }
  7323. // 替换美术风格
  7324. if ($mappedArtStyle !== '') {
  7325. $script_arr['art_style'] = $mappedArtStyle;
  7326. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7327. }
  7328. // 新建动漫
  7329. if ($user_anime_name == '新剧本策划') {
  7330. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7331. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7332. // if (!$anime_name) {
  7333. // // 未识别到剧本名,保存对话记录并返回提示
  7334. // dLog('deepseek')->info('未能识别到剧本名称');
  7335. // try {
  7336. // DB::beginTransaction();
  7337. // $now = date('Y-m-d H:i:s');
  7338. // // 保存对话记录
  7339. // $records = [
  7340. // [
  7341. // 'uid' => $uid,
  7342. // 'anime_id' => $anime_id,
  7343. // 'sequence' => 0,
  7344. // 'role' => 'user',
  7345. // 'content' => $prompt,
  7346. // 'created_at' => $now,
  7347. // 'updated_at' => $now
  7348. // ],
  7349. // [
  7350. // 'uid' => $uid,
  7351. // 'anime_id' => $anime_id,
  7352. // 'sequence' => 0,
  7353. // 'role' => 'assistant',
  7354. // 'content' => '未能生成剧本名称,请重试',
  7355. // 'created_at' => $now,
  7356. // 'updated_at' => $now
  7357. // ]
  7358. // ];
  7359. // DB::table('mp_anime_records')->insert($records);
  7360. // DB::commit();
  7361. // } catch (\Exception $e) {
  7362. // DB::rollBack();
  7363. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7364. // }
  7365. // yield [
  7366. // 'type' => 'done',
  7367. // 'script' => [],
  7368. // 'episode' => [],
  7369. // 'answer' => $fullContent,
  7370. // 'reasoning' => $fullReasoningContent,
  7371. // 'usage' => $usage,
  7372. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7373. // ];
  7374. // return;
  7375. // }
  7376. // 确认对话名称唯一性
  7377. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7378. $anime_name = $anime_name . '_' . date('YmdHis');
  7379. }
  7380. }else {
  7381. $anime_name = $user_anime_name;
  7382. }
  7383. $table_data = [
  7384. 'user_id' => $uid,
  7385. 'anime_name' => $anime_name,
  7386. 'model' => $model,
  7387. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7388. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7389. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7390. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7391. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7392. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7393. 'art_style_type' => $input_art_style,
  7394. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7395. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7396. 'status' => '解析完成',
  7397. 'content' => $content,
  7398. 'is_multi' => $is_multi,
  7399. 'ace_mode' => $ace_mode,
  7400. 'generate_status' => '待执行',
  7401. 'updated_at' => date('Y-m-d H:i:s')
  7402. ];
  7403. if ($table_data['content']) {
  7404. $chapters = splitContent($table_data['content']);
  7405. $chapter_count = count($chapters);
  7406. if ($chapter_count > 0) {
  7407. $table_data['start_episode_sequence'] = 1;
  7408. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7409. }
  7410. }
  7411. if ($extra_products) {
  7412. $table_data['extra_products'] = json_encode($extra_products, 256);
  7413. }
  7414. // 如果有剧本ID则进行绑定
  7415. if ($script_id) {
  7416. $table_data['script_id'] = $script_id;
  7417. }
  7418. $single_episode = [];
  7419. try {
  7420. DB::beginTransaction();
  7421. $now = date('Y-m-d H:i:s');
  7422. // 更新动漫大纲
  7423. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7424. if (!$boolen) {
  7425. dLog('deepseek')->info('动漫保存失败', $table_data);
  7426. Utils::throwError('20003:动漫保存失败');
  7427. }
  7428. // 保存对话记录
  7429. $records = [
  7430. [
  7431. 'uid' => $uid,
  7432. 'anime_id' => $anime_id,
  7433. 'sequence' => 0,
  7434. 'role' => 'user',
  7435. 'content' => $prompt,
  7436. 'created_at' => date('Y-m-d H:i:s'),
  7437. 'updated_at' => date('Y-m-d H:i:s')
  7438. ],
  7439. [
  7440. 'uid' => $uid,
  7441. 'anime_id' => $anime_id,
  7442. 'sequence' => 0,
  7443. 'role' => 'assistant',
  7444. 'content' => $fullContent,
  7445. 'created_at' => date('Y-m-d H:i:s'),
  7446. 'updated_at' => date('Y-m-d H:i:s')
  7447. ]
  7448. ];
  7449. // 保存对话记录
  7450. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7451. if (!$boolen3) {
  7452. Utils::throwError('20003:对话记录保存失败');
  7453. }
  7454. if ($is_single) {
  7455. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7456. if (empty($episode_arr['acts'])) {
  7457. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7458. }
  7459. $saveResult = $this->saveEpisodeVersionData(
  7460. $anime_id,
  7461. 1,
  7462. $episode_arr,
  7463. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7464. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7465. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7466. null,
  7467. null,
  7468. false,
  7469. $content,
  7470. $now,
  7471. $ref_products
  7472. );
  7473. $single_episode = $saveResult['episode'];
  7474. $episode_id = $saveResult['episode_id'];
  7475. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7476. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7477. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7478. 'props' => json_encode($saveResult['merged_props'], 256),
  7479. 'updated_at' => $now
  7480. ]);
  7481. if ($boolen5 === false) {
  7482. Utils::throwError('20003:单剧集主表资源同步失败');
  7483. }
  7484. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7485. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7486. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7487. $episode_record_content = '确认分镜大纲';
  7488. if ($content !== '') {
  7489. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7490. }
  7491. $episode_records = [
  7492. [
  7493. 'uid' => $uid,
  7494. 'anime_id' => $anime_id,
  7495. 'role' => 'user',
  7496. 'content' => $episode_record_content,
  7497. 'sequence' => 1,
  7498. 'episode_id' => $episode_id,
  7499. 'created_at' => $now,
  7500. 'updated_at' => $now
  7501. ],
  7502. [
  7503. 'uid' => $uid,
  7504. 'anime_id' => $anime_id,
  7505. 'role' => 'assistant',
  7506. 'content' => $fullContent,
  7507. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7508. 'sequence' => 1,
  7509. 'episode_id' => $episode_id,
  7510. 'created_at' => $now,
  7511. 'updated_at' => $now
  7512. ]
  7513. ];
  7514. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7515. if (!$boolen4) {
  7516. Utils::throwError('20003:单剧集分镜记录保存失败');
  7517. }
  7518. }
  7519. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7520. if ($is_single && !empty($single_episode)) {
  7521. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7522. 'anime_id' => $anime_id,
  7523. 'episode_id' => $episode_id ?? 0,
  7524. 'model' => $model,
  7525. 'source' => 'addChatForAce',
  7526. ]);
  7527. }
  7528. }catch (\Exception $e) {
  7529. DB::rollBack();
  7530. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7531. yield [
  7532. 'type' => 'done',
  7533. 'answer' => $fullContent,
  7534. 'reasoning' => $fullReasoningContent,
  7535. 'usage' => $usage,
  7536. 'error' => $e->getMessage(),
  7537. ];
  7538. return;
  7539. }
  7540. DB::commit();
  7541. dLog('deepseek')->info('保存完毕');
  7542. if ($is_single && !empty($single_episode)) {
  7543. // $this->batchSetGlobalRoleImg([
  7544. // 'anime_id' => $anime_id,
  7545. // ]);
  7546. // $this->batchSetGlobalSceneImg([
  7547. // 'anime_id' => $anime_id,
  7548. // ]);
  7549. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7550. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7551. }
  7552. $table_data['anime_id'] = $anime_id;
  7553. $table_data['roles'] = json_decode($table_data['roles'], true);
  7554. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7555. // $table_data['episodes'] = $script_arr['episodes'];
  7556. unset($table_data['created_at']);
  7557. unset($table_data['updated_at']);
  7558. unset($table_data['status']);
  7559. dLog('deepseek')->info('开始返回');
  7560. yield [
  7561. 'type' => 'done',
  7562. 'script' => $table_data,
  7563. 'episode' => $single_episode,
  7564. 'answer' => $fullContent,
  7565. 'reasoning' => $fullReasoningContent,
  7566. 'usage' => $usage
  7567. ];
  7568. }
  7569. public function reGenerateAnimeForAce($data) {
  7570. $uid = Site::getUid();
  7571. $file = getProp($data, 'file');
  7572. $content = getProp($data, 'content', '');
  7573. $bid = getProp($data, 'bid', 0);
  7574. $script_id = getProp($data, 'script_id', 0);
  7575. $anime_id = getProp($data, 'anime_id');
  7576. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7577. if (!$anime) {
  7578. Utils::throwError('20003:该对话不存在');
  7579. }
  7580. $is_multi = getProp($anime, 'is_multi', 1);
  7581. $is_single = (int)$is_multi !== 1;
  7582. // 积分余额预检(仅单剧集模式收费)
  7583. if ($is_single) {
  7584. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  7585. }
  7586. $extra_products = getProp($data, 'products', []);
  7587. if (!$extra_products) {
  7588. $extra_products = getProp($anime, 'extra_products');
  7589. if ($extra_products) {
  7590. $extra_products = json_decode($extra_products, true);
  7591. }else {
  7592. $extra_products = [];
  7593. }
  7594. }else {
  7595. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7596. }
  7597. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7598. $anime_script_id = getProp($anime, 'script_id');
  7599. if ($anime_script_id && $is_single) {
  7600. $cpid = Site::getCpid();
  7601. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7602. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7603. ->where('mapping.script_id', $anime_script_id)
  7604. ->where('product.cpid', $cpid)
  7605. ->where('product.is_deleted', 0);
  7606. $mappings = $script_products_mappings->select(
  7607. 'mapping.product_id',
  7608. 'mapping.episode_number',
  7609. 'product.product_name',
  7610. 'product.type',
  7611. 'product.product',
  7612. 'product.pic_prompt',
  7613. 'product.url',
  7614. 'product.pic_task_id',
  7615. 'product.pic_task_status',
  7616. 'product.three_view_image_url'
  7617. )
  7618. ->get();
  7619. // 按 product_id 分组,合并 episode_number
  7620. $productMap = [];
  7621. foreach ($mappings as $item) {
  7622. $product_id = $item->product_id;
  7623. $product_name = $item->product_name;
  7624. // 处理product_name两边的符号
  7625. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7626. if (!isset($productMap[$product_id])) {
  7627. $productMap[$product_id] = [
  7628. 'product_id' => $product_id,
  7629. 'product_name' => $product_name,
  7630. 'type' => (int)$item->type,
  7631. 'product' => (int)$item->product,
  7632. 'pic_prompt' => $item->pic_prompt,
  7633. 'url' => $item->url,
  7634. 'pic_task_id' => $item->pic_task_id,
  7635. 'pic_task_status' => $item->pic_task_status,
  7636. 'episode_numbers' => [],
  7637. ];
  7638. }
  7639. // 添加 episode_number(去重)
  7640. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7641. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7642. }
  7643. }
  7644. // 将查询到的剧本资产合并到extra_products中
  7645. // 先构建extra_products的索引(以product_id为key,用于去重)
  7646. $extraProductsMap = [];
  7647. foreach ($extra_products as $item) {
  7648. $key = getProp($item, 'product_id');
  7649. if ($key) {
  7650. $extraProductsMap[$key] = $item;
  7651. }
  7652. }
  7653. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7654. foreach ($productMap as $product) {
  7655. $product_id = $product['product_id'];
  7656. // 如果不存在则添加(不带episode_number信息)
  7657. if (!isset($extraProductsMap[$product_id])) {
  7658. $extraProductsMap[$product_id] = [
  7659. 'product_id' => $product['product_id'],
  7660. 'product_name' => $product['product_name'],
  7661. 'type' => $product['type'],
  7662. 'product' => $product['product'],
  7663. 'pic_prompt' => $product['pic_prompt'],
  7664. 'url' => $product['url'],
  7665. 'pic_task_id' => $product['pic_task_id'],
  7666. 'pic_task_status' => $product['pic_task_status'],
  7667. ];
  7668. }
  7669. }
  7670. // 重新赋值给extra_products
  7671. $extra_products = array_values($extraProductsMap);
  7672. }
  7673. $user_anime_name = getProp($anime, 'anime_name');
  7674. $prompt = getProp($data, 'prompt');
  7675. // 处理提示词
  7676. if ($prompt && $extra_products) {
  7677. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7678. foreach($extra_products as $item) {
  7679. $product_name = getProp($item, 'product_name');
  7680. if ($product_name) {
  7681. // 替换 {product_name} 为 product_name
  7682. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7683. }
  7684. }
  7685. }
  7686. // 处理文本模型
  7687. $model = getProp($data, 'model');
  7688. if (!$model) {
  7689. // 用户没有输入,从anime表获取
  7690. $model = getProp($anime, 'model');
  7691. if (!$model) {
  7692. // anime表也没有,使用默认值
  7693. $model = 'deepseek-v4-pro';
  7694. }
  7695. }
  7696. // 验证模型是否在可用模型表中
  7697. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7698. $model = 'deepseek-v4-pro';
  7699. }
  7700. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7701. if ($is_single) {
  7702. $episode_exists = DB::table('mp_anime_episodes')
  7703. ->where('anime_id', $anime_id)
  7704. ->where('sequence', 1)
  7705. ->exists();
  7706. if ($episode_exists) {
  7707. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7708. }
  7709. }
  7710. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7711. if ($prompt) {
  7712. $question .= "本次修改要求如下:\n{$prompt}";
  7713. }
  7714. // 提取文件内容
  7715. if ($file) {
  7716. $content = $this->extractFileContent($file);
  7717. if (!$content) {
  7718. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7719. }
  7720. } elseif ($script_id) {
  7721. $content = $this->getContentByScriptId($script_id);
  7722. if (!$content) {
  7723. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7724. }
  7725. } elseif ($bid) {
  7726. $content = $this->getContentByBid($bid);
  7727. if (!$content) {
  7728. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7729. }
  7730. } elseif ($content) {
  7731. $content = filterContent($content);
  7732. }else {
  7733. $content = filterContent(getProp($anime, 'content'));
  7734. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7735. $need_generate_content = true;
  7736. }
  7737. }
  7738. // 判断是否需要生成原文内容
  7739. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7740. // 如果需要生成原文内容,添加额外的要求
  7741. $content_generation_requirement = $need_generate_content
  7742. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7743. : "";
  7744. // 美术风格
  7745. $input_art_style = getProp($data, 'art_style');
  7746. if (!$input_art_style) {
  7747. $mappedArtStyle = getProp($anime, 'art_style');
  7748. }else {
  7749. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7750. }
  7751. if (!$mappedArtStyle) {
  7752. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7753. }else {
  7754. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7755. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7756. }else {
  7757. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7758. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7759. }
  7760. }
  7761. // 构建主体、场景和道具提示词
  7762. $extra_role_prompt = "\n";
  7763. $extra_scene_prompt = "\n";
  7764. $extra_prop_prompt = "\n";
  7765. $ref_products = []; // 参考资产
  7766. if ($extra_products) {
  7767. foreach($extra_products as $item) {
  7768. $product = getProp($item, 'product');
  7769. $product_name = getProp($item, 'product_name');
  7770. if ($product_name == '旁白') continue;
  7771. $ref_products[$product_name] = $item;
  7772. $pic_prompt = getProp($item, 'pic_prompt');
  7773. if ((int)$product === 1) {
  7774. // 拼接角色信息
  7775. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7776. } elseif ((int)$product === 2) {
  7777. // 拼接场景信息
  7778. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7779. } elseif ((int)$product === 3) {
  7780. // 拼接道具信息
  7781. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7782. }
  7783. }
  7784. // 优化提示词,融入剧本
  7785. if (!empty(trim($extra_role_prompt))) {
  7786. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7787. }
  7788. if (!empty(trim($extra_scene_prompt))) {
  7789. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7790. }
  7791. if (!empty(trim($extra_prop_prompt))) {
  7792. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7793. }
  7794. }
  7795. if ($anime_script_id && $is_single) {
  7796. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7797. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7798. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7799. }else {
  7800. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7801. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7802. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7803. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7804. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7805. {$extra_role_prompt}";
  7806. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7807. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7808. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7809. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7810. {$extra_scene_prompt}";
  7811. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7812. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7813. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7814. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7815. {$extra_prop_prompt}";
  7816. }
  7817. $system_message = ['role'=>'system', 'content'=>$is_single
  7818. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7819. 强制要求:
  7820. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7821. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7822. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7823. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7824. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7825. 普通要求:
  7826. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7827. $role_demo
  7828. $scene_demo
  7829. $prop_demo
  7830. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7831. 5.1片段分割逻辑(优先级从高到低):
  7832. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7833. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7834. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7835. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7836. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7837. - 片段数量格式为: 片段数量:8
  7838. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7839. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7840. 5.3分镜结构:每个分镜包含以下字段:
  7841. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7842. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7843. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7844. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7845. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7846. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7847. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7848. - 运镜:场景+画面描述+运镜
  7849. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7850. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7851. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7852. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7853. 6.{$mappedArtStyle_prompt}\n\n
  7854. 示例如下:\n
  7855. ###剧本名:西昆仑
  7856. ###故事梗概
  7857. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7858. ###剧本亮点
  7859. 亮点1:绝境奇药,生死一线
  7860. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7861. 亮点2:结拜兄妹,化解尴尬
  7862. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7863. 亮点3:纤发夺命,情愫暗涌
  7864. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7865. ###人物关系
  7866. 阿雪与梁萧之间存在兄妹之情。
  7867. ###核心矛盾
  7868. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7869. ###主体列表
  7870. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7871. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7872. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7873. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7874. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7875. 全景,正面拍摄,青年女性,亚洲人。
  7876. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7877. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7878. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7879. ###美术风格
  7880. 基础画风风格词:厚涂古风
  7881. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7882. ###场景列表
  7883. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7884. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7885. 无人物。}
  7886. ###分段剧本
  7887. 片段数量:8
  7888. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7889. ##片段1
  7890. 时长:12s
  7891. 分镜1
  7892. 出场角色:刀疤脸
  7893. 场景:边境小镇街道
  7894. 出场道具:酒杯-高脚杯
  7895. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7896. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7897. 配音台词:
  7898. 背景音效:
  7899. 分镜2
  7900. 出场角色:刀疤脸
  7901. 场景:悦来酒馆
  7902. 出场道具:酒杯-高脚杯
  7903. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7904. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7905. 配音台词:
  7906. 背景音效:
  7907. 分镜3
  7908. 出场角色:刀疤脸
  7909. 场景:悦来酒馆
  7910. 出场道具:酒杯-高脚杯
  7911. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7912. 运镜:从中景推向令牌特写。
  7913. 配音台词:
  7914. 背景音效:
  7915. 分镜4
  7916. 出场角色:刀疤脸
  7917. 场景:悦来酒馆
  7918. 出场道具:酒杯-高脚杯
  7919. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7920. 运镜:极速推向酒水溅起的瞬间。
  7921. 配音台词:
  7922. 背景音效:
  7923. 分镜5
  7924. 出场角色:刀疤脸
  7925. 场景:悦来酒馆
  7926. 出场道具:酒杯-高脚杯
  7927. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7928. 运镜:固定机位,利用倾斜构图制造压迫感。
  7929. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7930. 背景音效:
  7931. \n\n"
  7932. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7933. 强制要求:\n
  7934. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7935. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7936. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7937. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7938. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7939. 普通要求:\n
  7940. 1.剧本名(必须生成)必须与文档内容高度相关
  7941. $role_demo
  7942. $scene_demo
  7943. $prop_demo
  7944. 5.{$mappedArtStyle_prompt}\n\n
  7945. 示例如下:\n
  7946. ###剧本名:西昆仑
  7947. ###故事梗概
  7948. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7949. ###剧本亮点
  7950. 亮点1:绝境奇药,生死一线
  7951. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7952. 亮点2:结拜兄妹,化解尴尬
  7953. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7954. 亮点3:纤发夺命,情愫暗涌
  7955. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7956. ###人物关系
  7957. 阿雪与梁萧之间存在兄妹之情。
  7958. ###核心矛盾
  7959. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7960. ###主体列表
  7961. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7962. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7963. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7964. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7965. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7966. 全景,正面拍摄,青年女性,亚洲人。
  7967. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7968. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7969. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7970. ###美术风格
  7971. 基础画风风格词:厚涂古风
  7972. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7973. ###场景列表
  7974. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7975. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7976. 无人物。}
  7977. ###道具列表
  7978. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7979. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7980. $episode_count = $this->extractEpisodeNumber($prompt);
  7981. if ((int)getProp($anime, 'is_multi') !== 1) {
  7982. yield [
  7983. 'type' => 'done',
  7984. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7985. 'reasoning' => '',
  7986. 'usage' => []
  7987. ];
  7988. return;
  7989. }
  7990. if ($episode_count) {
  7991. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7992. $system_message = [
  7993. 'role' => 'system',
  7994. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7995. 强制要求:\n
  7996. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7997. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7998. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7999. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8000. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8001. 普通要求:\n
  8002. 1.<故事梗概>控制在200-300字左右
  8003. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8004. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8005. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8006. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8007. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8008. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8009. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8010. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8011. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8012. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8013. 示例如下:\n
  8014. ###剧本名:西昆仑
  8015. ###故事梗概
  8016. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8017. ###剧本亮点
  8018. 亮点1:绝境奇药,生死一线
  8019. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8020. 亮点2:结拜兄妹,化解尴尬
  8021. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8022. 亮点3:纤发夺命,情愫暗涌
  8023. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8024. ###人物关系
  8025. 阿雪与梁萧之间存在兄妹之情。
  8026. ###核心矛盾
  8027. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8028. ###主体列表
  8029. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8030. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8031. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8032. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8033. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8034. 全景,正面拍摄,青年女性,亚洲人。
  8035. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8036. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8037. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8038. ###美术风格
  8039. 基础画风风格词:厚涂古风
  8040. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8041. ###场景列表
  8042. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8043. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8044. 无人物。}
  8045. ###分集详细内容
  8046. ##第1章 重生
  8047. 我重生了。
  8048. 源于一个男人偏执的暗恋。
  8049. ##第2章 相救
  8050. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8051. 我眼睛扫向站在锅炉后的卞大伟。"
  8052. ];
  8053. // 构建消息
  8054. $messages = [
  8055. $system_message,
  8056. [
  8057. 'role' => 'user',
  8058. 'content' => "以下是文档内容:
  8059. {$content}
  8060. 用户问题:
  8061. {$question}"
  8062. ]
  8063. ];
  8064. }else {
  8065. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8066. // 构建消息
  8067. $messages = [
  8068. $system_message,
  8069. [
  8070. 'role' => 'user',
  8071. 'content' => "以下是文档内容:
  8072. {$content}
  8073. 用户问题:
  8074. {$question}"
  8075. ]
  8076. ];
  8077. }else {
  8078. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8079. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8080. return (array)$value;
  8081. })->toArray();
  8082. array_unshift($messages, $system_message);
  8083. $messages[] = [
  8084. 'role' => 'user',
  8085. 'content' => $prompt
  8086. ];
  8087. }
  8088. }
  8089. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8090. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8091. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8092. if ($model === 'deepseek-chat') {
  8093. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8094. $model = 'deepseek-v4-flash';
  8095. $thinkingMode = 'disabled';
  8096. } elseif ($model === 'deepseek-reasoner') {
  8097. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8098. $model = 'deepseek-v4-flash';
  8099. $thinkingMode = 'enabled';
  8100. }
  8101. $post_data = [
  8102. 'model' => $model,
  8103. 'messages' => $messages,
  8104. // 'max_tokens' => 8192,
  8105. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8106. 'frequency_penalty' => 0,
  8107. 'presence_penalty' => 0,
  8108. 'response_format' => ['type' => 'text'],
  8109. 'thinking' => ['type' => $thinkingMode],
  8110. 'stream' => true // 启用流式输出
  8111. ];
  8112. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8113. // 根据模型类型选择调用方法
  8114. $fullContent = '';
  8115. $fullReasoningContent = '';
  8116. $usage = [];
  8117. // dd($post_data);
  8118. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8119. try {
  8120. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8121. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8122. } else if (in_array($model, $this->gpt_text_models)) {
  8123. // GPT-5.4 模型使用 TokenRouter API
  8124. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8125. } else if (in_array($model, $this->gemini_text_models)) {
  8126. // Gemini 模型使用 Gemini API
  8127. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8128. } else {
  8129. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8130. }
  8131. // 验证返回值类型
  8132. if (!is_iterable($streamGenerator)) {
  8133. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8134. dLog('deepseek')->error('方法名流式生成器无效', [
  8135. 'generator_type' => $errorType,
  8136. 'model' => $model,
  8137. // 添加其他上下文信息
  8138. ]);
  8139. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8140. 'type' => $errorType,
  8141. 'model' => $model
  8142. ]);
  8143. yield [
  8144. 'type' => 'error',
  8145. // 根据方法返回相应的空数据结构
  8146. 'answer' => '',
  8147. 'reasoning' => '',
  8148. 'usage' => [],
  8149. 'error' => '接口返回数据异常,请重新请求'
  8150. ];
  8151. return;
  8152. }
  8153. // 处理流式输出
  8154. foreach ($streamGenerator as $chunk) {
  8155. if (isset($chunk['type'])) {
  8156. if ($chunk['type'] === 'done') {
  8157. $fullContent = $chunk['full_content'];
  8158. $fullReasoningContent = $chunk['full_reasoning'];
  8159. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8160. } else {
  8161. yield $chunk;
  8162. }
  8163. }
  8164. }
  8165. } catch (\Exception $e) {
  8166. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8167. 'model' => $model,
  8168. 'trace' => $e->getTraceAsString()
  8169. ]);
  8170. logDB('deepseek', 'error', '方法名流式处理失败', [
  8171. 'error' => $e->getMessage(),
  8172. 'model' => $model
  8173. ]);
  8174. yield [
  8175. 'type' => 'error',
  8176. // 根据方法返回相应的空数据结构
  8177. 'answer' => '',
  8178. 'reasoning' => '',
  8179. 'usage' => [],
  8180. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8181. ];
  8182. return;
  8183. }
  8184. dLog('deepseek')->info('完整内容: '.$fullContent);
  8185. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8186. // 处理完整内容并返回最终结果
  8187. $script_arr = [];
  8188. if ($fullContent) {
  8189. $script_arr = handleScriptContentForAce($fullContent);
  8190. dLog('deepseek')->info('解析内容', $script_arr);
  8191. logDB('deepseek', 'info', '解析内容', $script_arr);
  8192. }
  8193. if (empty($script_arr['roles'])) {
  8194. // 未生成剧本相关内容,保存对话记录并返回提示
  8195. dLog('deepseek')->info('未生成剧本相关的内容');
  8196. try {
  8197. $now = date('Y-m-d H:i:s');
  8198. // 保存对话记录
  8199. $records = [
  8200. [
  8201. 'uid' => $uid,
  8202. 'anime_id' => $anime_id,
  8203. 'sequence' => 0,
  8204. 'role' => 'user',
  8205. 'content' => $prompt,
  8206. 'created_at' => $now,
  8207. 'updated_at' => $now
  8208. ],
  8209. [
  8210. 'uid' => $uid,
  8211. 'anime_id' => $anime_id,
  8212. 'sequence' => 0,
  8213. 'role' => 'assistant',
  8214. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8215. 'created_at' => $now,
  8216. 'updated_at' => $now
  8217. ]
  8218. ];
  8219. DB::table('mp_anime_records')->insert($records);
  8220. } catch (\Exception $e) {
  8221. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8222. }
  8223. yield [
  8224. 'type' => 'done',
  8225. 'script' => [],
  8226. 'episode' => [],
  8227. 'answer' => $fullContent,
  8228. 'reasoning' => $fullReasoningContent,
  8229. 'usage' => $usage,
  8230. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8231. ];
  8232. return;
  8233. }
  8234. // 替换美术风格
  8235. if ($mappedArtStyle !== '') {
  8236. $script_arr['art_style'] = $mappedArtStyle;
  8237. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8238. }
  8239. if ($user_anime_name != '新剧本策划') {
  8240. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8241. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8242. // 确认对话名称唯一性
  8243. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8244. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8245. }
  8246. }else {
  8247. $anime_name = $user_anime_name;
  8248. }
  8249. $table_data = [
  8250. 'user_id' => $uid,
  8251. 'model' => $model,
  8252. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8253. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8254. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8255. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8256. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8257. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8258. 'art_style_type' => $input_art_style,
  8259. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8260. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8261. 'status' => '解析完成',
  8262. 'generate_status' => '待执行',
  8263. 'updated_at' => date('Y-m-d H:i:s')
  8264. ];
  8265. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8266. // 如果是修改集数,则将content内容更新(会改变原文)
  8267. if (isset($episode_count) && $episode_count > 0) {
  8268. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8269. $table_data['start_episode_sequence'] = 1;
  8270. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8271. }else {
  8272. // 如果需要生成原文内容,从script_arr中提取
  8273. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8274. $table_data['content'] = $script_arr['content'];
  8275. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8276. if (!$table_data['content']) {
  8277. yield [
  8278. 'type' => 'done',
  8279. 'script' => [],
  8280. 'episode' => [],
  8281. 'answer' => $fullContent,
  8282. 'reasoning' => $fullReasoningContent,
  8283. 'usage' => $usage,
  8284. 'error' => '未生成剧本内容,请调整提示词再试'
  8285. ];
  8286. return;
  8287. }
  8288. }
  8289. if (isset($table_data['content']) && $table_data['content']) {
  8290. $chapters = splitContent($table_data['content']);
  8291. $chapter_count = count($chapters);
  8292. if ($chapter_count > 0) {
  8293. $table_data['start_episode_sequence'] = 1;
  8294. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8295. }
  8296. }
  8297. }
  8298. if ($extra_products) {
  8299. $table_data['extra_products'] = json_encode($extra_products, 256);
  8300. }
  8301. $single_episode = [];
  8302. try {
  8303. DB::beginTransaction();
  8304. $now = date('Y-m-d H:i:s');
  8305. // 更新动漫大纲
  8306. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8307. if (!$boolen) {
  8308. dLog('deepseek')->info('对话修改失败', $table_data);
  8309. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8310. Utils::throwError('20003:对话修改失败');
  8311. }
  8312. // 保存对话记录
  8313. $records = [
  8314. [
  8315. 'uid' => $uid,
  8316. 'anime_id' => $anime_id,
  8317. 'sequence' => 0,
  8318. 'role' => 'user',
  8319. 'content' => $prompt,
  8320. 'created_at' => $now,
  8321. 'updated_at' => $now
  8322. ],
  8323. [
  8324. 'uid' => $uid,
  8325. 'anime_id' => $anime_id,
  8326. 'sequence' => 0,
  8327. 'role' => 'assistant',
  8328. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8329. 'content' => $fullContent,
  8330. 'created_at' => $now,
  8331. 'updated_at' => $now
  8332. ]
  8333. ];
  8334. // 保存对话记录
  8335. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8336. if (!$boolen3) {
  8337. Utils::throwError('20003:对话记录保存失败');
  8338. }
  8339. // 单剧集模式:生成并保存剧集信息
  8340. if ($is_single) {
  8341. $anime_name = getProp($anime, 'anime_name', '未命名');
  8342. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8343. if (empty($episode_arr['acts'])) {
  8344. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8345. }
  8346. $saveResult = $this->saveEpisodeVersionData(
  8347. $anime_id,
  8348. 1,
  8349. $episode_arr,
  8350. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8351. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8352. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8353. null,
  8354. null,
  8355. false,
  8356. $content,
  8357. $now,
  8358. $ref_products
  8359. );
  8360. $single_episode = $saveResult['episode'];
  8361. $episode_id = $saveResult['episode_id'];
  8362. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8363. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8364. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8365. 'props' => json_encode($saveResult['merged_props'], 256),
  8366. 'updated_at' => $now
  8367. ]);
  8368. if ($boolen5 === false) {
  8369. Utils::throwError('20003:单剧集主表资源同步失败');
  8370. }
  8371. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8372. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8373. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8374. $episode_record_content = '确认分镜大纲';
  8375. if ($content !== '') {
  8376. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8377. }
  8378. $episode_records = [
  8379. [
  8380. 'uid' => $uid,
  8381. 'anime_id' => $anime_id,
  8382. 'role' => 'user',
  8383. 'content' => $episode_record_content,
  8384. 'sequence' => 1,
  8385. 'episode_id' => $episode_id,
  8386. 'created_at' => $now,
  8387. 'updated_at' => $now
  8388. ],
  8389. [
  8390. 'uid' => $uid,
  8391. 'anime_id' => $anime_id,
  8392. 'role' => 'assistant',
  8393. 'content' => $fullContent,
  8394. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8395. 'sequence' => 1,
  8396. 'episode_id' => $episode_id,
  8397. 'created_at' => $now,
  8398. 'updated_at' => $now
  8399. ]
  8400. ];
  8401. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8402. if (!$boolen4) {
  8403. Utils::throwError('20003:单剧集分镜记录保存失败');
  8404. }
  8405. }
  8406. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8407. if ($is_single && !empty($single_episode)) {
  8408. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8409. 'anime_id' => $anime_id,
  8410. 'episode_id' => $episode_id ?? 0,
  8411. 'model' => $model,
  8412. 'source' => 'reGenerateAnimeForAce',
  8413. ]);
  8414. }
  8415. }catch (\Exception $e) {
  8416. DB::rollBack();
  8417. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8418. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8419. yield [
  8420. 'type' => 'done',
  8421. 'answer' => $fullContent,
  8422. 'reasoning' => $fullReasoningContent,
  8423. 'usage' => $usage,
  8424. 'error' => $e->getMessage(),
  8425. ];
  8426. return;
  8427. }
  8428. DB::commit();
  8429. dLog('deepseek')->info('保存完毕');
  8430. if ($is_single && !empty($single_episode)) {
  8431. // $this->batchSetGlobalRoleImg([
  8432. // 'anime_id' => $anime_id,
  8433. // ]);
  8434. // $this->batchSetGlobalSceneImg([
  8435. // 'anime_id' => $anime_id,
  8436. // ]);
  8437. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8438. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8439. }
  8440. $table_data['anime_id'] = $anime_id;
  8441. $table_data['roles'] = json_decode($table_data['roles'], true);
  8442. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8443. $table_data['props'] = json_decode($table_data['props'], true);
  8444. unset($table_data['updated_at']);
  8445. unset($table_data['status']);
  8446. yield [
  8447. 'type' => 'done',
  8448. 'script' => $table_data,
  8449. 'episode' => $single_episode,
  8450. 'answer' => $fullContent,
  8451. 'reasoning' => $fullReasoningContent,
  8452. 'usage' => $usage
  8453. ];
  8454. }
  8455. public function chatForAce($data) {
  8456. $uid = Site::getUid();
  8457. // 积分余额预检(不足直接报错)
  8458. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8459. $anime_id = getProp($data, 'anime_id');
  8460. $file = getProp($data, 'file');
  8461. $content = getProp($data, 'content', '');
  8462. $bid = getProp($data, 'bid', 0);
  8463. $script_id = getProp($data, 'script_id', 0);
  8464. $episode_number = getProp($data, 'episode_number', 1);
  8465. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8466. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8467. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8468. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8469. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8470. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8471. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8472. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8473. $roles = is_array($roles) ? $roles : [];
  8474. $scenes = is_array($scenes) ? $scenes : [];
  8475. $extra_products = getProp($data, 'products', []);
  8476. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8477. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8478. $anime_script_id = getProp($anime, 'script_id');
  8479. if ($anime_script_id) {
  8480. $cpid = Site::getCpid();
  8481. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8482. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8483. ->where('mapping.script_id', $anime_script_id)
  8484. ->where('product.cpid', $cpid)
  8485. ->where('product.is_deleted', 0);
  8486. // 如果提供了 episode_number,则过滤指定集数
  8487. if ($episode_number !== null && $episode_number !== '') {
  8488. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8489. }
  8490. $mappings = $script_products_mappings->select(
  8491. 'mapping.product_id',
  8492. 'mapping.episode_number',
  8493. 'product.product_name',
  8494. 'product.type',
  8495. 'product.product',
  8496. 'product.pic_prompt',
  8497. 'product.url',
  8498. 'product.pic_task_id',
  8499. 'product.pic_task_status',
  8500. 'product.three_view_image_url'
  8501. )
  8502. ->get();
  8503. // 按 product_id 分组,合并 episode_number
  8504. $productMap = [];
  8505. foreach ($mappings as $item) {
  8506. $product_id = $item->product_id;
  8507. $product_name = $item->product_name;
  8508. // 处理product_name两边的符号
  8509. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8510. if (!isset($productMap[$product_id])) {
  8511. $productMap[$product_id] = [
  8512. 'product_id' => $product_id,
  8513. 'product_name' => $product_name,
  8514. 'type' => (int)$item->type,
  8515. 'product' => (int)$item->product,
  8516. 'pic_prompt' => $item->pic_prompt,
  8517. 'url' => $item->url,
  8518. 'pic_task_id' => $item->pic_task_id,
  8519. 'pic_task_status' => $item->pic_task_status,
  8520. 'episode_numbers' => [],
  8521. ];
  8522. }
  8523. // 添加 episode_number(去重)
  8524. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8525. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8526. }
  8527. }
  8528. // 将查询到的剧本资产合并到extra_products中
  8529. // 先构建extra_products的索引(以product_id+episode_number为key)
  8530. $extraProductsMap = [];
  8531. foreach ($extra_products as $item) {
  8532. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8533. $extraProductsMap[$key] = $item;
  8534. }
  8535. // 合并剧本资产(去重:product_id+episode_number)
  8536. foreach ($productMap as $product) {
  8537. foreach ($product['episode_numbers'] as $ep_num) {
  8538. $key = $product['product_id'] . '_' . $ep_num;
  8539. // 如果不存在则添加
  8540. if (!isset($extraProductsMap[$key])) {
  8541. $extraProductsMap[$key] = [
  8542. 'product_id' => $product['product_id'],
  8543. 'product_name' => $product['product_name'],
  8544. 'type' => $product['type'],
  8545. 'product' => $product['product'],
  8546. 'pic_prompt' => $product['pic_prompt'],
  8547. 'url' => $product['url'],
  8548. 'pic_task_id' => $product['pic_task_id'],
  8549. 'pic_task_status' => $product['pic_task_status'],
  8550. 'episode_number' => $ep_num,
  8551. ];
  8552. }
  8553. }
  8554. }
  8555. // 重新赋值给extra_products
  8556. $extra_products = array_values($extraProductsMap);
  8557. }
  8558. // 处理提示词
  8559. if ($prompt && $extra_products) {
  8560. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8561. foreach($extra_products as $item) {
  8562. $product_name = getProp($item, 'product_name');
  8563. if ($product_name) {
  8564. // 替换 {product_name} 为 product_name
  8565. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8566. }
  8567. }
  8568. }
  8569. // 获取最后一集序号
  8570. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8571. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8572. // 转换主体列表和场景列表的格式
  8573. // 获取参考主体或场景
  8574. if ((int)$episode_number === 1) {
  8575. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8576. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8577. }else {
  8578. $prev_episode_number = $episode_number - 1;
  8579. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8580. }
  8581. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8582. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8583. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8584. // 合并anime_products和extra_products(extra_products优先,去重)
  8585. $anime_products = getProp($anime, 'extra_products');
  8586. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8587. $ref_products = [];
  8588. foreach($anime_products as $item) {
  8589. $product_name = getProp($item, 'product_name');
  8590. $ref_products[$product_name] = $item;
  8591. }
  8592. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8593. $extra_roles = []; // 从extra_products中提取的角色
  8594. $extra_scenes = []; // 从extra_products中提取的场景
  8595. $extra_props = []; // 从extra_products中提取的道具
  8596. if ($extra_products && is_array($extra_products)) {
  8597. foreach($extra_products as $item) {
  8598. $product = (int)getProp($item, 'product');
  8599. $product_name = getProp($item, 'product_name');
  8600. if ($product_name == '旁白') continue;
  8601. $pic_prompt = getProp($item, 'pic_prompt');
  8602. $ref_products[$product_name] = $item;
  8603. if ($product === 1) {
  8604. // 角色
  8605. $extra_roles[$product_name] = [
  8606. 'role' => $product_name,
  8607. 'pic_prompt' => $pic_prompt,
  8608. 'url' => getProp($item, 'url', ''),
  8609. ];
  8610. } elseif ($product === 2) {
  8611. // 场景
  8612. $extra_scenes[$product_name] = [
  8613. 'scene' => $product_name,
  8614. 'pic_prompt' => $pic_prompt,
  8615. 'url' => getProp($item, 'url', ''),
  8616. ];
  8617. } elseif ($product === 3) {
  8618. // 道具
  8619. $extra_props[$product_name] = [
  8620. 'prop' => $product_name,
  8621. 'pic_prompt' => $pic_prompt,
  8622. 'url' => getProp($item, 'url', ''),
  8623. ];
  8624. }
  8625. }
  8626. }
  8627. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8628. $merged_roles = [];
  8629. foreach($ref_roles as $role) {
  8630. $role_name = getProp($role, 'role');
  8631. if (!isset($extra_roles[$role_name])) {
  8632. $merged_roles[$role_name] = $role;
  8633. }
  8634. }
  8635. // 添加extra_roles
  8636. foreach($extra_roles as $role_name => $role) {
  8637. $merged_roles[$role_name] = $role;
  8638. }
  8639. $ref_roles = array_values($merged_roles);
  8640. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8641. $merged_scenes = [];
  8642. foreach($ref_scenes as $scene) {
  8643. $scene_name = getProp($scene, 'scene');
  8644. if (!isset($extra_scenes[$scene_name])) {
  8645. $merged_scenes[$scene_name] = $scene;
  8646. }
  8647. }
  8648. // 添加extra_scenes
  8649. foreach($extra_scenes as $scene_name => $scene) {
  8650. $merged_scenes[$scene_name] = $scene;
  8651. }
  8652. $ref_scenes = array_values($merged_scenes);
  8653. // 合并ref_props和extra_props(extra_props优先,去重)
  8654. $merged_props = [];
  8655. foreach($ref_props as $prop) {
  8656. $prop_name = getProp($prop, 'prop');
  8657. if (!isset($extra_props[$prop_name])) {
  8658. $merged_props[$prop_name] = $prop;
  8659. }
  8660. }
  8661. // 添加extra_props
  8662. foreach($extra_props as $prop_name => $prop) {
  8663. $merged_props[$prop_name] = $prop;
  8664. }
  8665. $ref_props = array_values($merged_props);
  8666. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8667. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8668. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8669. // 构建强制主体、场景和道具提示词
  8670. $forced_roles_prompt = "";
  8671. $forced_scenes_prompt = "";
  8672. $forced_props_prompt = "";
  8673. if (!empty($extra_roles)) {
  8674. $forced_roles_list = "";
  8675. foreach($extra_roles as $role_name => $role) {
  8676. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8677. }
  8678. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8679. }
  8680. if (!empty($extra_scenes)) {
  8681. $forced_scenes_list = "";
  8682. foreach($extra_scenes as $scene_name => $scene) {
  8683. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8684. }
  8685. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8686. }
  8687. if (!empty($extra_props)) {
  8688. $forced_props_list = "";
  8689. foreach($extra_props as $prop_name => $prop) {
  8690. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8691. }
  8692. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8693. }
  8694. if ($anime_script_id) {
  8695. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8696. }else if ($roles_content) {
  8697. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8698. 主体范围:\n {$roles_content}\n
  8699. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8700. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8701. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8702. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8703. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8704. }else {
  8705. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8706. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8707. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8708. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8709. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8710. }
  8711. if ($anime_script_id) {
  8712. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8713. }else if ($scenes_content) {
  8714. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8715. 场景范围:\n {$scenes_content}\n
  8716. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8717. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8718. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8719. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8720. }else {
  8721. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8722. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8723. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8724. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8725. }
  8726. if ($anime_script_id) {
  8727. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8728. }else if ($props_content) {
  8729. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8730. 道具范围:\n {$props_content}\n
  8731. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8732. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8733. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8734. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8735. }else {
  8736. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8737. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8738. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8739. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8740. }
  8741. // 提取文件内容
  8742. if ($file) {
  8743. $uploaded_content = $this->extractFileContent($file);
  8744. if (!$uploaded_content) {
  8745. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8746. }
  8747. } elseif ($script_id) {
  8748. $uploaded_content = $this->getContentByScriptId($script_id);
  8749. if (!$uploaded_content) {
  8750. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8751. }
  8752. } elseif ($bid) {
  8753. $uploaded_content = $this->getContentByBid($bid);
  8754. if (!$uploaded_content) {
  8755. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8756. }
  8757. } elseif ($content) {
  8758. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8759. }
  8760. // elseif ($prompt) {
  8761. // $uploaded_content = filterContent($prompt);
  8762. // }
  8763. else {
  8764. $uploaded_content = '';
  8765. }
  8766. // 美术风格
  8767. $input_art_style = getProp($data, 'art_style');
  8768. if (!$input_art_style) {
  8769. $mappedArtStyle = getProp($anime, 'art_style');
  8770. }else {
  8771. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8772. }
  8773. if (!$mappedArtStyle) {
  8774. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8775. }else {
  8776. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8777. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8778. }else {
  8779. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8780. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8781. }
  8782. }
  8783. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8784. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8785. // 强制要求:
  8786. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8787. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8788. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8789. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8790. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8791. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8792. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8793. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8794. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8795. // 10.分镜要和场景列表、人物主体保持一致\n
  8796. // 普通要求:
  8797. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8798. // {$role_demo}
  8799. // {$scene_demo}
  8800. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8801. // 4.1片段分割逻辑(优先级从高到低):
  8802. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8803. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8804. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8805. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8806. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8807. // - 片段数量格式为: 片段数量:8
  8808. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8809. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8810. // 4.3分镜结构:每个分镜包含以下字段:
  8811. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8812. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8813. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8814. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8815. // - 运镜:场景+画面描述+运镜
  8816. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8817. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8818. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8819. // 5.$mappedArtStyle_prompt\n\n
  8820. // 示例格式:\n
  8821. // 第1集:隐形的守护者
  8822. // ###故事梗概
  8823. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8824. // ###美术风格
  8825. // 基础画风风格词:胡金铨武侠
  8826. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8827. // ###主体列表
  8828. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8829. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8830. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8831. // ###场景列表
  8832. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8833. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8834. // ###分段剧本
  8835. // 片段数量:8
  8836. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8837. // ##片段1
  8838. // 时长:12s
  8839. // 分镜1
  8840. // 场景:边境小镇街道
  8841. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8842. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8843. // 配音台词:
  8844. // 背景音效:
  8845. // 分镜2
  8846. // 场景:悦来酒馆
  8847. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8848. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8849. // 配音台词:
  8850. // 背景音效:
  8851. // 分镜3
  8852. // 场景:悦来酒馆
  8853. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8854. // 运镜:从中景推向令牌特写。
  8855. // 配音台词:
  8856. // 背景音效:
  8857. // 分镜4
  8858. // 场景:悦来酒馆
  8859. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8860. // 运镜:极速推向酒水溅起的瞬间。
  8861. // 配音台词:
  8862. // 背景音效:
  8863. // 分镜5
  8864. // 镜头描述
  8865. // 场景:悦来酒馆
  8866. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8867. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8868. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8869. // 背景音效:
  8870. // \n\n";
  8871. /*
  8872. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  8873. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  8874. // ===================================================================
  8875. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8876. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8877. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8878. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8879. 强制要求:
  8880. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  8881. 普通要求:
  8882. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8883. {$role_demo}
  8884. {$scene_demo}
  8885. {$prop_demo}
  8886. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8887. 5.1片段分割逻辑(优先级从高到低):
  8888. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8889. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8890. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8891. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8892. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8893. - 片段数量格式为: 片段数量:8
  8894. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8895. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8896. 5.3分镜结构:每个分镜包含以下字段:
  8897. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8898. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8899. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8900. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8901. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8902. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8903. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8904. - 运镜:场景+画面描述+运镜
  8905. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8906. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8907. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8908. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8909. 6.《情绪-视听语言映射表》:
  8910. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8911. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8912. -----|---------|------------|----------------
  8913. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8914. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8915. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8916. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8917. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8918. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8919. -----|---------|------------|----------------
  8920. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8921. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8922. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8923. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8924. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8925. --------|---------|--------------|-------------
  8926. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8927. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8928. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8929. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8930. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8931. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8932. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8933. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8934. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8935. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8936. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8937. -----|---------|------------|------------
  8938. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8939. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8940. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8941. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8942. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8943. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8944. --------|---------|--------------|----------
  8945. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8946. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8947. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8948. 6.6 声音设计与潜意识影响 (Soundscape)
  8949. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8950. -----|---------|------------|------------------
  8951. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8952. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8953. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8954. 理论基石:
  8955. - The Five C's of Cinematography by Joseph V. Mascelli
  8956. - Film Art: An Introduction by David Bordwell
  8957. - Sight, Sound, Motion by Herbert Zettl
  8958. - Notes on the Cinematograph by Robert Bresson
  8959. \n\n
  8960. 7.{$mappedArtStyle_prompt}
  8961. 示例格式:\n
  8962. 第1集:隐形的守护者
  8963. ###故事梗概
  8964. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8965. ###美术风格
  8966. 基础画风风格词:胡金铨武侠
  8967. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8968. ###主体列表
  8969. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8970. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8971. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8972. ###场景列表
  8973. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8974. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8975. ###道具列表
  8976. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8977. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8978. ###分段剧本
  8979. 片段数量:8
  8980. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8981. ##片段1
  8982. 时长:12s
  8983. 分镜1
  8984. 出场角色:刀疤脸
  8985. 场景:边境小镇街道
  8986. 出场道具:酒杯-高脚杯
  8987. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8988. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8989. 配音台词:
  8990. 背景音效:
  8991. 分镜2
  8992. 出场角色:刀疤脸
  8993. 场景:悦来酒馆
  8994. 出场道具:酒杯-高脚杯
  8995. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8996. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8997. 配音台词:
  8998. 背景音效:
  8999. 分镜3
  9000. 出场角色:刀疤脸
  9001. 场景:悦来酒馆
  9002. 出场道具:酒杯-高脚杯
  9003. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9004. 运镜:从中景推向令牌特写。
  9005. 配音台词:
  9006. 背景音效:
  9007. 分镜4
  9008. 出场角色:刀疤脸
  9009. 场景:悦来酒馆
  9010. 出场道具:酒杯-高脚杯
  9011. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9012. 运镜:极速推向酒水溅起的瞬间。
  9013. 配音台词:
  9014. 背景音效:
  9015. 分镜5
  9016. 出场角色:刀疤脸
  9017. 场景:悦来酒馆
  9018. 出场道具:酒杯-高脚杯
  9019. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9020. 运镜:固定机位,利用倾斜构图制造压迫感。
  9021. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9022. 背景音效:
  9023. \n\n";
  9024. */
  9025. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9026. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9027. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9028. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9029. 强制要求:
  9030. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9031. 普通要求:
  9032. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  9033. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  9034. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  9035. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  9036. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9037. 5.1片段分割逻辑(优先级从高到低):
  9038. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9039. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9040. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9041. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9042. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9043. - 片段数量格式为: 片段数量:8
  9044. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9045. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9046. 5.3分镜结构:每个分镜包含以下字段:
  9047. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9048. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9049. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9050. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9051. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9052. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9053. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9054. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9055. - 运镜:场景+画面描述+运镜
  9056. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9057. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9058. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9059. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9060. 6.《情绪-视听语言映射表》:
  9061. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9062. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9063. -----|---------|------------|----------------
  9064. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9065. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9066. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9067. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9068. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9069. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9070. -----|---------|------------|----------------
  9071. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9072. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9073. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9074. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9075. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9076. --------|---------|--------------|-------------
  9077. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9078. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9079. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9080. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9081. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9082. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9083. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9084. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9085. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9086. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9087. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9088. -----|---------|------------|------------
  9089. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9090. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9091. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9092. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9093. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9094. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9095. --------|---------|--------------|----------
  9096. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9097. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9098. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9099. 6.6 声音设计与潜意识影响 (Soundscape)
  9100. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9101. -----|---------|------------|------------------
  9102. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9103. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9104. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9105. 理论基石:
  9106. - The Five C's of Cinematography by Joseph V. Mascelli
  9107. - Film Art: An Introduction by David Bordwell
  9108. - Sight, Sound, Motion by Herbert Zettl
  9109. - Notes on the Cinematograph by Robert Bresson
  9110. \n\n
  9111. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9112. 示例格式:\n
  9113. 第1集:隐形的守护者
  9114. ###故事梗概
  9115. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9116. ###美术风格
  9117. 基础画风风格词:胡金铨武侠
  9118. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9119. ###主体列表
  9120. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9121. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9122. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9123. ###场景列表
  9124. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9125. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9126. ###道具列表
  9127. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9128. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9129. ###分段剧本
  9130. 片段数量:8
  9131. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9132. ##片段1
  9133. 时长:12s
  9134. 分镜1
  9135. 出场角色:刀疤脸
  9136. 场景:边境小镇街道
  9137. 出场道具:酒杯-高脚杯
  9138. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9139. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9140. 配音台词:
  9141. 背景音效:
  9142. 分镜2
  9143. 出场角色:刀疤脸
  9144. 场景:悦来酒馆
  9145. 出场道具:酒杯-高脚杯
  9146. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9147. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9148. 配音台词:
  9149. 背景音效:
  9150. 分镜3
  9151. 出场角色:刀疤脸
  9152. 场景:悦来酒馆
  9153. 出场道具:酒杯-高脚杯
  9154. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9155. 运镜:从中景推向令牌特写。
  9156. 配音台词:
  9157. 背景音效:
  9158. 分镜4
  9159. 出场角色:刀疤脸
  9160. 场景:悦来酒馆
  9161. 出场道具:酒杯-高脚杯
  9162. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9163. 运镜:极速推向酒水溅起的瞬间。
  9164. 配音台词:
  9165. 背景音效:
  9166. 分镜5
  9167. 出场角色:刀疤脸
  9168. 场景:悦来酒馆
  9169. 出场道具:酒杯-高脚杯
  9170. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9171. 运镜:固定机位,利用倾斜构图制造压迫感。
  9172. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9173. 背景音效:
  9174. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9175. 【本次剧集信息】剧集序号是{$episode_number}。
  9176. 【本次生成数据-主体列表】{$role_demo}
  9177. 【本次生成数据-场景列表】{$scene_demo}
  9178. 【本次生成数据-道具列表】{$prop_demo}
  9179. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9180. \n\n";
  9181. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9182. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9183. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9184. $prompt = $origin_prompt;
  9185. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9186. // 获取章节内容
  9187. $full_content = getProp($anime, 'content');
  9188. if ($uploaded_content) {
  9189. $full_content = $uploaded_content;
  9190. }
  9191. // 根据章节内容拆分章节
  9192. $chapters = splitContent($full_content);
  9193. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9194. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9195. $messages = [];
  9196. if ($prompt == '确认分镜大纲') {
  9197. // 暂时保留
  9198. $content = $chapter_content;
  9199. if ($is_single) $content = $full_content; // 单剧集使用全文
  9200. if (!$content) {
  9201. Utils::throwError('20003:章节内容无法获取,请确认');
  9202. }
  9203. $question = $is_single
  9204. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9205. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9206. // 构建消息
  9207. $messages[] =
  9208. [
  9209. 'role' => 'user',
  9210. 'content' => $question
  9211. ];
  9212. }else if ($prompt == '继续策划下一集') {
  9213. if ($is_single) {
  9214. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9215. }
  9216. $content = $chapter_content;
  9217. if (!$content) {
  9218. Utils::throwError('20003:章节内容无法获取,请确认');
  9219. }
  9220. // 获取上一集最后记录
  9221. $prev_sequence = $episode_number - 1;
  9222. $messages = array_merge(
  9223. [
  9224. [
  9225. 'role' => 'system',
  9226. 'content' => $demo
  9227. ]
  9228. ],
  9229. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9230. );
  9231. // 构建消息
  9232. $messages[] =
  9233. [
  9234. 'role' => 'user',
  9235. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9236. ];
  9237. /*
  9238. // 旧版逻辑
  9239. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9240. // 构建消息
  9241. $messages[] =
  9242. [
  9243. 'role' => 'user',
  9244. 'content' => $question
  9245. ];
  9246. */
  9247. // dd($messages);
  9248. }else {
  9249. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9250. if (!$content) {
  9251. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9252. }
  9253. if (!$content) {
  9254. Utils::throwError('20003:章节内容无法获取,请确认');
  9255. }
  9256. $messages = array_merge(
  9257. [
  9258. [
  9259. 'role' => 'system',
  9260. 'content' => $demo
  9261. ]
  9262. ],
  9263. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9264. );
  9265. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9266. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9267. if ($origin_prompt) {
  9268. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9269. }
  9270. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9271. $messages[] = [
  9272. 'role' => 'user',
  9273. 'content' => "本集剧情内容:\n\n{$content}\n"
  9274. ];
  9275. $messages[] =
  9276. [
  9277. 'role' => 'user',
  9278. 'content' => $question
  9279. ];
  9280. }
  9281. // 处理文本模型
  9282. $model = getProp($data, 'model');
  9283. if (!$model) {
  9284. // 用户没有输入,从anime表获取
  9285. $model = getProp($anime, 'model');
  9286. if (!$model) {
  9287. // anime表也没有,使用默认值
  9288. $model = 'deepseek-v4-pro';
  9289. }
  9290. }
  9291. // 验证模型是否在可用模型表中
  9292. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9293. $model = 'deepseek-v4-pro';
  9294. }
  9295. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9296. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9297. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9298. if ($model === 'deepseek-chat') {
  9299. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9300. $model = 'deepseek-v4-flash';
  9301. $thinkingMode = 'disabled';
  9302. } elseif ($model === 'deepseek-reasoner') {
  9303. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9304. $model = 'deepseek-v4-flash';
  9305. $thinkingMode = 'enabled';
  9306. }
  9307. $post_data = [
  9308. 'model' => $model,
  9309. 'messages' => $messages,
  9310. // 'max_tokens' => 8192,
  9311. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9312. 'frequency_penalty' => 0,
  9313. 'presence_penalty' => 0,
  9314. 'response_format' => ['type' => 'text'],
  9315. 'thinking' => ['type' => $thinkingMode],
  9316. 'stream' => true // 启用流式输出
  9317. ];
  9318. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9319. // 根据模型类型选择调用方法
  9320. $fullContent = '';
  9321. $fullReasoningContent = '';
  9322. $usage = [];
  9323. try {
  9324. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9325. // DeepSeek 官方模型使用 DeepSeek API
  9326. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9327. } else if (in_array($model, $this->gpt_text_models)) {
  9328. // GPT-5.4 模型使用 TokenRouter API
  9329. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9330. } else if (in_array($model, $this->gemini_text_models)) {
  9331. // Gemini 模型使用 Gemini API
  9332. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9333. } else {
  9334. // 其他模型使用火山引擎API
  9335. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9336. }
  9337. // 验证返回值类型
  9338. if (!is_iterable($streamGenerator)) {
  9339. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9340. dLog('deepseek')->error('chat流式生成器无效', [
  9341. 'generator_type' => $errorType,
  9342. 'model' => $model,
  9343. 'anime_id' => $anime_id,
  9344. 'episode_number' => $episode_number
  9345. ]);
  9346. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9347. 'type' => $errorType,
  9348. 'model' => $model
  9349. ]);
  9350. yield [
  9351. 'type' => 'error',
  9352. 'episode' => [],
  9353. 'answer' => '',
  9354. 'reasoning' => '',
  9355. 'usage' => [],
  9356. 'error' => '接口返回数据异常,请重新请求'
  9357. ];
  9358. return;
  9359. }
  9360. // 处理流式输出
  9361. foreach ($streamGenerator as $chunk) {
  9362. if (isset($chunk['type'])) {
  9363. if ($chunk['type'] === 'done') {
  9364. // 最终结果
  9365. $fullContent = $chunk['full_content'];
  9366. $fullReasoningContent = $chunk['full_reasoning'];
  9367. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9368. } else {
  9369. // 逐块yield数据
  9370. yield $chunk;
  9371. }
  9372. }
  9373. }
  9374. } catch (\Exception $e) {
  9375. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9376. 'model' => $model,
  9377. 'anime_id' => $anime_id,
  9378. 'episode_number' => $episode_number,
  9379. 'trace' => $e->getTraceAsString()
  9380. ]);
  9381. logDB('deepseek', 'error', 'chat流式处理失败', [
  9382. 'error' => $e->getMessage(),
  9383. 'model' => $model
  9384. ]);
  9385. yield [
  9386. 'type' => 'error',
  9387. 'episode' => [],
  9388. 'answer' => '',
  9389. 'reasoning' => '',
  9390. 'usage' => [],
  9391. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9392. ];
  9393. return;
  9394. }
  9395. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9396. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9397. dLog('deepseek')->info('完整内容: '.$fullContent);
  9398. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9399. // 处理完整内容并返回最终结果
  9400. $episode_arr = handleEpisodeContentForAce($fullContent);
  9401. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9402. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9403. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9404. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9405. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9406. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9407. // }
  9408. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9409. $max_retries = 3;
  9410. $retry_count = 0;
  9411. $validation_failed = false;
  9412. $validation_error_msg = '';
  9413. // 验证生成的内容
  9414. if ($anime_script_id) {
  9415. // 检查是否有acts数据
  9416. if (empty($episode_arr['acts'])) {
  9417. $validation_failed = true;
  9418. $validation_error_msg = '未生成分镜剧本相关的内容';
  9419. } else {
  9420. // 校验主体列表:不能为空主体(旁白不算)
  9421. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9422. // 过滤掉"旁白"角色
  9423. $generated_roles = array_filter($generated_roles, function($role) {
  9424. return $role !== '旁白';
  9425. });
  9426. if (empty($generated_roles)) {
  9427. $validation_failed = true;
  9428. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9429. }
  9430. // 仅当存在强制主体设定时校验主体列表
  9431. if (!$validation_failed && !empty($extra_roles)) {
  9432. $expected_roles = array_keys($extra_roles);
  9433. // 找出生成的主体中不在预期列表中的主体
  9434. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9435. if (!empty($invalid_roles)) {
  9436. $validation_failed = true;
  9437. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9438. }
  9439. }
  9440. // 仅当存在强制场景设定时校验场景列表
  9441. if (!$validation_failed && !empty($extra_scenes)) {
  9442. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9443. $expected_scenes = array_keys($extra_scenes);
  9444. // 找出生成的场景中不在预期列表中的场景
  9445. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9446. if (!empty($invalid_scenes)) {
  9447. $validation_failed = true;
  9448. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9449. }
  9450. }
  9451. // 仅当存在强制道具设定时校验道具列表
  9452. if (!$validation_failed && !empty($extra_props)) {
  9453. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9454. $expected_props = array_keys($extra_props);
  9455. // 找出生成的道具中不在预期列表中的道具
  9456. $invalid_props = array_diff($generated_props, $expected_props);
  9457. if (!empty($invalid_props)) {
  9458. $validation_failed = true;
  9459. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9460. }
  9461. }
  9462. }
  9463. } else {
  9464. // 如果没有anime_script_id,只检查是否有acts数据
  9465. if (empty($episode_arr['acts'])) {
  9466. $validation_failed = true;
  9467. $validation_error_msg = '未生成分镜剧本相关的内容';
  9468. } else {
  9469. // 校验主体列表:不能为空主体(旁白不算)
  9470. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9471. // 过滤掉"旁白"角色
  9472. $generated_roles = array_filter($generated_roles, function($role) {
  9473. return $role !== '旁白';
  9474. });
  9475. if (empty($generated_roles)) {
  9476. $validation_failed = true;
  9477. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9478. }
  9479. }
  9480. }
  9481. // 重试逻辑
  9482. while ($validation_failed && $retry_count < $max_retries) {
  9483. $retry_count++;
  9484. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9485. 'reason' => $validation_error_msg,
  9486. 'anime_id' => $anime_id,
  9487. 'episode_number' => $episode_number
  9488. ]);
  9489. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9490. 'reason' => $validation_error_msg,
  9491. 'anime_id' => $anime_id
  9492. ]);
  9493. // 发送流式重试提示
  9494. yield [
  9495. 'type' => 'retry',
  9496. 'retry_count' => $retry_count,
  9497. 'reason' => $validation_error_msg
  9498. ];
  9499. // 构建重试提示词
  9500. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9501. if ($anime_script_id) {
  9502. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9503. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9504. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9505. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9506. } else {
  9507. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9508. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9509. }
  9510. // 添加重试消息到messages
  9511. $messages[] = [
  9512. 'role' => 'assistant',
  9513. 'content' => $fullContent
  9514. ];
  9515. $messages[] = [
  9516. 'role' => 'user',
  9517. 'content' => $retry_prompt
  9518. ];
  9519. // 更新post_data的messages
  9520. $post_data['messages'] = $messages;
  9521. // 重新调用API
  9522. try {
  9523. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9524. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9525. } else if (in_array($model, $this->gpt_text_models)) {
  9526. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9527. } else if (in_array($model, $this->gemini_text_models)) {
  9528. // Gemini 模型使用 Gemini API
  9529. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9530. } else {
  9531. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9532. }
  9533. // 处理流式输出
  9534. $fullContent = '';
  9535. $fullReasoningContent = '';
  9536. foreach ($streamGenerator as $chunk) {
  9537. if (isset($chunk['type'])) {
  9538. if ($chunk['type'] === 'done') {
  9539. $fullContent = $chunk['full_content'];
  9540. $fullReasoningContent = $chunk['full_reasoning'];
  9541. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9542. } else {
  9543. yield $chunk;
  9544. }
  9545. }
  9546. }
  9547. // 重新解析内容
  9548. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9549. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9550. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9551. $episode_arr = handleEpisodeContentForAce($fullContent);
  9552. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9553. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9554. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9555. // }
  9556. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9557. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9558. // 重新验证
  9559. $validation_failed = false;
  9560. $validation_error_msg = '';
  9561. if ($anime_script_id) {
  9562. if (empty($episode_arr['acts'])) {
  9563. $validation_failed = true;
  9564. $validation_error_msg = '未生成分镜剧本相关的内容';
  9565. } else {
  9566. // 校验主体列表:不能为空主体(旁白不算)
  9567. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9568. // 过滤掉"旁白"角色
  9569. $generated_roles = array_filter($generated_roles, function($role) {
  9570. return $role !== '旁白';
  9571. });
  9572. if (empty($generated_roles)) {
  9573. $validation_failed = true;
  9574. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9575. }
  9576. // 仅当存在强制主体设定时校验主体列表
  9577. if (!$validation_failed && !empty($extra_roles)) {
  9578. $expected_roles = array_keys($extra_roles);
  9579. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9580. if (!empty($invalid_roles)) {
  9581. $validation_failed = true;
  9582. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9583. }
  9584. }
  9585. // 仅当存在强制场景设定时校验场景列表
  9586. if (!$validation_failed && !empty($extra_scenes)) {
  9587. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9588. $expected_scenes = array_keys($extra_scenes);
  9589. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9590. if (!empty($invalid_scenes)) {
  9591. $validation_failed = true;
  9592. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9593. }
  9594. }
  9595. // 仅当存在强制道具设定时校验道具列表
  9596. if (!$validation_failed && !empty($extra_props)) {
  9597. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9598. $expected_props = array_keys($extra_props);
  9599. $invalid_props = array_diff($generated_props, $expected_props);
  9600. if (!empty($invalid_props)) {
  9601. $validation_failed = true;
  9602. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9603. }
  9604. }
  9605. }
  9606. } else {
  9607. if (empty($episode_arr['acts'])) {
  9608. $validation_failed = true;
  9609. $validation_error_msg = '未生成分镜剧本相关的内容';
  9610. } else {
  9611. // 校验主体列表:不能为空主体(旁白不算)
  9612. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9613. // 过滤掉"旁白"角色
  9614. $generated_roles = array_filter($generated_roles, function($role) {
  9615. return $role !== '旁白';
  9616. });
  9617. if (empty($generated_roles)) {
  9618. $validation_failed = true;
  9619. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9620. }
  9621. }
  9622. }
  9623. } catch (\Exception $e) {
  9624. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9625. 'trace' => $e->getTraceAsString()
  9626. ]);
  9627. break;
  9628. }
  9629. }
  9630. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  9631. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  9632. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  9633. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  9634. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  9635. if ($validation_failed && $retry_count >= $max_retries) {
  9636. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9637. 'retry_count' => $retry_count,
  9638. 'last_error' => $validation_error_msg
  9639. ]);
  9640. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9641. 'error' => $validation_error_msg,
  9642. 'anime_id' => $anime_id
  9643. ]);
  9644. $validation_failed = false;
  9645. $validation_error_msg = '';
  9646. }
  9647. // 如果重试后仍然失败
  9648. if ($validation_failed) {
  9649. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9650. 'retry_count' => $retry_count,
  9651. 'last_error' => $validation_error_msg
  9652. ]);
  9653. try {
  9654. $now = date('Y-m-d H:i:s');
  9655. $records = [
  9656. [
  9657. 'uid' => $uid,
  9658. 'anime_id' => $anime_id,
  9659. 'sequence' => $episode_number,
  9660. 'role' => 'user',
  9661. 'content' => $prompt,
  9662. 'created_at' => $now,
  9663. 'updated_at' => $now
  9664. ],
  9665. [
  9666. 'uid' => $uid,
  9667. 'anime_id' => $anime_id,
  9668. 'sequence' => $episode_number,
  9669. 'role' => 'assistant',
  9670. 'content' => $fullContent,
  9671. 'created_at' => $now,
  9672. 'updated_at' => $now
  9673. ]
  9674. ];
  9675. DB::table('mp_anime_records')->insert($records);
  9676. } catch (\Exception $e) {
  9677. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9678. }
  9679. yield [
  9680. 'type' => 'done',
  9681. 'episode' => [],
  9682. 'answer' => $fullContent,
  9683. 'reasoning' => $fullReasoningContent,
  9684. 'usage' => $usage,
  9685. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9686. ];
  9687. return;
  9688. }
  9689. // 验证成功,记录日志
  9690. if ($retry_count > 0) {
  9691. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9692. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9693. }
  9694. // 老逻辑
  9695. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  9696. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  9697. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  9698. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  9699. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  9700. $existing_props = is_array($existing_props) ? $existing_props : [];
  9701. $now = date('Y-m-d H:i:s');
  9702. try {
  9703. DB::beginTransaction();
  9704. $saveResult = $this->saveEpisodeVersionData(
  9705. $anime_id,
  9706. $episode_number,
  9707. $episode_arr,
  9708. $existing_roles,
  9709. $existing_scenes,
  9710. $existing_props,
  9711. $current_episode,
  9712. $base_episode,
  9713. $is_regenerate_version,
  9714. $content,
  9715. $now,
  9716. $ref_products
  9717. );
  9718. $episode = $saveResult['episode'];
  9719. $episode_id = $saveResult['episode_id'];
  9720. $merged_roles = $saveResult['merged_roles'];
  9721. $merged_scenes = $saveResult['merged_scenes'];
  9722. $merged_props = $saveResult['merged_props'];
  9723. $record_content = $origin_prompt;
  9724. if ($uploaded_content !== '') {
  9725. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9726. }
  9727. $records = [
  9728. [
  9729. 'uid' => $uid,
  9730. 'anime_id' => $anime_id,
  9731. 'role' => 'user',
  9732. 'content' => $record_content,
  9733. 'sequence' => $episode_number,
  9734. 'episode_id' => $episode_id,
  9735. 'created_at' => $now,
  9736. 'updated_at' => $now
  9737. ],
  9738. [
  9739. 'uid' => $uid,
  9740. 'anime_id' => $anime_id,
  9741. 'role' => 'assistant',
  9742. 'content' => $fullContent,
  9743. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9744. 'sequence' => $episode_number,
  9745. 'episode_id' => $episode_id,
  9746. 'created_at' => $now,
  9747. 'updated_at' => $now
  9748. ]
  9749. ];
  9750. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9751. if (!$boolen4) {
  9752. Utils::throwError('20003:对话记录保存失败');
  9753. }
  9754. // 保存模型到anime表
  9755. $update_anime_data = [
  9756. 'model' => $model,
  9757. 'updated_at' => $now
  9758. ];
  9759. if ($uploaded_content) {
  9760. $update_anime_data['content'] = $uploaded_content;
  9761. }
  9762. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9763. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9764. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9765. 'anime_id' => $anime_id,
  9766. 'episode_number' => $episode_number,
  9767. 'model' => $model,
  9768. 'source' => 'chatForAce',
  9769. ]);
  9770. }catch (\Exception $e) {
  9771. DB::rollBack();
  9772. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9773. yield [
  9774. 'type' => 'done',
  9775. 'answer' => $fullContent,
  9776. 'reasoning' => $fullReasoningContent,
  9777. 'usage' => $usage,
  9778. 'error' => $e->getMessage(),
  9779. ];
  9780. return;
  9781. }
  9782. DB::commit();
  9783. if ($is_global_generate_pics) {
  9784. // // 批量生成全局角色图片
  9785. // $this->batchSetGlobalRoleImg([
  9786. // 'anime_id' => $anime_id,
  9787. // ], true);
  9788. // // 批量生成全局场景图片
  9789. // $this->batchSetGlobalSceneImg([
  9790. // 'anime_id' => $anime_id,
  9791. // ], true);
  9792. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9793. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9794. }
  9795. $episode['episode_id'] = $episode_id;
  9796. $episode['roles'] = $merged_roles;
  9797. $episode['scenes'] = $merged_scenes;
  9798. $episode['props'] = $merged_props;
  9799. $episode['end_episode_sequence'] = $end_episode_sequence;
  9800. // 获取mp_animes表中的视频参数
  9801. $episode['video_params'] = [
  9802. 'video_model' => getProp($anime, 'video_model'),
  9803. 'video_resolution' => getProp($anime, 'video_resolution'),
  9804. 'ratio' => getProp($anime, 'video_ratio'),
  9805. ];
  9806. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9807. yield [
  9808. 'type' => 'done',
  9809. 'episode' => $episode,
  9810. 'answer' => $fullContent,
  9811. 'reasoning' => $fullReasoningContent,
  9812. 'usage' => $usage
  9813. ];
  9814. }
  9815. /**
  9816. * chatForAce的非流式版本 - 用于定时任务
  9817. * 只获取最终 type=done 的数据,并验证必要字段
  9818. *
  9819. * @param array $data 请求数据
  9820. * @return array 生成结果
  9821. */
  9822. public function chatForAceNonStream($data) {
  9823. $finalResult = null;
  9824. // 调用流式方法,只保存 type=done 的数据
  9825. foreach ($this->chatForAce($data) as $chunk) {
  9826. // 只关注最终结果
  9827. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9828. $finalResult = $chunk;
  9829. break; // 找到 done 就退出循环
  9830. }
  9831. }
  9832. // 验证最终结果
  9833. if (!$finalResult) {
  9834. return ['error' => '生成失败:未获取到最终结果'];
  9835. }
  9836. // 检查是否有错误
  9837. if (isset($finalResult['error']) && $finalResult['error']) {
  9838. return $finalResult;
  9839. }
  9840. // 验证必要字段
  9841. $episode = $finalResult['episode'] ?? [];
  9842. // 验证 roles(旁白不算主体,过滤后不能为空)
  9843. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9844. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9845. }
  9846. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  9847. return $role !== '旁白';
  9848. });
  9849. if (empty($nonNarratorRoles)) {
  9850. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  9851. }
  9852. // 验证 scenes
  9853. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9854. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9855. }
  9856. // 验证 props(道具可以为空,但必须存在且为数组)
  9857. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9858. $episode['props'] = [];
  9859. }
  9860. // 验证 acts(分镜剧本)
  9861. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9862. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9863. }
  9864. // 更新验证后的 episode 数据
  9865. $finalResult['episode'] = $episode;
  9866. // 记录验证成功日志
  9867. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9868. 'roles_count' => count($episode['roles']),
  9869. 'scenes_count' => count($episode['scenes']),
  9870. 'props_count' => count($episode['props']),
  9871. 'acts_count' => count($episode['acts'])
  9872. ]);
  9873. return $finalResult;
  9874. }
  9875. /**
  9876. * 批量生成多个分集
  9877. *
  9878. * @param array $data 请求数据
  9879. * @return array 任务信息
  9880. */
  9881. public function batchGenerateEpisodes($data) {
  9882. $uid = Site::getUid();
  9883. $cpid = Site::getCpid();
  9884. $anime_id = getProp($data, 'anime_id');
  9885. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9886. if (!$anime_id) {
  9887. Utils::throwError('20003:anime_id参数缺失');
  9888. }
  9889. if ($generate_episode_number < 1) {
  9890. Utils::throwError('20003:生成集数必须大于0');
  9891. }
  9892. // 获取动漫信息
  9893. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9894. if (!$anime) {
  9895. Utils::throwError('20003:该剧集不存在');
  9896. }
  9897. // 检查是否是全能模式
  9898. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9899. Utils::throwError('20003:只有全能模式才支持批量生成');
  9900. }
  9901. // 检查是否是多剧集模式
  9902. if ((int)getProp($anime, 'is_multi') !== 1) {
  9903. Utils::throwError('20003:单剧集不支持批量生成');
  9904. }
  9905. // 获取当前已生成的最大集数
  9906. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9907. ->where('anime_id', $anime_id)
  9908. ->where('is_default', 1)
  9909. ->max('episode_number');
  9910. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9911. // 确定起始集数
  9912. $startEpisodeNumber = $currentMaxEpisode + 1;
  9913. // 计算结束集数
  9914. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9915. // 检查是否超过总集数限制
  9916. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9917. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9918. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9919. }
  9920. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  9921. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  9922. ->where('anime_id', $anime_id)
  9923. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9924. ->whereIn('status', ['pending', 'processing', 'completed'])
  9925. ->count();
  9926. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  9927. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  9928. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  9929. if ($needEpisodeCount > 0) {
  9930. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  9931. }
  9932. $now = date('Y-m-d H:i:s');
  9933. $createdTasks = [];
  9934. $skippedTasks = [];
  9935. // 为每一集创建详情记录
  9936. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9937. // 检查是否已有该集的任务记录
  9938. $existingTask = DB::table('mp_batch_episode_generation_details')
  9939. ->where('anime_id', $anime_id)
  9940. ->where('episode_number', $episodeNumber)
  9941. ->first();
  9942. if ($existingTask) {
  9943. // 如果已存在且未完成,跳过
  9944. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9945. $skippedTasks[] = $episodeNumber;
  9946. continue;
  9947. }
  9948. // 如果是失败状态,可以重新创建(删除旧记录)
  9949. if ($existingTask->status === 'failed') {
  9950. DB::table('mp_batch_episode_generation_details')
  9951. ->where('id', $existingTask->id)
  9952. ->delete();
  9953. }
  9954. // 如果是已完成状态,也跳过
  9955. if ($existingTask->status === 'completed') {
  9956. $skippedTasks[] = $episodeNumber;
  9957. continue;
  9958. }
  9959. }
  9960. // 准备任务数据
  9961. $taskData = [
  9962. 'anime_id' => $anime_id,
  9963. 'uid' => $uid,
  9964. 'cpid' => $cpid,
  9965. 'episode_number' => $episodeNumber,
  9966. 'status' => 'pending',
  9967. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9968. 'retry_count' => 0,
  9969. 'created_at' => $now,
  9970. 'updated_at' => $now
  9971. ];
  9972. // 创建任务记录
  9973. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9974. if ($taskId) {
  9975. $createdTasks[] = $episodeNumber;
  9976. }
  9977. }
  9978. if (empty($createdTasks)) {
  9979. if (!empty($skippedTasks)) {
  9980. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9981. } else {
  9982. Utils::throwError('20003:创建批量生成任务失败');
  9983. }
  9984. }
  9985. return [
  9986. 'anime_id' => $anime_id,
  9987. 'start_episode' => $startEpisodeNumber,
  9988. 'end_episode' => $endEpisodeNumber,
  9989. 'total_episodes' => $generate_episode_number,
  9990. 'created_episodes' => $createdTasks,
  9991. 'skipped_episodes' => $skippedTasks,
  9992. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9993. "已创建: " . implode(',', $createdTasks) .
  9994. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9995. ];
  9996. }
  9997. /**
  9998. * 获取批量生成任务状态
  9999. *
  10000. * @param array $data 请求数据
  10001. * @return array 任务状态信息
  10002. */
  10003. public function getBatchGenerationTaskStatus($data) {
  10004. $anime_id = getProp($data, 'anime_id');
  10005. if (!$anime_id) {
  10006. Utils::throwError('20003:anime_id参数缺失');
  10007. }
  10008. // 获取该anime的所有任务
  10009. $tasks = DB::table('mp_batch_episode_generation_details')
  10010. ->where('anime_id', $anime_id)
  10011. ->orderBy('episode_number')
  10012. ->get()
  10013. ->map(function($item) {
  10014. return [
  10015. 'id' => $item->id,
  10016. 'episode_number' => $item->episode_number,
  10017. 'status' => $item->status,
  10018. 'error_message' => $item->error_message,
  10019. 'retry_count' => $item->retry_count,
  10020. 'created_at' => $item->created_at,
  10021. 'updated_at' => $item->updated_at,
  10022. 'completed_at' => $item->completed_at
  10023. ];
  10024. })
  10025. ->toArray();
  10026. if (empty($tasks)) {
  10027. Utils::throwError('20003:该剧集没有批量生成任务');
  10028. }
  10029. // 统计各状态数量
  10030. $totalCount = count($tasks);
  10031. $pendingCount = 0;
  10032. $processingCount = 0;
  10033. $completedCount = 0;
  10034. $failedCount = 0;
  10035. $failed_episodes = [];
  10036. foreach ($tasks as $task) {
  10037. switch ($task['status']) {
  10038. case 'pending':
  10039. $pendingCount++;
  10040. break;
  10041. case 'processing':
  10042. $processingCount++;
  10043. break;
  10044. case 'completed':
  10045. $completedCount++;
  10046. break;
  10047. case 'failed':
  10048. $failedCount++;
  10049. // 组装失败分集对象(新对象):分集序号、错误原因
  10050. $failed_episodes[] = [
  10051. 'episode_number' => $task['episode_number'],
  10052. 'error_message' => $task['error_message'] ?? ''
  10053. ];
  10054. break;
  10055. }
  10056. }
  10057. // 计算进度百分比
  10058. $progress = 0;
  10059. if ($totalCount > 0) {
  10060. $progress = round(($completedCount / $totalCount) * 100, 2);
  10061. }
  10062. // 判断整体状态
  10063. $overallStatus = 'processing';
  10064. if ($completedCount === $totalCount) {
  10065. $overallStatus = 'completed';
  10066. } elseif ($pendingCount === $totalCount) {
  10067. $overallStatus = 'pending';
  10068. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  10069. $overallStatus = 'failed';
  10070. }
  10071. return [
  10072. 'anime_id' => $anime_id,
  10073. 'total_episodes' => $totalCount,
  10074. 'pending_count' => $pendingCount,
  10075. 'processing_count' => $processingCount,
  10076. 'completed_count' => $completedCount,
  10077. 'failed_count' => $failedCount,
  10078. 'progress' => $progress,
  10079. 'overall_status' => $overallStatus,
  10080. 'failed_episodes' => $failed_episodes,
  10081. 'tasks' => $tasks
  10082. ];
  10083. }
  10084. /**
  10085. * 将生成内容中不在强制列表中的资源合并进强制列表
  10086. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  10087. *
  10088. * @param array $generated 生成内容中的资源列表
  10089. * @param array $forced 强制资源列表(key为资源名称)
  10090. * @param string $type 资源类型:role、scene、prop
  10091. * @return array
  10092. */
  10093. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  10094. {
  10095. foreach ($generated as $item) {
  10096. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  10097. if ($name === null || $name === '') {
  10098. continue;
  10099. }
  10100. if ($name === '旁白') {
  10101. continue;
  10102. }
  10103. if (!isset($forced[$name])) {
  10104. $forced[$name] = $item;
  10105. }
  10106. }
  10107. return $forced;
  10108. }
  10109. /**
  10110. * 智能匹配并替换主体和场景名称
  10111. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10112. *
  10113. * @param array $episode_arr 解析后的剧集数据
  10114. * @param array $extra_roles 强制主体设定(key为主体名称)
  10115. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10116. * @return array 替换后的剧集数据
  10117. */
  10118. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10119. $replaced_count = 0;
  10120. // 1. 处理主体列表
  10121. if (!empty($episode_arr['roles'])) {
  10122. foreach ($episode_arr['roles'] as &$role) {
  10123. $generated_role_name = $role['role'] ?? '';
  10124. // 跳过旁白
  10125. if ($generated_role_name === '旁白') {
  10126. continue;
  10127. }
  10128. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10129. if (!isset($extra_roles[$generated_role_name])) {
  10130. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10131. if ($matched_role) {
  10132. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10133. $role['role'] = $matched_role;
  10134. $replaced_count++;
  10135. }
  10136. }
  10137. }
  10138. }
  10139. // 2. 处理场景列表
  10140. if (!empty($episode_arr['scenes'])) {
  10141. foreach ($episode_arr['scenes'] as &$scene) {
  10142. $generated_scene_name = $scene['scene'] ?? '';
  10143. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10144. if (!isset($extra_scenes[$generated_scene_name])) {
  10145. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10146. if ($matched_scene) {
  10147. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10148. $scene['scene'] = $matched_scene;
  10149. $replaced_count++;
  10150. }
  10151. }
  10152. }
  10153. }
  10154. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10155. if (!empty($episode_arr['acts'])) {
  10156. foreach ($episode_arr['acts'] as &$act) {
  10157. if (!empty($act['segments'])) {
  10158. foreach ($act['segments'] as &$segment) {
  10159. if (!empty($segment['segment_content'])) {
  10160. $original_content = $segment['segment_content'];
  10161. $replaced_content = $original_content;
  10162. // 替换场景名 - 在文本中查找并替换
  10163. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10164. // 尝试找到可能的短名称
  10165. $potential_short_names = [];
  10166. // 提取场景名的主要部分(冒号之前)
  10167. if (mb_strpos($full_scene_name, ':') !== false) {
  10168. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10169. $potential_short_names[] = $short_name;
  10170. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10171. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10172. $potential_short_names[] = $short_name;
  10173. }
  10174. // 替换场景字段中的短名称
  10175. foreach ($potential_short_names as $short_name) {
  10176. if ($short_name !== $full_scene_name) {
  10177. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10178. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10179. if ($new_content !== $replaced_content) {
  10180. $replaced_content = $new_content;
  10181. $replaced_count++;
  10182. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10183. }
  10184. }
  10185. }
  10186. }
  10187. // 替换配音角色名(跳过旁白)
  10188. foreach (array_keys($extra_roles) as $full_role_name) {
  10189. if ($full_role_name === '旁白') {
  10190. continue;
  10191. }
  10192. // 尝试找到可能的短名称
  10193. $potential_short_names = [];
  10194. // 提取角色名的主要部分(短横线之前)
  10195. if (mb_strpos($full_role_name, '-') !== false) {
  10196. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10197. $potential_short_names[] = $short_name;
  10198. }
  10199. // 替换配音台词中的短名称
  10200. foreach ($potential_short_names as $short_name) {
  10201. if ($short_name !== $full_role_name) {
  10202. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10203. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10204. if ($new_content !== $replaced_content) {
  10205. $replaced_content = $new_content;
  10206. $replaced_count++;
  10207. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10208. }
  10209. }
  10210. }
  10211. }
  10212. // 如果有替换,更新segment_content
  10213. if ($replaced_content !== $original_content) {
  10214. $segment['segment_content'] = $replaced_content;
  10215. }
  10216. }
  10217. }
  10218. }
  10219. }
  10220. }
  10221. if ($replaced_count > 0) {
  10222. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10223. 'replaced_count' => $replaced_count
  10224. ]);
  10225. }
  10226. return $episode_arr;
  10227. }
  10228. /**
  10229. * 查找匹配的名称
  10230. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10231. *
  10232. * @param string $generated_name 生成的名称
  10233. * @param array $expected_names 预期的名称列表
  10234. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10235. */
  10236. private function findMatchingName($generated_name, $expected_names) {
  10237. if (empty($generated_name)) {
  10238. return null;
  10239. }
  10240. // 尝试精确匹配
  10241. if (in_array($generated_name, $expected_names)) {
  10242. return $generated_name;
  10243. }
  10244. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10245. foreach ($expected_names as $expected_name) {
  10246. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10247. if (mb_strpos($expected_name, $generated_name) === 0) {
  10248. return $expected_name;
  10249. }
  10250. }
  10251. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10252. // 这样可以处理一些变体,但优先级较低
  10253. foreach ($expected_names as $expected_name) {
  10254. if (mb_strpos($expected_name, $generated_name) !== false) {
  10255. return $expected_name;
  10256. }
  10257. }
  10258. return null;
  10259. }
  10260. /**
  10261. * 重新生成分段剧本
  10262. * @param array $data 包含以下字段:
  10263. * - prompt: string|null 用户修改要求(可选)
  10264. * - template_id: int|null 提示词模板ID(可选)
  10265. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10266. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10267. * @return array 返回生成结果
  10268. */
  10269. public function regenerateSegmentScript($data) {
  10270. $uid = Site::getUid();
  10271. $prompt = trim((string)getProp($data, 'prompt', ''));
  10272. $template_id = getProp($data, 'template_id', 0);
  10273. $act_id = getProp($data, 'act_id', 0);
  10274. $episode_id = getProp($data, 'episode_id', 0);
  10275. // 验证:prompt和template_id至少提供一个
  10276. if (empty($prompt) && empty($template_id)) {
  10277. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10278. }
  10279. // 验证:act_id和episode_id二选一
  10280. if (empty($act_id) && empty($episode_id)) {
  10281. Utils::throwError('20003:请提供片段ID或剧集ID');
  10282. }
  10283. if (!empty($act_id) && !empty($episode_id)) {
  10284. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10285. }
  10286. // 积分余额预检(仅剧集ID模式收费)
  10287. if (!empty($episode_id)) {
  10288. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  10289. }
  10290. // 如果提供了template_id,获取模板提示词
  10291. $template_prompt = '';
  10292. if ($template_id > 0) {
  10293. $template = DB::table('mp_prompt_templates')
  10294. ->where('id', $template_id)
  10295. ->where('is_deleted', 0)
  10296. ->first();
  10297. if (!$template) {
  10298. Utils::throwError('20003:提示词模板不存在或已删除');
  10299. }
  10300. $template_prompt = $template->template_prompt ?? '';
  10301. }
  10302. // 合并用户提示词和模板提示词
  10303. $final_prompt = '';
  10304. if (!empty($template_prompt)) {
  10305. $final_prompt = $template_prompt;
  10306. if (!empty($prompt)) {
  10307. $final_prompt .= "\n\n补充要求:" . $prompt;
  10308. }
  10309. } else {
  10310. $final_prompt = $prompt;
  10311. }
  10312. // 获取需要重新生成的内容参考
  10313. $reference_content = '';
  10314. $target_episode_id = 0;
  10315. $target_anime_id = 0;
  10316. $target_episode_number = 0;
  10317. if ($act_id > 0) {
  10318. // 单个片段模式:获取该片段的内容
  10319. $segment = DB::table('mp_episode_segments')
  10320. ->where('id', $act_id)
  10321. ->first();
  10322. if (!$segment) {
  10323. Utils::throwError('20003:片段不存在');
  10324. }
  10325. $target_episode_id = $segment->episode_id;
  10326. $target_anime_id = $segment->anime_id;
  10327. $target_episode_number = $segment->episode_number;
  10328. $reference_content = $segment->act_content ?? '';
  10329. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10330. } else {
  10331. // 整个剧集模式:获取所有片段的内容
  10332. $segments = DB::table('mp_episode_segments')
  10333. ->where('episode_id', $episode_id)
  10334. ->orderBy('act_number')
  10335. ->get();
  10336. if ($segments->isEmpty()) {
  10337. Utils::throwError('20003:该剧集没有片段数据');
  10338. }
  10339. $target_episode_id = $episode_id;
  10340. $target_anime_id = $segments[0]->anime_id;
  10341. $target_episode_number = $segments[0]->episode_number;
  10342. // 拼接所有片段内容,保留格式用于AI理解
  10343. $act_contents = [];
  10344. foreach ($segments as $seg) {
  10345. $act_number = $seg->act_number;
  10346. $act_content = $seg->act_content ?? '';
  10347. if (!empty($act_content)) {
  10348. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  10349. }
  10350. }
  10351. $reference_content = implode("\n\n", $act_contents);
  10352. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  10353. if ($episode_content) {
  10354. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  10355. }else {
  10356. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10357. }
  10358. }
  10359. if (empty($reference_content)) {
  10360. Utils::throwError('20003:没有可参考的片段内容');
  10361. }
  10362. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  10363. $episode = DB::table('mp_anime_episodes')
  10364. ->where('id', $target_episode_id)
  10365. ->first();
  10366. if (!$episode) {
  10367. Utils::throwError('20003:剧集不存在');
  10368. }
  10369. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  10370. $anime_script_id = getProp($anime, 'script_id');
  10371. $intro = $episode->intro ?? '';
  10372. $art_style = $episode->art_style ?? '';
  10373. $roles = json_decode($episode->roles ?? '[]', true);
  10374. $scenes = json_decode($episode->scenes ?? '[]', true);
  10375. $props = json_decode($episode->props ?? '[]', true);
  10376. // 构建提示词中的主体列表和场景列表参考
  10377. $roles_ref = '';
  10378. if (!empty($roles) && is_array($roles)) {
  10379. $roles_list = [];
  10380. foreach ($roles as $role) {
  10381. $role_name = getProp($role, 'role', '');
  10382. $role_desc = getProp($role, 'description', '');
  10383. $pic_prompt = getProp($role, 'pic_prompt', '');
  10384. $voice_prompt = getProp($role, 'voice_prompt', '');
  10385. if (!empty($role_name)) {
  10386. $role_line = $role_name;
  10387. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  10388. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  10389. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  10390. $roles_list[] = $role_line;
  10391. }
  10392. }
  10393. if (!empty($roles_list)) {
  10394. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  10395. }
  10396. }
  10397. $scenes_ref = '';
  10398. if (!empty($scenes) && is_array($scenes)) {
  10399. $scenes_list = [];
  10400. foreach ($scenes as $scene) {
  10401. $scene_name = getProp($scene, 'scene', '');
  10402. $scene_desc = getProp($scene, 'description', '');
  10403. $pic_prompt = getProp($scene, 'pic_prompt', '');
  10404. if (!empty($scene_name)) {
  10405. $scene_line = $scene_name;
  10406. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  10407. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  10408. $scenes_list[] = $scene_line;
  10409. }
  10410. }
  10411. if (!empty($scenes_list)) {
  10412. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  10413. }
  10414. }
  10415. $props_ref = '';
  10416. if (!empty($props) && is_array($props)) {
  10417. $props_list = [];
  10418. foreach ($props as $prop) {
  10419. $prop_name = getProp($prop, 'prop', '');
  10420. $prop_desc = getProp($prop, 'description', '');
  10421. $pic_prompt = getProp($prop, 'pic_prompt', '');
  10422. if (!empty($prop_name)) {
  10423. $prop_line = $prop_name;
  10424. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  10425. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  10426. $props_list[] = $prop_line;
  10427. }
  10428. }
  10429. if (!empty($props_list)) {
  10430. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  10431. }
  10432. }
  10433. // 构建美术风格参考
  10434. $art_style_ref = '';
  10435. if (!empty($art_style)) {
  10436. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  10437. }
  10438. // 构建内容简介参考
  10439. $intro_ref = '';
  10440. if (!empty($intro)) {
  10441. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  10442. }
  10443. // 构建完整的AI提示词
  10444. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  10445. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  10446. $user_prompt .= $intro_ref;
  10447. $user_prompt .= $art_style_ref;
  10448. $user_prompt .= $reference_content;
  10449. // $user_prompt .= $roles_ref;
  10450. // $user_prompt .= $scenes_ref;
  10451. $system_prompt = "\n\n【强制要求】\n";
  10452. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  10453. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  10454. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  10455. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  10456. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  10457. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  10458. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  10459. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  10460. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  10461. ###分段剧本
  10462. 片段数量:8
  10463. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10464. ##片段1
  10465. 时长:12s
  10466. 分镜1
  10467. 出场角色:刀疤脸
  10468. 场景:边境小镇街道
  10469. 出场道具:酒杯-高脚杯
  10470. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10471. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10472. 配音台词:
  10473. 背景音效:
  10474. 分镜2
  10475. 出场角色:刀疤脸
  10476. 场景:悦来酒馆
  10477. 出场道具:酒杯-高脚杯
  10478. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10479. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10480. 配音台词:
  10481. 背景音效:
  10482. 分镜3
  10483. 出场角色:刀疤脸
  10484. 场景:悦来酒馆
  10485. 出场道具:酒杯-高脚杯
  10486. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10487. 运镜:从中景推向令牌特写。
  10488. 配音台词:
  10489. 背景音效:
  10490. 分镜4
  10491. 出场角色:刀疤脸
  10492. 场景:悦来酒馆
  10493. 出场道具:酒杯-高脚杯
  10494. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10495. 运镜:极速推向酒水溅起的瞬间。
  10496. 配音台词:
  10497. 背景音效:
  10498. 分镜5
  10499. 出场角色:刀疤脸
  10500. 场景:悦来酒馆
  10501. 出场道具:酒杯-高脚杯
  10502. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10503. 运镜:固定机位,利用倾斜构图制造压迫感。
  10504. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10505. 背景音效:";
  10506. // 获取模型配置
  10507. $model = getProp($data, 'model');
  10508. if (!$model) {
  10509. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  10510. }
  10511. // 验证模型是否在可用模型表中
  10512. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10513. $model = 'deepseek-v4-pro';
  10514. }
  10515. // 模型兼容性处理
  10516. $thinkingMode = 'disabled';
  10517. $reasoningEffort = 'high';
  10518. if ($model === 'deepseek-chat') {
  10519. $model = 'deepseek-v4-flash';
  10520. $thinkingMode = 'disabled';
  10521. } elseif ($model === 'deepseek-reasoner') {
  10522. $model = 'deepseek-v4-flash';
  10523. $thinkingMode = 'enabled';
  10524. }
  10525. // 构建消息
  10526. $messages = [
  10527. [
  10528. 'role' => 'system',
  10529. 'content' => $system_prompt
  10530. ],
  10531. [
  10532. 'role' => 'user',
  10533. 'content' => $user_prompt
  10534. ]
  10535. ];
  10536. // dd($messages);
  10537. // 构建请求参数
  10538. $post_data = [
  10539. 'model' => $model,
  10540. 'messages' => $messages,
  10541. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10542. 'frequency_penalty' => 0,
  10543. 'presence_penalty' => 0,
  10544. 'response_format' => ['type' => 'text'],
  10545. 'thinking' => ['type' => $thinkingMode],
  10546. 'stream' => false // 非流式输出
  10547. ];
  10548. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10549. // 调用AI生成新的分段剧本
  10550. try {
  10551. $fullContent = '';
  10552. $usage = [];
  10553. // 根据模型类型选择调用方法
  10554. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10555. // DeepSeek 官方模型使用 DeepSeek API
  10556. $chatResult = $this->chatOnly($post_data);
  10557. } else if (in_array($model, $this->gpt_text_models)) {
  10558. // GPT 模型使用 TokenRouter API
  10559. $chatResult = $this->gpt54ChatOnly($post_data);
  10560. } else {
  10561. // 其他模型使用火山引擎API
  10562. $chatResult = $this->volcEngineChatCompletion($post_data);
  10563. }
  10564. if (is_array($chatResult)) {
  10565. $fullContent = $chatResult['fullContent'] ?? '';
  10566. $usage = $chatResult['usage'] ?? [];
  10567. }
  10568. $generated_content = $fullContent;
  10569. if (empty($generated_content)) {
  10570. Utils::throwError('20003:AI生成内容为空,请重试');
  10571. }
  10572. // 解析生成的内容 - 按片段分割
  10573. $parsed_segments = [];
  10574. // 先在开头添加换行符,确保第1片段也能被正确分割
  10575. $normalizedText = "\n" . $generated_content;
  10576. $parts = preg_split('/\n\s*##/', $normalizedText);
  10577. foreach ($parts as $part) {
  10578. $part = trim($part);
  10579. if (empty($part)) continue;
  10580. // 匹配"片段X"格式
  10581. if (!preg_match('/^片段\d+/', $part)) {
  10582. continue;
  10583. }
  10584. // 分离标题和内容
  10585. $lines = explode("\n", $part, 2);
  10586. $actTitle = trim($lines[0]);
  10587. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  10588. // 解析标题,提取序号
  10589. $actNumber = 0;
  10590. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  10591. $actNumber = intval($segmentTitleMatch[1]);
  10592. } else {
  10593. $actNumber = count($parsed_segments) + 1;
  10594. }
  10595. // 提取时长(仅保留数字)
  10596. $actDuration = 0;
  10597. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  10598. $actDurationStr = trim($actDurationMatch[1]);
  10599. // 提取数字部分(支持整数和小数)
  10600. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  10601. $actDuration = (float)$numMatch[1];
  10602. }
  10603. }
  10604. // 清理act_content:去除时长、旁白音色等非分镜内容行
  10605. // 只保留分镜内容,并确保分镜标记使用【】格式
  10606. $cleaned_content = '';
  10607. $content_lines = explode("\n", $actContent);
  10608. $is_capturing = false; // 标记是否开始捕获分镜内容
  10609. $count = 0;
  10610. foreach ($content_lines as $line) {
  10611. $trimmed_line = trim($line);
  10612. // 跳过时长和旁白音色行
  10613. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  10614. continue;
  10615. }
  10616. // 检测是否是分镜开始
  10617. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  10618. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  10619. $count++;
  10620. $is_capturing = true;
  10621. // 如果没有【】,则添加
  10622. if (!preg_match('/^【/u', $trimmed_line)) {
  10623. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  10624. }
  10625. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  10626. }
  10627. // 如果已经开始捕获,则添加该行
  10628. if ($is_capturing && !empty($trimmed_line)) {
  10629. $cleaned_content .= $trimmed_line."\n";
  10630. }
  10631. }
  10632. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  10633. $parsed_segments[] = [
  10634. 'act_number' => $actNumber,
  10635. 'act_title' => $actTitle,
  10636. 'act_duration' => $actDuration,
  10637. 'act_content' => $cleaned_content,
  10638. ];
  10639. }
  10640. if (empty($parsed_segments)) {
  10641. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  10642. }
  10643. // 收集所有资产名称(角色、场景、道具)
  10644. $product_names = [];
  10645. // 收集角色名称
  10646. if (!empty($roles) && is_array($roles)) {
  10647. foreach ($roles as $role) {
  10648. $role_name = getProp($role, 'role', '');
  10649. if (!empty($role_name)) {
  10650. $product_names[] = $role_name;
  10651. }
  10652. }
  10653. }
  10654. // 收集场景名称
  10655. if (!empty($scenes) && is_array($scenes)) {
  10656. foreach ($scenes as $scene) {
  10657. $scene_name = getProp($scene, 'scene', '');
  10658. if (!empty($scene_name)) {
  10659. $product_names[] = $scene_name;
  10660. }
  10661. }
  10662. }
  10663. // 收集道具名称
  10664. if (!empty($props) && is_array($props)) {
  10665. foreach ($props as $prop) {
  10666. $prop_name = getProp($prop, 'prop', '');
  10667. if (!empty($prop_name)) {
  10668. $product_names[] = $prop_name;
  10669. }
  10670. }
  10671. }
  10672. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10673. $product_names = array_unique($product_names);
  10674. usort($product_names, function($a, $b) {
  10675. return mb_strlen($b) - mb_strlen($a);
  10676. });
  10677. // 处理每个片段的 act_show_content
  10678. foreach ($parsed_segments as &$segment) {
  10679. $act_content = getProp($segment, 'act_content', '');
  10680. if (empty($act_content)) {
  10681. $segment['act_show_content'] = '';
  10682. continue;
  10683. }
  10684. $processed_content = $act_content;
  10685. // 统一替换所有资产名称为 {资产名} 格式
  10686. // 使用占位符避免嵌套替换问题
  10687. $placeholder_map = [];
  10688. $placeholder_index = 0;
  10689. foreach ($product_names as $product_name) {
  10690. // 转义特殊字符
  10691. $escaped_product = preg_quote($product_name, '/');
  10692. // 检查是否匹配且未被 {} 包裹
  10693. $processed_content = preg_replace_callback(
  10694. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10695. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10696. // 使用唯一占位符
  10697. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10698. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10699. $placeholder_index++;
  10700. return $placeholder;
  10701. },
  10702. $processed_content
  10703. );
  10704. }
  10705. // 将所有占位符替换回实际内容
  10706. foreach ($placeholder_map as $placeholder => $replacement) {
  10707. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10708. }
  10709. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10710. $shot_counter = 0;
  10711. $processed_content = preg_replace_callback(
  10712. '/【(?:镜头|分镜)(\d+)】/u',
  10713. function($matches) use (&$shot_counter) {
  10714. $shot_counter++;
  10715. return '【镜头' . $shot_counter . '】';
  10716. },
  10717. $processed_content
  10718. );
  10719. $segment['act_show_content'] = $processed_content;
  10720. }
  10721. unset($segment); // 解除引用
  10722. // 保存到数据库
  10723. $now = date('Y-m-d H:i:s');
  10724. $saved_acts = []; // 用于记录保存后的片段信息
  10725. if ($act_id > 0) {
  10726. // 单个片段模式:更新单条记录
  10727. if (count($parsed_segments) > 0) {
  10728. $new_segment = $parsed_segments[0];
  10729. $update_data = [
  10730. 'act_content' => getProp($new_segment, 'act_content', ''),
  10731. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  10732. 'act_title' => getProp($new_segment, 'act_title', ''),
  10733. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  10734. 'updated_at' => $now,
  10735. ];
  10736. DB::table('mp_episode_segments')
  10737. ->where('id', $act_id)
  10738. ->update($update_data);
  10739. // 获取更新后的记录
  10740. $updated_act = DB::table('mp_episode_segments')
  10741. ->where('id', $act_id)
  10742. ->first();
  10743. if ($updated_act) {
  10744. $saved_acts[] = [
  10745. 'act_id' => $updated_act->id,
  10746. 'act_number' => $updated_act->act_number,
  10747. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  10748. 'act_content' => $updated_act->act_content,
  10749. 'act_show_content' => $updated_act->act_show_content,
  10750. 'video_url' => $updated_act->video_url ?? '',
  10751. 'video_duration' => $updated_act->video_duration ?? 0,
  10752. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  10753. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  10754. ];
  10755. }
  10756. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  10757. }
  10758. } else {
  10759. // 整个剧集模式:删除原有记录并批量保存新记录
  10760. DB::beginTransaction();
  10761. try {
  10762. // 删除原有的所有片段记录
  10763. DB::table('mp_episode_segments')
  10764. ->where('episode_id', $target_episode_id)
  10765. ->delete();
  10766. // 批量插入新的片段记录
  10767. $segments_to_insert = [];
  10768. foreach ($parsed_segments as $index => $segment) {
  10769. $act_number = $index + 1;
  10770. $segments_to_insert[] = [
  10771. 'anime_id' => $target_anime_id,
  10772. 'episode_id' => $target_episode_id,
  10773. 'episode_number' => $target_episode_number,
  10774. 'act_number' => $act_number,
  10775. 'act_title' => getProp($segment, 'act_title', ''),
  10776. 'act_duration' => getProp($segment, 'act_duration', 0),
  10777. 'act_content' => getProp($segment, 'act_content', ''),
  10778. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  10779. 'created_at' => $now,
  10780. 'updated_at' => $now,
  10781. ];
  10782. }
  10783. if (!empty($segments_to_insert)) {
  10784. DB::table('mp_episode_segments')->insert($segments_to_insert);
  10785. }
  10786. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10787. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10788. 'anime_id' => $target_anime_id,
  10789. 'episode_id' => $target_episode_id,
  10790. 'model' => $model,
  10791. 'source' => 'regenerateSegmentScript',
  10792. ]);
  10793. DB::commit();
  10794. // 查询保存后的所有片段记录
  10795. $saved_segments = DB::table('mp_episode_segments')
  10796. ->where('episode_id', $target_episode_id)
  10797. ->orderBy('act_number')
  10798. ->get();
  10799. foreach ($saved_segments as $saved_segment) {
  10800. $saved_acts[] = [
  10801. 'act_id' => $saved_segment->id,
  10802. 'act_number' => $saved_segment->act_number,
  10803. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  10804. 'act_content' => $saved_segment->act_content,
  10805. 'act_show_content' => $saved_segment->act_show_content,
  10806. 'video_url' => $saved_segment->video_url ?? '',
  10807. 'video_duration' => $saved_segment->video_duration ?? 0,
  10808. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  10809. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  10810. ];
  10811. }
  10812. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  10813. 'episode_id' => $target_episode_id,
  10814. 'segments_count' => count($segments_to_insert)
  10815. ]);
  10816. } catch (\Exception $e) {
  10817. DB::rollBack();
  10818. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  10819. Utils::throwError('20003:保存失败,请重试');
  10820. }
  10821. }
  10822. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  10823. return [
  10824. 'anime_id' => $target_anime_id,
  10825. 'episode_id' => $target_episode_id,
  10826. 'title' => getProp($episode, 'title', ''),
  10827. 'episode_number' => $target_episode_number,
  10828. 'is_generated' => getProp($episode, 'is_generated', 0),
  10829. 'acts' => $saved_acts,
  10830. ];
  10831. } catch (\Exception $e) {
  10832. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  10833. throw $e;
  10834. }
  10835. }
  10836. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  10837. {
  10838. $episode_arr = [
  10839. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  10840. 'intro' => getProp($script_arr, 'intro'),
  10841. 'art_style' => getProp($script_arr, 'art_style'),
  10842. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10843. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10844. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10845. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  10846. ];
  10847. if (empty($episode_arr['acts'])) {
  10848. $fallback_episode_arr = handleEpisodeContent($fullContent);
  10849. if (!empty($fallback_episode_arr['acts'])) {
  10850. $episode_arr = array_merge($fallback_episode_arr, [
  10851. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  10852. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  10853. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  10854. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  10855. ]);
  10856. }
  10857. }
  10858. // if (!getProp($episode_arr, 'episode_title')) {
  10859. // $episode_title = '';
  10860. // $episodes = getProp($script_arr, 'episodes', []);
  10861. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  10862. // $episode_title = '第1集:' . $episodes[0]['title'];
  10863. // }
  10864. // if (!$episode_title) {
  10865. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  10866. // }
  10867. // $episode_arr['episode_title'] = $episode_title;
  10868. // }
  10869. return $episode_arr;
  10870. }
  10871. private function saveEpisodeVersionData(
  10872. int $anime_id,
  10873. int $episode_number,
  10874. array $episode_arr,
  10875. array $existing_roles,
  10876. array $existing_scenes,
  10877. array $existing_props,
  10878. $current_episode,
  10879. $base_episode,
  10880. bool $is_regenerate_version,
  10881. string $content,
  10882. string $now,
  10883. array $ref_products = []
  10884. ): array {
  10885. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10886. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10887. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10888. // 过滤掉关键字段为空的条目
  10889. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10890. return !empty($item['role'] ?? null);
  10891. }));
  10892. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10893. return !empty($item['scene'] ?? null);
  10894. }));
  10895. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10896. return !empty($item['prop'] ?? null);
  10897. }));
  10898. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10899. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10900. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10901. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10902. $ace_mode = getProp($anime, 'ace_mode');
  10903. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10904. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10905. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10906. $global_roles = is_array($global_roles) ? $global_roles : [];
  10907. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10908. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10909. $art_style_type = getProp($anime, 'art_style_type');
  10910. // 检查并创建 roles 的图片生成任务
  10911. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10912. // 检查并创建 scenes 的图片生成任务
  10913. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10914. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10915. if ($arr && is_array($arr)) {
  10916. $merged_roles = $arr['roles'];
  10917. $merged_scenes = $arr['scenes'];
  10918. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10919. }
  10920. // 确保数据是数组类型
  10921. if (!is_array($merged_roles)) {
  10922. dLog('deepseek')->error('merged_roles不是数组类型', [
  10923. 'type' => gettype($merged_roles),
  10924. 'value' => $merged_roles
  10925. ]);
  10926. $merged_roles = [];
  10927. }
  10928. if (!is_array($merged_scenes)) {
  10929. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10930. 'type' => gettype($merged_scenes),
  10931. 'value' => $merged_scenes
  10932. ]);
  10933. $merged_scenes = [];
  10934. }
  10935. if (!is_array($merged_props)) {
  10936. dLog('deepseek')->error('merged_props不是数组类型', [
  10937. 'type' => gettype($merged_props),
  10938. 'value' => $merged_props
  10939. ]);
  10940. $merged_props = [];
  10941. }
  10942. // 同步新出现的主体和场景到全局
  10943. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10944. $role_arr = [];
  10945. foreach ($merged_roles as $item) {
  10946. $role_arr[$item['role']] = $item;
  10947. }
  10948. $version_count = DB::table('mp_anime_episodes')
  10949. ->where('anime_id', $anime_id)
  10950. ->where('episode_number', $episode_number)
  10951. ->count('id');
  10952. $episode = [
  10953. 'anime_id' => $anime_id,
  10954. 'episode_number' => $episode_number,
  10955. 'title' => getProp($episode_arr, 'episode_title'),
  10956. 'content' => $content,
  10957. 'intro' => getProp($episode_arr, 'intro'),
  10958. 'art_style' => getProp($episode_arr, 'art_style'),
  10959. 'roles' => json_encode($merged_roles, 256),
  10960. 'scenes' => json_encode($merged_scenes, 256),
  10961. 'props' => json_encode($merged_props, 256),
  10962. 'generate_status' => '待执行',
  10963. 'generate_at' => $now,
  10964. 'is_default' => 1,
  10965. 'updated_at' => $now,
  10966. ];
  10967. $del_flag = false;
  10968. if ($is_regenerate_version) {
  10969. DB::table('mp_anime_episodes')
  10970. ->where('anime_id', $anime_id)
  10971. ->where('episode_number', $episode_number)
  10972. ->update(['is_default' => 0, 'updated_at' => $now]);
  10973. $episode['sequence'] = $version_count + 1;
  10974. $episode['created_at'] = $now;
  10975. $episode['cpid'] = Site::getCpid();
  10976. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10977. if (!$episode_id) {
  10978. Utils::throwError('20003:创建剧集版本失败');
  10979. }
  10980. } else {
  10981. $target_episode = $current_episode ?: $base_episode;
  10982. if ($target_episode) {
  10983. $episode_id = getProp($target_episode, 'id');
  10984. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10985. DB::table('mp_anime_episodes')
  10986. ->where('anime_id', $anime_id)
  10987. ->where('episode_number', $episode_number)
  10988. ->where('id', '<>', $episode_id)
  10989. ->update(['is_default' => 0, 'updated_at' => $now]);
  10990. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10991. if ($boolen === false) {
  10992. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10993. Utils::throwError('20003:分集内容保存失败');
  10994. }
  10995. $del_flag = true;
  10996. } else {
  10997. DB::table('mp_anime_episodes')
  10998. ->where('anime_id', $anime_id)
  10999. ->where('episode_number', $episode_number)
  11000. ->update(['is_default' => 0, 'updated_at' => $now]);
  11001. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  11002. $episode['created_at'] = $now;
  11003. $episode['cpid'] = Site::getCpid();
  11004. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11005. if (!$episode_id) {
  11006. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  11007. Utils::throwError('20003:分集内容保存失败');
  11008. }
  11009. }
  11010. }
  11011. $segments = [];
  11012. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11013. // 如果是第2集及以后,获取上一集的主体音色数据
  11014. $previous_roles_voice = [];
  11015. if ($episode_number >= 2) {
  11016. $previous_episode = DB::table('mp_anime_episodes')
  11017. ->where('anime_id', $anime_id)
  11018. ->where('episode_number', $episode_number - 1)
  11019. ->where('is_default', 1)
  11020. ->first();
  11021. if ($previous_episode) {
  11022. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  11023. if (is_array($previous_roles)) {
  11024. foreach ($previous_roles as $prev_role) {
  11025. $role_name = getProp($prev_role, 'role');
  11026. if ($role_name) {
  11027. $previous_roles_voice[$role_name] = [
  11028. 'voice_name' => getProp($prev_role, 'voice_name'),
  11029. 'voice_type' => getProp($prev_role, 'voice_type'),
  11030. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  11031. ];
  11032. $voice_prompt = getProp($prev_role, 'voice_prompt');
  11033. if ($voice_prompt) {
  11034. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  11035. }
  11036. }
  11037. }
  11038. }
  11039. }
  11040. }
  11041. // 将继承的音色数据同步到当前集的主体列表
  11042. if (!empty($previous_roles_voice)) {
  11043. foreach ($merged_roles as &$role) {
  11044. $role_name = getProp($role, 'role');
  11045. if ($role_name && isset($previous_roles_voice[$role_name])) {
  11046. // 强制继承上一集的音色数据
  11047. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  11048. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  11049. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  11050. // 如果上一集有 voice_prompt 则继承,否则跳过
  11051. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  11052. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  11053. }
  11054. }
  11055. }
  11056. unset($role); // 解除引用
  11057. // 更新 role_arr 以便后续使用
  11058. $role_arr = [];
  11059. foreach ($merged_roles as $item) {
  11060. $role_arr[$item['role']] = $item;
  11061. }
  11062. }
  11063. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  11064. $emotion_list = array_flip($emotion_list);
  11065. foreach ($acts as $act) {
  11066. $act_segments = getProp($act, 'segments', []);
  11067. if (!is_array($act_segments)) {
  11068. continue;
  11069. }
  11070. if ((int)$ace_mode === 1) {
  11071. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  11072. $merged_parts = [];
  11073. foreach ($act_segments as $seg) {
  11074. $seg_num = getProp($seg, 'segment_number');
  11075. $seg_content = getProp($seg, 'segment_content');
  11076. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  11077. }
  11078. $act_content = implode("\n", $merged_parts);
  11079. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11080. $segments[] = [
  11081. 'anime_id' => $anime_id,
  11082. 'episode_id' => $episode_id,
  11083. 'episode_number' => $episode_number,
  11084. 'act_number' => getProp($act, 'act_number'),
  11085. 'act_title' => getProp($act, 'act_title'),
  11086. 'act_duration' => getProp($act, 'act_duration'),
  11087. 'act_content' => $act_content,
  11088. 'created_at' => $now,
  11089. 'updated_at' => $now
  11090. ];
  11091. } else {
  11092. foreach ($act_segments as $segment) {
  11093. $voice_actor = getProp($segment, 'voice_actor');
  11094. // 优先从上一集继承音色数据
  11095. $timbre_info = [];
  11096. if (isset($previous_roles_voice[$voice_actor])) {
  11097. // 从上一集继承音色数据
  11098. $timbre_info = $previous_roles_voice[$voice_actor];
  11099. } elseif (isset($role_arr[$voice_actor])) {
  11100. // 使用当前集的主体音色数据
  11101. $timbre_info = $role_arr[$voice_actor];
  11102. }
  11103. $voice_type = getProp($timbre_info, 'voice_type');
  11104. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  11105. if ($timbre_emotion) {
  11106. $timbre_emotion = explode(',', $timbre_emotion);
  11107. } else {
  11108. $timbre_emotion = [];
  11109. }
  11110. $emotion = getProp($segment, 'emotion', '中性');
  11111. if (!in_array($emotion, $timbre_emotion)) {
  11112. $emotion = '中性';
  11113. }
  11114. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11115. $segments[] = [
  11116. 'anime_id' => $anime_id,
  11117. 'episode_id' => $episode_id,
  11118. 'episode_number' => $episode_number,
  11119. 'act_number' => getProp($act, 'act_number'),
  11120. 'act_title' => getProp($act, 'act_title'),
  11121. 'act_duration' => getProp($act, 'act_duration'),
  11122. 'segment_id' => getProp($segment, 'segment_id'),
  11123. 'segment_number' => getProp($segment, 'segment_number'),
  11124. 'segment_content' => getProp($segment, 'segment_content'),
  11125. 'description' => getProp($segment, 'description'),
  11126. 'composition' => getProp($segment, 'composition'),
  11127. 'camera_movement' => getProp($segment, 'camera_movement'),
  11128. 'voice_actor' => $voice_actor,
  11129. 'dialogue' => getProp($segment, 'dialogue'),
  11130. 'frame_type' => getProp($segment, 'frame_type'),
  11131. 'scene' => getProp($segment, 'scene'),
  11132. 'characters' => getProp($segment, 'characters'),
  11133. 'tail_frame' => getProp($segment, 'tail_frame'),
  11134. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11135. 'voice_type' => $voice_type,
  11136. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11137. 'emotion' => $emotion,
  11138. 'emotion_type' => $emotion_type,
  11139. 'gender' => getProp($segment, 'gender', '0'),
  11140. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11141. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11142. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11143. 'pitch' => getProp($segment, 'pitch', 0),
  11144. 'created_at' => $now,
  11145. 'updated_at' => $now
  11146. ];
  11147. }
  11148. }
  11149. }
  11150. if ($segments) {
  11151. if ($del_flag) {
  11152. DB::table('mp_episode_segments')
  11153. ->where('anime_id', $anime_id)
  11154. ->where('episode_id', $episode_id)
  11155. ->delete();
  11156. }
  11157. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11158. if (!$boolen) {
  11159. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11160. Utils::throwError('20003:分镜内容保存失败');
  11161. }
  11162. }
  11163. dLog('deepseek')->info('segments', $segments);
  11164. // ace_mode=1: acts 返回值按合并格式调整
  11165. if ((int)$ace_mode === 1) {
  11166. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11167. $act_map = [];
  11168. foreach ($table_act_data as $item) {
  11169. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11170. }
  11171. $restructured_acts = [];
  11172. foreach ($acts as $act) {
  11173. $act_segments = getProp($act, 'segments', []);
  11174. if (!is_array($act_segments)) {
  11175. continue;
  11176. }
  11177. $merged_parts = [];
  11178. foreach ($act_segments as $seg) {
  11179. $seg_num = getProp($seg, 'segment_number');
  11180. $seg_content = getProp($seg, 'segment_content');
  11181. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11182. }
  11183. $act_content = implode("\n", $merged_parts);
  11184. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11185. $restructured_acts[] = [
  11186. 'anime_id' => $anime_id,
  11187. 'episode_id' => $episode_id,
  11188. 'episode_number' => $episode_number,
  11189. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11190. 'act_number' => getProp($act, 'act_number'),
  11191. 'act_title' => getProp($act, 'act_title'),
  11192. 'act_duration' => getProp($act, 'act_duration'),
  11193. 'act_content' => $act_content,
  11194. 'created_at' => $now,
  11195. 'updated_at' => $now,
  11196. ];
  11197. }
  11198. $acts = $restructured_acts;
  11199. }
  11200. $episode['episode_id'] = $episode_id;
  11201. $episode['roles'] = $merged_roles;
  11202. $episode['scenes'] = $merged_scenes;
  11203. $episode['props'] = $merged_props;
  11204. $episode['acts'] = $acts;
  11205. return [
  11206. 'episode' => $episode,
  11207. 'episode_id' => $episode_id,
  11208. 'merged_roles' => $merged_roles,
  11209. 'merged_scenes' => $merged_scenes,
  11210. 'merged_props' => $merged_props,
  11211. ];
  11212. }
  11213. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11214. {
  11215. $content = '';
  11216. foreach ($items as $item) {
  11217. $name = trim((string)getProp($item, $nameKey));
  11218. if ($name === '' || $name === '旁白') {
  11219. continue;
  11220. }
  11221. $description = trim((string)getProp($item, 'description'));
  11222. $content .= $name . ': ' . $description;
  11223. if ($nameKey == 'role') {
  11224. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11225. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11226. $voice_name = trim(getProp($item, 'voice_name'));
  11227. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11228. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  11229. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11230. }else {
  11231. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11232. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11233. }
  11234. $content .= "\n";
  11235. }
  11236. return trim($content);
  11237. }
  11238. private function getEpisodeChatContent($animeId, $sequence, $content) {
  11239. if ((int)$sequence <= 0) {
  11240. return [];
  11241. }
  11242. $origin_content = '';
  11243. if ($content) {
  11244. $origin_content = '本集剧情内容:'.$content;
  11245. }else {
  11246. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  11247. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  11248. }
  11249. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  11250. // 获取分集信息
  11251. $episode = DB::table('mp_anime_episodes')
  11252. ->where('anime_id', $animeId)
  11253. ->where('episode_number', $sequence)
  11254. ->where('is_default', 1)
  11255. ->first();
  11256. if (!$episode) {
  11257. return [];
  11258. }
  11259. $episode_id = getProp($episode, 'id');
  11260. $episode_number = getProp($episode, 'episode_number');
  11261. $title = getProp($episode, 'title');
  11262. $intro = getProp($episode, 'intro');
  11263. $art_style = getProp($episode, 'art_style');
  11264. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11265. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11266. // 组装纯文本内容
  11267. $content = '';
  11268. // 添加分集标题和梗概
  11269. $content .= "###第{$episode_number}集:{$title}\n\n";
  11270. $content .= "###故事梗概\n";
  11271. $content .= trim($intro) . "\n\n";
  11272. // 添加美术风格
  11273. $content .= "###美术风格\n";
  11274. $content .= trim($art_style) . "\n\n";
  11275. // 添加主体列表
  11276. $content .= "###主体列表\n";
  11277. $pangbai_voice_prompt = "";
  11278. foreach ($roles as $role) {
  11279. $name = getProp($role, 'role');
  11280. $description = getProp($role, 'description');
  11281. $pic_prompt = getProp($role, 'pic_prompt');
  11282. $voice_prompt = getProp($role, 'voice_prompt');
  11283. $voice_name = getProp($role, 'voice_name');
  11284. $content .= "{$name}: {$description}";
  11285. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11286. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11287. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11288. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  11289. $content .= "\n";
  11290. }
  11291. $content .= "\n";
  11292. // 添加场景列表
  11293. $content .= "###场景列表\n";
  11294. foreach ($scenes as $scene) {
  11295. $name = getProp($scene, 'scene');
  11296. $description = getProp($scene, 'description');
  11297. $pic_prompt = getProp($scene, 'pic_prompt');
  11298. $content .= "{$name}: {$description}";
  11299. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11300. $content .= "\n";
  11301. }
  11302. $content .= "\n";
  11303. // 获取分镜信息
  11304. $segments = DB::table('mp_episode_segments')
  11305. ->where('anime_id', $animeId)
  11306. ->where('episode_id', $episode_id)
  11307. ->orderBy('segment_number')
  11308. ->get();
  11309. if ($segments && count($segments) > 0) {
  11310. if ((int)$ace_mode === 1) {
  11311. $content .= "###分段剧本\n";
  11312. // 获取片段数量
  11313. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  11314. $content .= "片段数量:{$act_count}\n";
  11315. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  11316. $content .= "\n";
  11317. }else {
  11318. $content .= "###分镜剧本\n";
  11319. }
  11320. // 按幕分组
  11321. $currentAct = null;
  11322. foreach ($segments as $segment) {
  11323. $act_number = getProp($segment, 'act_number');
  11324. $act_title = getProp($segment, 'act_title');
  11325. $act_duration = getProp($segment, 'act_duration');
  11326. $segment_number = getProp($segment, 'segment_number');
  11327. $segment_content = getProp($segment, 'segment_content');
  11328. $scene_description = getProp($segment, 'scene_description');
  11329. $scene_name = getProp($segment, 'scene_name');
  11330. $composition = getProp($segment, 'composition');
  11331. $camera_movement = getProp($segment, 'camera_movement');
  11332. $voice_type = getProp($segment, 'voice_type');
  11333. $characters = getProp($segment, 'characters');
  11334. $dialogue = getProp($segment, 'dialogue');
  11335. $frame_type = getProp($segment, 'frame_type');
  11336. $tail_frame_description = getProp($segment, 'tail_frame_description');
  11337. // 判断是否是全能模式
  11338. if ((int)$ace_mode === 1) { // 全能模式
  11339. // 如果是新的分段,添加分段标题
  11340. if ($act_number !== $currentAct) {
  11341. $currentAct = $act_number;
  11342. $content .= "##{$act_title}\n";
  11343. $content .= "时长:{$act_duration}s\n";
  11344. }
  11345. }else {
  11346. // 如果是新的幕,添加幕标题
  11347. if ($act_number !== $currentAct) {
  11348. $currentAct = $act_number;
  11349. $content .= "##第{$act_number}幕:{$scene_name}\n";
  11350. }
  11351. }
  11352. // 添加分镜信息
  11353. $content .= "分镜{$segment_number}\n";
  11354. $content .= "分镜内容:\n{$segment_content}\n";
  11355. // $content .= "画面描述:{$scene_description}\n";
  11356. // $content .= "场景:{$scene_name}\n";
  11357. // $content .= "构图设计:{$composition}\n";
  11358. // $content .= "运镜调度:{$camera_movement}\n";
  11359. // if (!empty($voice_type)) {
  11360. // $content .= "配音角色:{$voice_type}\n";
  11361. // }
  11362. // if (!empty($characters)) {
  11363. // $content .= "出镜角色:{$characters}\n";
  11364. // }
  11365. // if (!empty($dialogue)) {
  11366. // $content .= "台词内容:\"{$dialogue}\"\n";
  11367. // }
  11368. // $content .= "画面类型:{$frame_type}\n";
  11369. // $content .= "尾帧描述:{$tail_frame_description}\n";
  11370. $content .= "\n";
  11371. }
  11372. }
  11373. $content = trim($content);
  11374. if($content) $content = "上集剧本内容:\n{$content}";
  11375. return [
  11376. [
  11377. 'role' => 'user',
  11378. 'content' => $origin_content
  11379. ],
  11380. [
  11381. 'role' => 'assistant',
  11382. 'content' => $content
  11383. ]
  11384. ];
  11385. }
  11386. private function getEpisodeChatMessages($animeId, $sequence): array
  11387. {
  11388. if ((int)$sequence <= 0) {
  11389. return [];
  11390. }
  11391. return DB::table('mp_anime_records')
  11392. ->where('anime_id', $animeId)
  11393. ->where('sequence', $sequence)
  11394. ->where('episode_id', '>', 0)
  11395. ->select('role', 'content')
  11396. ->orderBy('created_at')
  11397. ->orderBy('id')
  11398. ->get()
  11399. ->map(function ($value) {
  11400. return (array)$value;
  11401. })
  11402. ->toArray();
  11403. }
  11404. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  11405. {
  11406. $existingMap = [];
  11407. foreach ($existingItems as $item) {
  11408. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11409. if ($itemKey === '') {
  11410. continue;
  11411. }
  11412. $existingMap[$itemKey] = $item;
  11413. }
  11414. if (!$generatedItems) {
  11415. return array_values($existingItems);
  11416. }
  11417. $merged = [];
  11418. foreach ($generatedItems as $item) {
  11419. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11420. if ($itemKey === '') {
  11421. continue;
  11422. }
  11423. if (isset($existingMap[$itemKey])) {
  11424. if (trim((string)getProp($item, 'description')) === '') {
  11425. $merged[] = $existingMap[$itemKey];
  11426. continue;
  11427. }
  11428. // 检查内容是否发生变化
  11429. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  11430. if (!$isChanged) {
  11431. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  11432. $mergedItem = [
  11433. $nameKey => trim((string)getProp($item, $nameKey)),
  11434. 'description' => trim((string)getProp($item, 'description')),
  11435. ];
  11436. // 如果有 pic_prompt,添加到合并项中
  11437. $picPrompt = getProp($item, 'pic_prompt');
  11438. if (!empty($picPrompt)) {
  11439. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11440. }
  11441. // 继承现有项的 URL
  11442. $existingUrl = getProp($existingMap[$itemKey], 'url');
  11443. if (!empty($existingUrl)) {
  11444. $mergedItem['url'] = $existingUrl;
  11445. }
  11446. // 继承现有项的 task_id
  11447. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  11448. if (!empty($existingTaskId)) {
  11449. $mergedItem['task_id'] = $existingTaskId;
  11450. }
  11451. // 继承现有项的 task_status
  11452. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  11453. if (!empty($existingTaskStatus)) {
  11454. $mergedItem['task_status'] = $existingTaskStatus;
  11455. }
  11456. // 保留生成项的音色字段
  11457. $voiceName = getProp($item, 'voice_name');
  11458. if (!empty($voiceName)) {
  11459. $mergedItem['voice_name'] = $voiceName;
  11460. }
  11461. $voiceType = getProp($item, 'voice_type');
  11462. if (!empty($voiceType)) {
  11463. $mergedItem['voice_type'] = $voiceType;
  11464. }
  11465. $audioUrl = getProp($item, 'voice_audio_url');
  11466. if (!empty($audioUrl)) {
  11467. $mergedItem['voice_audio_url'] = $audioUrl;
  11468. }
  11469. $merged[] = $mergedItem;
  11470. } else {
  11471. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  11472. $mergedItem = [
  11473. $nameKey => trim((string)getProp($item, $nameKey)),
  11474. 'description' => trim((string)getProp($item, 'description')),
  11475. ];
  11476. // 如果有 pic_prompt,添加到合并项中
  11477. $picPrompt = getProp($item, 'pic_prompt');
  11478. if (!empty($picPrompt)) {
  11479. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11480. }
  11481. // 保留生成项的音色字段
  11482. $voiceName = getProp($item, 'voice_name');
  11483. if (!empty($voiceName)) {
  11484. $mergedItem['voice_name'] = $voiceName;
  11485. }
  11486. $voiceType = getProp($item, 'voice_type');
  11487. if (!empty($voiceType)) {
  11488. $mergedItem['voice_type'] = $voiceType;
  11489. }
  11490. $audioUrl = getProp($item, 'voice_audio_url');
  11491. if (!empty($audioUrl)) {
  11492. $mergedItem['voice_audio_url'] = $audioUrl;
  11493. }
  11494. // 不继承 URL、task_id 和 task_status(重置状态)
  11495. $merged[] = $mergedItem;
  11496. }
  11497. } else {
  11498. // 新增项,保留生成项的所有字段
  11499. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  11500. }
  11501. }
  11502. return $merged ?: array_values($existingItems);
  11503. }
  11504. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  11505. {
  11506. $resetItem = [
  11507. $nameKey => trim((string)getProp($item, $nameKey)),
  11508. 'description' => trim((string)getProp($item, 'description')),
  11509. ];
  11510. // 保留指定的字段
  11511. foreach ($preserveFields as $field) {
  11512. $value = getProp($item, $field);
  11513. if (!empty($value)) {
  11514. $resetItem[$field] = $value;
  11515. }
  11516. }
  11517. return $resetItem;
  11518. }
  11519. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  11520. {
  11521. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  11522. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  11523. if ($existingKey !== $generatedKey) {
  11524. return true;
  11525. }
  11526. // 比较 description 是否变化
  11527. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  11528. return true;
  11529. }
  11530. // 比较 pic_prompt 是否变化
  11531. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  11532. }
  11533. private function normalizeEpisodeResourceKey($value): string
  11534. {
  11535. $value = trim((string)$value);
  11536. if ($value === '') {
  11537. return '';
  11538. }
  11539. return strtolower((string)preg_replace('/\s+/u', '', $value));
  11540. }
  11541. // 生成全局角色图片
  11542. private function batchSetGlobalRoleImg($data, $is_force=false) {
  11543. $anime_id = getProp($data, 'anime_id');
  11544. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11545. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11546. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11547. $art_style = getProp($anime, 'art_style');
  11548. $update_flag = false;
  11549. foreach ($roles as &$role) {
  11550. $role_name = getProp($role, 'role');
  11551. if ($role_name == '旁白') continue;
  11552. // 优先使用 pic_prompt,如果没有则使用 description
  11553. $pic_prompt = getProp($role, 'pic_prompt');
  11554. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11555. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11556. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11557. // 参考图地址
  11558. $ref_img_url = getProp($role, 'url');
  11559. if (!$is_force && $ref_img_url) continue;
  11560. $update_flag = true;
  11561. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11562. try {
  11563. $params = [
  11564. 'prompt' => $description,
  11565. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  11566. 'ref_img_urls' => []
  11567. ];
  11568. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11569. $task_id = $task->id;
  11570. if (!$task_id) {
  11571. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  11572. }
  11573. $role['task_id'] = $task_id;
  11574. $role['task_status'] = 'processing';
  11575. } catch (\Exception $e) {
  11576. Utils::throwError("20003:" . $e->getMessage());
  11577. }
  11578. }
  11579. if (!$update_flag) return true;
  11580. // 保存角色信息
  11581. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11582. 'roles' => json_encode($roles, 256),
  11583. 'generate_status' => '执行中',
  11584. 'generate_at' => date('Y-m-d H:i:s'),
  11585. 'updated_at' => date('Y-m-d H:i:s')
  11586. ]);
  11587. if (!$boolen) {
  11588. Utils::throwError('20003:保存角色信息失败');
  11589. }
  11590. return $boolen;
  11591. }
  11592. // 生成全局场景图片
  11593. private function batchSetGlobalSceneImg($data, $is_force=false) {
  11594. $anime_id = getProp($data, 'anime_id');
  11595. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11596. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11597. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11598. $art_style = getProp($anime, 'art_style');
  11599. $update_flag = false;
  11600. foreach ($scenes as &$scene) {
  11601. $scene_name = getProp($scene, 'scene');
  11602. // 优先使用 pic_prompt,如果没有则使用 description
  11603. $pic_prompt = getProp($scene, 'pic_prompt');
  11604. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11605. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  11606. // 参考图地址
  11607. $ref_img_url = getProp($scene, 'url');
  11608. if (!$is_force && $ref_img_url) continue;
  11609. $update_flag = true;
  11610. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11611. try {
  11612. $params = [
  11613. 'prompt' => $description,
  11614. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  11615. 'ref_img_urls' => []
  11616. ];
  11617. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11618. $task_id = $task->id;
  11619. if (!$task_id) {
  11620. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  11621. }
  11622. $scene['task_id'] = $task_id;
  11623. $scene['task_status'] = 'processing';
  11624. } catch (\Exception $e) {
  11625. Utils::throwError("20003:" . $e->getMessage());
  11626. }
  11627. }
  11628. if (!$update_flag) return true;
  11629. // 保存角色信息
  11630. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11631. 'scenes' => json_encode($scenes, 256),
  11632. 'generate_status' => '执行中',
  11633. 'generate_at' => date('Y-m-d H:i:s'),
  11634. 'updated_at' => date('Y-m-d H:i:s')
  11635. ]);
  11636. if (!$boolen) {
  11637. Utils::throwError('20003:保存角色信息失败');
  11638. }
  11639. return $boolen;
  11640. }
  11641. // 生成分镜主体、场景和道具图片
  11642. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  11643. $character_prefix = '';
  11644. $scene_prefix = '';
  11645. $prop_prefix = '';
  11646. if ($art_style_type) {
  11647. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  11648. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  11649. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  11650. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  11651. }
  11652. $update_flag = false;
  11653. // 获取上一集的roles、scenes和props数据
  11654. $prev_roles = [];
  11655. $prev_scenes = [];
  11656. $prev_props = [];
  11657. if ($episode_number > 1) {
  11658. $prev_episode = DB::table('mp_anime_episodes')
  11659. ->where('anime_id', $anime_id)
  11660. ->where('episode_number', $episode_number - 1)
  11661. ->where('is_default', 1)
  11662. ->first();
  11663. if ($prev_episode) {
  11664. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  11665. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  11666. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  11667. dLog('deepseek')->info("获取上一集数据成功", [
  11668. 'anime_id' => $anime_id,
  11669. 'prev_episode_number' => $episode_number - 1,
  11670. 'prev_roles_count' => count($prev_roles),
  11671. 'prev_scenes_count' => count($prev_scenes),
  11672. 'prev_props_count' => count($prev_props)
  11673. ]);
  11674. }
  11675. }
  11676. // 处理角色图片生成
  11677. foreach ($roles as &$role) {
  11678. $role_name = getProp($role, 'role');
  11679. if ($role_name == '旁白') continue;
  11680. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  11681. if (isset($ref_products[$role_name])) {
  11682. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  11683. if ($role['url']) continue;
  11684. }
  11685. $role_description = getProp($role, 'description');
  11686. $role_pic_prompt = getProp($role, 'pic_prompt');
  11687. $role_url = getProp($role, 'url');
  11688. // 检查是否可以从上一集继承
  11689. $inherited = false;
  11690. if (!$is_force && !empty($prev_roles)) {
  11691. foreach ($prev_roles as $prev_role) {
  11692. $prev_role_name = getProp($prev_role, 'role');
  11693. $prev_description = getProp($prev_role, 'description');
  11694. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  11695. $prev_url = getProp($prev_role, 'url');
  11696. $prev_task_id = getProp($prev_role, 'task_id');
  11697. $prev_task_status = getProp($prev_role, 'task_status');
  11698. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  11699. if ($role_name == $prev_role_name
  11700. && $role_description == $prev_description
  11701. && $role_pic_prompt == $prev_pic_prompt
  11702. && !empty($prev_url)) {
  11703. $role['task_id'] = $prev_task_id;
  11704. $role['task_status'] = $prev_task_status;
  11705. $role['url'] = $prev_url;
  11706. $inherited = true;
  11707. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  11708. 'anime_id' => $anime_id,
  11709. 'episode_number' => $episode_number,
  11710. 'task_id' => $prev_task_id,
  11711. 'url' => $prev_url
  11712. ]);
  11713. break;
  11714. }
  11715. }
  11716. }
  11717. // 如果已继承或已有url,跳过生成
  11718. if ($inherited || (!$is_force && $role_url)) {
  11719. continue;
  11720. }
  11721. // 优先使用 pic_prompt,如果没有则使用 description
  11722. $pic_prompt = getProp($role, 'pic_prompt');
  11723. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11724. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11725. $update_flag = true;
  11726. // 调用AIImageGenerationService的生成图片任务接口
  11727. try {
  11728. $params = [
  11729. 'prompt' => $description,
  11730. 'ref_img_urls' => []
  11731. ];
  11732. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11733. $task_id = $task->id;
  11734. if (!$task_id) {
  11735. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  11736. continue; // 不中断,继续处理其他角色
  11737. }
  11738. $role['task_id'] = $task_id;
  11739. $role['task_status'] = 'processing';
  11740. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  11741. 'anime_id' => $anime_id,
  11742. 'episode_number' => $episode_number,
  11743. 'task_id' => $task_id
  11744. ]);
  11745. } catch (\Exception $e) {
  11746. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  11747. // 不抛出异常,继续处理其他角色
  11748. }
  11749. }
  11750. // 处理场景图片生成
  11751. foreach ($scenes as &$scene) {
  11752. $scene_name = getProp($scene, 'scene');
  11753. $scene_description = getProp($scene, 'description');
  11754. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  11755. $scene_url = getProp($scene, 'url');
  11756. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  11757. if (isset($ref_products[$scene_name])) {
  11758. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  11759. if ($scene['url']) continue;
  11760. }
  11761. // 检查是否可以从上一集继承
  11762. $inherited = false;
  11763. if (!$is_force && !empty($prev_scenes)) {
  11764. foreach ($prev_scenes as $prev_scene) {
  11765. $prev_scene_name = getProp($prev_scene, 'scene');
  11766. $prev_description = getProp($prev_scene, 'description');
  11767. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  11768. $prev_url = getProp($prev_scene, 'url');
  11769. $prev_task_id = getProp($prev_scene, 'task_id');
  11770. $prev_task_status = getProp($prev_scene, 'task_status');
  11771. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  11772. if ($scene_name == $prev_scene_name
  11773. && $scene_description == $prev_description
  11774. && $scene_pic_prompt == $prev_pic_prompt
  11775. && !empty($prev_url)) {
  11776. $scene['task_id'] = $prev_task_id;
  11777. $scene['task_status'] = $prev_task_status;
  11778. $scene['url'] = $prev_url;
  11779. $inherited = true;
  11780. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  11781. 'anime_id' => $anime_id,
  11782. 'episode_number' => $episode_number,
  11783. 'task_id' => $prev_task_id,
  11784. 'url' => $prev_url
  11785. ]);
  11786. break;
  11787. }
  11788. }
  11789. }
  11790. // 如果已继承或已有url,跳过生成
  11791. if ($inherited || (!$is_force && $scene_url)) {
  11792. continue;
  11793. }
  11794. // 优先使用 pic_prompt,如果没有则使用 description
  11795. $pic_prompt = getProp($scene, 'pic_prompt');
  11796. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11797. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11798. $update_flag = true;
  11799. // 调用AIImageGenerationService的生成图片任务接口
  11800. try {
  11801. $params = [
  11802. 'prompt' => $description,
  11803. 'ref_img_urls' => []
  11804. ];
  11805. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11806. $task_id = $task->id;
  11807. if (!$task_id) {
  11808. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  11809. continue; // 不中断,继续处理其他场景
  11810. }
  11811. $scene['task_id'] = $task_id;
  11812. $scene['task_status'] = 'processing';
  11813. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  11814. 'anime_id' => $anime_id,
  11815. 'episode_number' => $episode_number,
  11816. 'task_id' => $task_id
  11817. ]);
  11818. } catch (\Exception $e) {
  11819. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  11820. // 不抛出异常,继续处理其他场景
  11821. }
  11822. }
  11823. // 处理道具图片生成(逻辑与场景一致)
  11824. foreach ($props as &$prop) {
  11825. $prop_name = getProp($prop, 'prop');
  11826. $prop_description = getProp($prop, 'description');
  11827. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  11828. $prop_url = getProp($prop, 'url');
  11829. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  11830. if (isset($ref_products[$prop_name])) {
  11831. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  11832. if ($prop['url']) continue;
  11833. }
  11834. // 检查是否可以从上一集继承
  11835. $inherited = false;
  11836. if (!$is_force && !empty($prev_props)) {
  11837. foreach ($prev_props as $prev_prop) {
  11838. $prev_prop_name = getProp($prev_prop, 'prop');
  11839. $prev_description = getProp($prev_prop, 'description');
  11840. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  11841. $prev_url = getProp($prev_prop, 'url');
  11842. $prev_task_id = getProp($prev_prop, 'task_id');
  11843. $prev_task_status = getProp($prev_prop, 'task_status');
  11844. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  11845. if ($prop_name == $prev_prop_name
  11846. && $prop_description == $prev_description
  11847. && $prop_pic_prompt == $prev_pic_prompt
  11848. && !empty($prev_url)) {
  11849. $prop['task_id'] = $prev_task_id;
  11850. $prop['task_status'] = $prev_task_status;
  11851. $prop['url'] = $prev_url;
  11852. $inherited = true;
  11853. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  11854. 'anime_id' => $anime_id,
  11855. 'episode_number' => $episode_number,
  11856. 'task_id' => $prev_task_id,
  11857. 'url' => $prev_url
  11858. ]);
  11859. break;
  11860. }
  11861. }
  11862. }
  11863. // 如果已继承或已有url,跳过生成
  11864. if ($inherited || (!$is_force && $prop_url)) {
  11865. continue;
  11866. }
  11867. // 优先使用 pic_prompt,如果没有则使用 description
  11868. $pic_prompt = getProp($prop, 'pic_prompt');
  11869. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  11870. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11871. $update_flag = true;
  11872. // 调用AIImageGenerationService的生成图片任务接口
  11873. try {
  11874. $params = [
  11875. 'prompt' => $description,
  11876. 'ref_img_urls' => []
  11877. ];
  11878. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11879. $task_id = $task->id;
  11880. if (!$task_id) {
  11881. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11882. continue; // 不中断,继续处理其他道具
  11883. }
  11884. $prop['task_id'] = $task_id;
  11885. $prop['task_status'] = 'processing';
  11886. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11887. 'anime_id' => $anime_id,
  11888. 'episode_number' => $episode_number,
  11889. 'task_id' => $task_id
  11890. ]);
  11891. } catch (\Exception $e) {
  11892. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11893. // 不抛出异常,继续处理其他道具
  11894. }
  11895. }
  11896. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11897. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11898. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11899. // // 保存剧集的角色和场景信息
  11900. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11901. // 'roles' => json_encode($roles, 256),
  11902. // 'scenes' => json_encode($scenes, 256),
  11903. // 'generate_status' => '执行中',
  11904. // 'generate_at' => date('Y-m-d H:i:s'),
  11905. // 'updated_at' => date('Y-m-d H:i:s')
  11906. // ]);
  11907. // if (!$boolen) {
  11908. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11909. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11910. // }
  11911. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11912. // 'episode_id' => $episode_id,
  11913. 'roles_count' => count($roles),
  11914. 'scenes_count' => count($scenes),
  11915. 'props_count' => count($props)
  11916. ]);
  11917. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11918. }
  11919. /**
  11920. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11921. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11922. *
  11923. * @param int $anime_id 动漫对话ID
  11924. * @param array $episode_roles 剧集角色数据
  11925. * @param array $episode_scenes 剧集场景数据
  11926. * @param array $episode_props 剧集道具数据
  11927. * @return bool
  11928. */
  11929. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11930. // 获取全局数据
  11931. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11932. if (!$anime) {
  11933. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11934. return false;
  11935. }
  11936. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11937. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11938. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11939. $roles_added = false;
  11940. $roles_updated = false;
  11941. $scenes_added = false;
  11942. $props_added = false;
  11943. // 处理角色同步
  11944. foreach ($episode_roles as $episode_role) {
  11945. $episode_role_name = getProp($episode_role, 'role');
  11946. $episode_description = getProp($episode_role, 'description');
  11947. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11948. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11949. // 跳过旁白
  11950. if ($episode_role_name == '旁白') {
  11951. continue;
  11952. }
  11953. // 检查全局中是否已存在相同的角色
  11954. $exists = false;
  11955. $global_role_index = -1;
  11956. foreach ($global_roles as $index => $global_role) {
  11957. $global_role_name = getProp($global_role, 'role');
  11958. $global_description = getProp($global_role, 'description');
  11959. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11960. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11961. if ($episode_role_name == $global_role_name
  11962. && $episode_description == $global_description
  11963. && $episode_pic_prompt == $global_pic_prompt) {
  11964. $exists = true;
  11965. $global_role_index = $index;
  11966. break;
  11967. }
  11968. }
  11969. // 如果不存在,则添加到全局
  11970. if (!$exists) {
  11971. $global_roles[] = $episode_role;
  11972. $roles_added = true;
  11973. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11974. 'anime_id' => $anime_id,
  11975. 'role' => $episode_role_name
  11976. ]);
  11977. } else {
  11978. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11979. if (!empty($episode_voice_prompt)) {
  11980. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11981. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11982. if ($global_voice_prompt !== $episode_voice_prompt) {
  11983. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11984. $roles_updated = true;
  11985. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11986. 'anime_id' => $anime_id,
  11987. 'role' => $episode_role_name,
  11988. 'voice_prompt' => $episode_voice_prompt
  11989. ]);
  11990. }
  11991. }
  11992. }
  11993. }
  11994. // 处理场景同步
  11995. foreach ($episode_scenes as $episode_scene) {
  11996. $episode_scene_name = getProp($episode_scene, 'scene');
  11997. $episode_description = getProp($episode_scene, 'description');
  11998. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11999. // 检查全局中是否已存在相同的场景
  12000. $exists = false;
  12001. foreach ($global_scenes as $global_scene) {
  12002. $global_scene_name = getProp($global_scene, 'scene');
  12003. $global_description = getProp($global_scene, 'description');
  12004. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12005. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  12006. if ($episode_scene_name == $global_scene_name
  12007. && $episode_description == $global_description
  12008. && $episode_pic_prompt == $global_pic_prompt) {
  12009. $exists = true;
  12010. break;
  12011. }
  12012. }
  12013. // 如果不存在,则添加到全局
  12014. if (!$exists) {
  12015. $global_scenes[] = $episode_scene;
  12016. $scenes_added = true;
  12017. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  12018. 'anime_id' => $anime_id,
  12019. 'scene' => $episode_scene_name
  12020. ]);
  12021. }
  12022. }
  12023. // 处理道具同步(逻辑与场景一致)
  12024. foreach ($episode_props as $episode_prop) {
  12025. $episode_prop_name = getProp($episode_prop, 'prop');
  12026. $episode_description = getProp($episode_prop, 'description');
  12027. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  12028. // 检查全局中是否已存在相同的道具
  12029. $exists = false;
  12030. foreach ($global_props as $global_prop) {
  12031. $global_prop_name = getProp($global_prop, 'prop');
  12032. $global_description = getProp($global_prop, 'description');
  12033. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  12034. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  12035. if ($episode_prop_name == $global_prop_name
  12036. && $episode_description == $global_description
  12037. && $episode_pic_prompt == $global_pic_prompt) {
  12038. $exists = true;
  12039. break;
  12040. }
  12041. }
  12042. // 如果不存在,则添加到全局
  12043. if (!$exists) {
  12044. $global_props[] = $episode_prop;
  12045. $props_added = true;
  12046. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  12047. 'anime_id' => $anime_id,
  12048. 'prop' => $episode_prop_name
  12049. ]);
  12050. }
  12051. }
  12052. // 如果有新增或更新,则更新全局数据
  12053. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  12054. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12055. if ($roles_added || $roles_updated) {
  12056. $update_data['roles'] = json_encode($global_roles, 256);
  12057. }
  12058. if ($scenes_added) {
  12059. $update_data['scenes'] = json_encode($global_scenes, 256);
  12060. }
  12061. if ($props_added) {
  12062. $update_data['props'] = json_encode($global_props, 256);
  12063. }
  12064. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12065. dLog('deepseek')->info('剧集数据同步到全局完成', [
  12066. 'anime_id' => $anime_id,
  12067. 'roles_added' => $roles_added,
  12068. 'roles_updated' => $roles_updated,
  12069. 'scenes_added' => $scenes_added,
  12070. 'props_added' => $props_added,
  12071. 'global_roles_count' => count($global_roles),
  12072. 'global_scenes_count' => count($global_scenes),
  12073. 'global_props_count' => count($global_props)
  12074. ]);
  12075. }
  12076. return true;
  12077. }
  12078. /**
  12079. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  12080. *
  12081. * @param int $anime_id 动漫对话ID
  12082. * @param int $episode_id 分集ID
  12083. * @return bool
  12084. */
  12085. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  12086. // 获取全局角色和场景数据
  12087. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12088. if (!$anime) {
  12089. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12090. return false;
  12091. }
  12092. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12093. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12094. // 获取指定的分集
  12095. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  12096. if (!$episode) {
  12097. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12098. return false;
  12099. }
  12100. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12101. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12102. $roles_updated = false;
  12103. $scenes_updated = false;
  12104. // 继承角色的task_id、task_status和url
  12105. foreach ($episode_roles as &$episode_role) {
  12106. $episode_role_name = getProp($episode_role, 'role');
  12107. $episode_description = getProp($episode_role, 'description');
  12108. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12109. $episode_url = getProp($episode_role, 'url');
  12110. // 跳过旁白角色
  12111. if ($episode_role_name == '旁白') {
  12112. continue;
  12113. }
  12114. // 如果剧集中已有URL,跳过
  12115. if (!empty($episode_url)) {
  12116. continue;
  12117. }
  12118. // 遍历全局角色数据,查找匹配的角色
  12119. foreach ($global_roles as $global_role) {
  12120. $global_role_name = getProp($global_role, 'role');
  12121. $global_description = getProp($global_role, 'description');
  12122. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12123. $global_url = getProp($global_role, 'url');
  12124. $global_task_id = getProp($global_role, 'task_id');
  12125. $global_task_status = getProp($global_role, 'task_status');
  12126. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12127. if ($episode_role_name == $global_role_name
  12128. && $episode_description == $global_description
  12129. && $episode_pic_prompt == $global_pic_prompt) {
  12130. // 继承 task_id、task_status 和 url
  12131. if (!empty($global_task_id)) {
  12132. $episode_role['task_id'] = $global_task_id;
  12133. $episode_role['task_status'] = $global_task_status;
  12134. $roles_updated = true;
  12135. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12136. 'episode_id' => $episode_id,
  12137. 'role' => $episode_role_name,
  12138. 'task_id' => $global_task_id,
  12139. 'task_status' => $global_task_status
  12140. ]);
  12141. }
  12142. if (!empty($global_url)) {
  12143. $episode_role['url'] = $global_url;
  12144. $roles_updated = true;
  12145. dLog('deepseek')->info('剧集角色继承全局url', [
  12146. 'episode_id' => $episode_id,
  12147. 'role' => $episode_role_name,
  12148. 'url' => $global_url
  12149. ]);
  12150. }
  12151. break;
  12152. }
  12153. }
  12154. }
  12155. // 继承场景的task_id、task_status和url
  12156. foreach ($episode_scenes as &$episode_scene) {
  12157. $episode_scene_name = getProp($episode_scene, 'scene');
  12158. $episode_description = getProp($episode_scene, 'description');
  12159. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12160. $episode_url = getProp($episode_scene, 'url');
  12161. // 如果剧集中已有URL,跳过
  12162. if (!empty($episode_url)) {
  12163. continue;
  12164. }
  12165. // 遍历全局场景数据,查找匹配的场景
  12166. foreach ($global_scenes as $global_scene) {
  12167. $global_scene_name = getProp($global_scene, 'scene');
  12168. $global_description = getProp($global_scene, 'description');
  12169. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12170. $global_url = getProp($global_scene, 'url');
  12171. $global_task_id = getProp($global_scene, 'task_id');
  12172. $global_task_status = getProp($global_scene, 'task_status');
  12173. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12174. if ($episode_scene_name == $global_scene_name
  12175. && $episode_description == $global_description
  12176. && $episode_pic_prompt == $global_pic_prompt) {
  12177. // 继承 task_id、task_status 和 url
  12178. if (!empty($global_task_id)) {
  12179. $episode_scene['task_id'] = $global_task_id;
  12180. $episode_scene['task_status'] = $global_task_status;
  12181. $scenes_updated = true;
  12182. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12183. 'episode_id' => $episode_id,
  12184. 'scene' => $episode_scene_name,
  12185. 'task_id' => $global_task_id,
  12186. 'task_status' => $global_task_status
  12187. ]);
  12188. }
  12189. if (!empty($global_url)) {
  12190. $episode_scene['url'] = $global_url;
  12191. $scenes_updated = true;
  12192. dLog('deepseek')->info('剧集场景继承全局url', [
  12193. 'episode_id' => $episode_id,
  12194. 'scene' => $episode_scene_name,
  12195. 'url' => $global_url
  12196. ]);
  12197. }
  12198. break;
  12199. }
  12200. }
  12201. }
  12202. // 如果有更新,则保存到数据库
  12203. if ($roles_updated || $scenes_updated) {
  12204. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12205. if ($roles_updated) {
  12206. $update_data['roles'] = json_encode($episode_roles, 256);
  12207. }
  12208. if ($scenes_updated) {
  12209. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12210. }
  12211. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12212. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12213. 'episode_id' => $episode_id,
  12214. 'roles_updated' => $roles_updated,
  12215. 'scenes_updated' => $scenes_updated
  12216. ]);
  12217. }
  12218. return true;
  12219. }
  12220. public function chatChangeImg($data) {
  12221. $segment = getProp($data, 'segment');
  12222. $segment_content = getProp($segment, 'segment_content');
  12223. $prompt = getProp($data, 'prompt');
  12224. $ref_img = getProp($data, 'ref_img');
  12225. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12226. // 处理文本模型
  12227. $model = getProp($data, 'model');
  12228. if (!$model) {
  12229. // 用户没有输入,从anime表获取
  12230. $segment_id = getProp($segment, 'segment_id');
  12231. if ($segment_id) {
  12232. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  12233. if ($episode_id) {
  12234. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  12235. if ($anime_id) {
  12236. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  12237. }
  12238. }
  12239. }
  12240. if (!$model) {
  12241. // anime表也没有,使用默认值
  12242. $model = 'doubao-seed-2-0-mini-260215';
  12243. }
  12244. }
  12245. // 验证模型是否在可用模型表中
  12246. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12247. $model = 'doubao-seed-2-0-mini-260215';
  12248. }
  12249. $messages[] =
  12250. [
  12251. 'role' => 'user',
  12252. 'content' => $question
  12253. ];
  12254. $post_data = [
  12255. 'model' => $model,
  12256. 'messages' => $messages,
  12257. // 'max_tokens' => 8192,
  12258. 'temperature' => 0.7,
  12259. 'frequency_penalty' => 0,
  12260. 'presence_penalty' => 0,
  12261. 'response_format' => ['type' => 'text'],
  12262. 'stream' => false // 是否启用流式输出
  12263. ];
  12264. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12265. // DeepSeek 官方模型使用 DeepSeek API
  12266. $chatResult = $this->chatOnly($post_data);
  12267. } else if (in_array($model, $this->gpt_text_models)) {
  12268. // GPT-5.4 模型使用 TokenRouter API
  12269. $chatResult = $this->gpt54ChatOnly($post_data);
  12270. } else {
  12271. // 其他模型使用火山引擎API
  12272. $chatResult = $this->volcEngineChatCompletion($post_data);
  12273. }
  12274. if (is_array($chatResult)) {
  12275. extract($chatResult);
  12276. }else {
  12277. Utils::throwError('20003: 接口调用失败!');
  12278. }
  12279. // 仅记录 token 使用明细(不扣积分)
  12280. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  12281. 'model' => $model,
  12282. 'source' => 'chatChangeImg',
  12283. ], $model);
  12284. return [
  12285. 'type' => 'done',
  12286. // 'episode' => $episode,
  12287. 'answer' => $fullContent,
  12288. 'reasoning' => $fullReasoningContent,
  12289. 'usage' => $usage
  12290. ];
  12291. }
  12292. /**
  12293. * 仅调用 deepseek 对话接口(非流式)
  12294. *
  12295. * @param array $post_data
  12296. * @param int $timeout
  12297. * @return array
  12298. */
  12299. private function chatOnly($post_data, $timeout = 1800) {
  12300. $post_data['max_tokens'] = 300000;
  12301. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  12302. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  12303. $response = $result->getBody()->getContents();
  12304. $response_arr = json_decode($response, true);
  12305. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  12306. $fullContent = '';
  12307. $fullReasoningContent = [];
  12308. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12309. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12310. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12311. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  12312. }
  12313. return [
  12314. 'fullContent' => $fullContent,
  12315. 'fullReasoningContent' => $fullReasoningContent,
  12316. 'usage' => $usage
  12317. ];
  12318. }
  12319. /**
  12320. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  12321. *
  12322. * @param string $errorMessage
  12323. * @return string|null
  12324. */
  12325. public function analyzeErrorMessage($errorMessage)
  12326. {
  12327. try {
  12328. $post_data = [
  12329. 'model' => 'deepseek-v4-flash',
  12330. 'messages' => [
  12331. [
  12332. 'role' => 'system',
  12333. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  12334. ],
  12335. [
  12336. 'role' => 'user',
  12337. 'content' => (string)$errorMessage,
  12338. ],
  12339. ],
  12340. 'temperature' => 0.3,
  12341. 'frequency_penalty' => 0,
  12342. 'presence_penalty' => 0,
  12343. 'response_format' => ['type' => 'text'],
  12344. 'stream' => false,
  12345. ];
  12346. $result = $this->chatOnly($post_data, 8);
  12347. $content = trim((string)($result['fullContent'] ?? ''));
  12348. if ($content === '') {
  12349. return null;
  12350. }
  12351. return mb_substr($content, 0, 50);
  12352. } catch (\Exception $e) {
  12353. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  12354. 'error_message' => $errorMessage
  12355. ]);
  12356. return null;
  12357. }
  12358. }
  12359. // 仅调用 GPT-5.4 对话接口(非流式)
  12360. private function gpt54ChatOnly($post_data) {
  12361. $apiKey = env('GPT_54_API_KEY');
  12362. if (empty($apiKey)) {
  12363. Utils::throwError('20003:GPT-5.4 API Key未配置');
  12364. }
  12365. // 先探活,服务不可用时自动重试
  12366. $this->ensureGptServiceAvailable();
  12367. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12368. $headers = [
  12369. 'Authorization' => 'Bearer ' . $apiKey,
  12370. 'Content-Type' => 'application/json'
  12371. ];
  12372. // 移除 thinking 参数,GPT-5.4 不支持
  12373. if (isset($post_data['thinking'])) {
  12374. unset($post_data['thinking']);
  12375. }
  12376. if (isset($post_data['reasoning_effort'])) {
  12377. unset($post_data['reasoning_effort']);
  12378. }
  12379. $post_data['max_completion_tokens'] = 100000;
  12380. // 确保 stream 为 false
  12381. $post_data['stream'] = false;
  12382. $maxRetries = $this->gptRetryTimes();
  12383. $interval = $this->gptRetryInterval();
  12384. $attempt = 0;
  12385. while (true) {
  12386. try {
  12387. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  12388. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  12389. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  12390. 'json' => $post_data,
  12391. 'headers' => $headers
  12392. ]);
  12393. $response = $result->getBody()->getContents();
  12394. $response_arr = json_decode($response, true);
  12395. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  12396. $fullContent = '';
  12397. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12398. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12399. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12400. }
  12401. return [
  12402. 'fullContent' => $fullContent,
  12403. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  12404. 'usage' => $usage
  12405. ];
  12406. } catch (\Exception $e) {
  12407. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  12408. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  12409. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  12410. throw $e;
  12411. }
  12412. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  12413. 'retry' => $attempt + 1,
  12414. 'max_retries' => $maxRetries,
  12415. 'error' => $e->getMessage()
  12416. ]);
  12417. sleep($interval);
  12418. $attempt++;
  12419. }
  12420. }
  12421. }
  12422. private function splitContent($content) {
  12423. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  12424. $chapters = [];
  12425. // 匹配章节标题格式:
  12426. // 1. 标题可能独占一行,也可能在正文末尾或中间
  12427. // 2. 格式支持:
  12428. // - **第一集**
  12429. // - 第一集:
  12430. // - ###第1章 重生
  12431. // - ##第2章 相救
  12432. // - 第三章 共处一室
  12433. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  12434. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  12435. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  12436. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  12437. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  12438. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  12439. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  12440. // 先在每个标题前插入换行符(如果前面不是换行的话)
  12441. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  12442. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  12443. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  12444. // 用正则找出所有章节标题的位置
  12445. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  12446. $titleCount = count($matches[0]);
  12447. for ($i = 0; $i < $titleCount; $i++) {
  12448. // 获取当前章节标题
  12449. $titleLine = trim($matches[0][$i][0]);
  12450. // 去除标题开头的特殊符号
  12451. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/u', '', $titleLine);
  12452. // 去除标题结尾的冒号和特殊符号
  12453. $cleanTitle = preg_replace('/[#*·::\s]+$/u', '', $cleanTitle);
  12454. $cleanTitle = trim($cleanTitle);
  12455. // 获取当前标题的结束位置
  12456. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  12457. // 获取下一个章节标题的开始位置(如果存在)
  12458. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  12459. // 提取章节内容(从标题结束到下一个标题开始)
  12460. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  12461. // 清理内容:去除前后空白和分隔线
  12462. $chapterContent = trim($chapterContent);
  12463. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  12464. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  12465. if (!empty($cleanTitle) && !empty($chapterContent)) {
  12466. $chapters[] = [
  12467. 'title' => $cleanTitle,
  12468. 'content' => $chapterContent
  12469. ];
  12470. }
  12471. }
  12472. } else {
  12473. // 如果没有匹配到章节,返回整个内容
  12474. $chapters[] = [
  12475. 'title' => '',
  12476. 'content' => $content
  12477. ];
  12478. }
  12479. return $chapters;
  12480. }
  12481. public function getContentByBid($bid) {
  12482. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  12483. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  12484. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  12485. $content = '';
  12486. foreach ($chapters as $chapter) {
  12487. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  12488. }
  12489. return $content;
  12490. }
  12491. public function getContentByScriptId($script_id) {
  12492. $content = '';
  12493. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  12494. if ($contents) {
  12495. $content = implode(PHP_EOL, $contents);
  12496. }else {
  12497. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  12498. }
  12499. return $content;
  12500. }
  12501. /**
  12502. * 根据文件类型提取文本内容
  12503. *
  12504. * @param mixed $file 文件对象或文件路径
  12505. * @return string
  12506. */
  12507. public function extractFileContent($file) {
  12508. // 获取文件路径和扩展名
  12509. if (is_string($file)) {
  12510. $filePath = $file;
  12511. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  12512. } else {
  12513. // Laravel UploadedFile 对象
  12514. $filePath = $file->getRealPath();
  12515. $extension = strtolower($file->getClientOriginalExtension());
  12516. }
  12517. $content = '';
  12518. switch ($extension) {
  12519. case 'txt':
  12520. $content = $this->extractTxtContent($filePath);
  12521. break;
  12522. case 'pdf':
  12523. $content = $this->extractPdfContent($filePath);
  12524. break;
  12525. case 'doc':
  12526. case 'docx':
  12527. $content = $this->extractWordContent($filePath);
  12528. break;
  12529. // case 'jpg':
  12530. // case 'jpeg':
  12531. // case 'png':
  12532. // case 'gif':
  12533. // case 'bmp':
  12534. // case 'webp':
  12535. // $content = $this->extractImageContent($filePath);
  12536. // break;
  12537. default:
  12538. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  12539. }
  12540. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  12541. if (!mb_check_encoding($content, 'UTF-8')) {
  12542. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  12543. $content = $cleaned === false ? $content : $cleaned;
  12544. }
  12545. return $content;
  12546. }
  12547. /**
  12548. * 提取 TXT 文件内容
  12549. */
  12550. private function extractTxtContent($filePath) {
  12551. if (!file_exists($filePath)) {
  12552. Utils::throwError('20003:文件不存在');
  12553. }
  12554. $content = file_get_contents($filePath);
  12555. // 尝试检测并转换编码
  12556. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  12557. if ($encoding && $encoding !== 'UTF-8') {
  12558. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  12559. }
  12560. return trim($content);
  12561. }
  12562. /**
  12563. * 提取 PDF 文件内容
  12564. */
  12565. private function extractPdfContent($filePath) {
  12566. if (!file_exists($filePath)) {
  12567. Utils::throwError('20003:文件不存在');
  12568. }
  12569. try {
  12570. $parser = new PdfParser();
  12571. $pdf = $parser->parseFile($filePath);
  12572. $content = $pdf->getText();
  12573. return trim($content);
  12574. } catch (\Exception $e) {
  12575. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  12576. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  12577. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  12578. }
  12579. }
  12580. /**
  12581. * 提取 Word 文件内容(支持 doc 和 docx)
  12582. */
  12583. private function extractWordContent($filePath) {
  12584. if (!file_exists($filePath)) {
  12585. Utils::throwError('20003:文件不存在');
  12586. }
  12587. try {
  12588. $phpWord = WordIOFactory::load($filePath);
  12589. $content = '';
  12590. foreach ($phpWord->getSections() as $section) {
  12591. foreach ($section->getElements() as $element) {
  12592. $content .= $this->extractWordElementText($element);
  12593. }
  12594. }
  12595. return trim($content);
  12596. } catch (\Exception $e) {
  12597. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  12598. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  12599. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  12600. }
  12601. }
  12602. /**
  12603. * 递归提取 Word 元素中的文本
  12604. */
  12605. private function extractWordElementText($element) {
  12606. $text = '';
  12607. if (method_exists($element, 'getText')) {
  12608. $text .= $element->getText() . "\n";
  12609. } elseif (method_exists($element, 'getElements')) {
  12610. foreach ($element->getElements() as $childElement) {
  12611. $text .= $this->extractWordElementText($childElement);
  12612. }
  12613. }
  12614. return $text;
  12615. }
  12616. /**
  12617. * 提取图片内容(使用火山引擎 OCR)
  12618. */
  12619. private function extractImageContent($filePath) {
  12620. if (!file_exists($filePath)) {
  12621. Utils::throwError('20003:文件不存在');
  12622. }
  12623. try {
  12624. // 读取图片并转换为 base64
  12625. $imageData = file_get_contents($filePath);
  12626. $base64Image = base64_encode($imageData);
  12627. // 调用火山引擎 OCR 服务
  12628. $content = $this->callVolcEngineOCR($base64Image);
  12629. return trim($content);
  12630. } catch (\Exception $e) {
  12631. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  12632. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  12633. Utils::throwError('20003:图片识别失败');
  12634. }
  12635. }
  12636. /**
  12637. * 调用火山引擎 OCR 服务识别图片文字
  12638. *
  12639. * @param string $base64Image base64 编码的图片数据
  12640. * @return string 识别的文字内容
  12641. */
  12642. private function callVolcEngineOCR($base64Image) {
  12643. $method = 'POST';
  12644. $service = 'cv';
  12645. $host = 'visual.volcengineapi.com';
  12646. $region = env('VOLC_REGION', 'cn-north-1');
  12647. $access_key = env('VOLC_AK');
  12648. $secret_key = env('VOLC_SK');
  12649. $action = 'OCRNormal';
  12650. $version = '2020-08-26';
  12651. if (!$access_key || !$secret_key) {
  12652. Utils::throwError('20003:请配置火山引擎 AK/SK');
  12653. }
  12654. // 请求体
  12655. $body = json_encode([
  12656. 'image_base64' => $base64Image
  12657. ]);
  12658. // 生成签名
  12659. $headers = $this->getVolcEngineSignHeaders(
  12660. $method, $service, $host, $region,
  12661. "Action={$action}&Version={$version}",
  12662. $access_key, $secret_key, $body
  12663. );
  12664. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12665. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  12666. 'headers' => $headers,
  12667. 'body' => $body
  12668. ]);
  12669. $response_arr = json_decode($response->getBody()->getContents(), true);
  12670. // 提取识别的文字
  12671. $textLines = [];
  12672. if (isset($response_arr['data']['line_texts'])) {
  12673. $textLines = $response_arr['data']['line_texts'];
  12674. } elseif (isset($response_arr['data']['ocr_infos'])) {
  12675. foreach ($response_arr['data']['ocr_infos'] as $info) {
  12676. if (isset($info['text'])) {
  12677. $textLines[] = $info['text'];
  12678. }
  12679. }
  12680. }
  12681. if (empty($textLines)) {
  12682. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  12683. return '';
  12684. }
  12685. return implode("\n", $textLines);
  12686. }
  12687. /**
  12688. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  12689. */
  12690. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  12691. $contentType = 'application/json';
  12692. $accept = 'application/json';
  12693. // 获取当前UTC时间
  12694. $t = new DateTime('now', new DateTimeZone('UTC'));
  12695. $xDate = $t->format('Ymd\THis\Z');
  12696. $dateStamp = $t->format('Ymd');
  12697. // 计算 body 的 sha256 哈希
  12698. $payloadHash = hash('sha256', $body);
  12699. // 1. 拼接规范请求串
  12700. $canonicalUri = '/';
  12701. $canonicalQueryString = $queryString;
  12702. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  12703. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  12704. $canonicalRequest = implode("\n", [
  12705. $method,
  12706. $canonicalUri,
  12707. $canonicalQueryString,
  12708. $canonicalHeaders,
  12709. $signedHeaders,
  12710. $payloadHash
  12711. ]);
  12712. // 2. 拼接待签名字符串
  12713. $algorithm = 'HMAC-SHA256';
  12714. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  12715. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  12716. $stringToSign = implode("\n", [
  12717. $algorithm,
  12718. $xDate,
  12719. $credentialScope,
  12720. $hashedCanonicalRequest
  12721. ]);
  12722. // 3. 计算签名
  12723. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  12724. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  12725. // 4. 添加签名到请求头
  12726. $authorizationHeader = sprintf(
  12727. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  12728. $algorithm,
  12729. $access_key,
  12730. $credentialScope,
  12731. $signedHeaders,
  12732. $signature
  12733. );
  12734. return [
  12735. 'Accept' => $accept,
  12736. 'Content-Type' => $contentType,
  12737. 'Host' => $host,
  12738. 'X-Date' => $xDate,
  12739. 'X-Content-Sha256'=> $payloadHash,
  12740. 'Authorization' => $authorizationHeader
  12741. ];
  12742. }
  12743. public function generateScriptWords($cid, $model = 'r1') {
  12744. ini_set('max_execution_time', 0);
  12745. if (!$cid) Utils::throwError('20003: 请选择章节!');
  12746. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  12747. // 模型兼容性处理和思考模式设置
  12748. $thinkingMode = 'disabled';
  12749. $reasoningEffort = 'high';
  12750. if ($model == 'r1') {
  12751. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  12752. $thinkingMode = 'enabled';
  12753. } else {
  12754. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  12755. $thinkingMode = 'disabled';
  12756. }
  12757. $messages = [
  12758. [
  12759. 'role' => 'system',
  12760. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  12761. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  12762. 2.非对话部分请全部用旁白角色代替
  12763. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  12764. ],
  12765. [
  12766. 'role' => 'user',
  12767. 'content' => $content
  12768. ]
  12769. ];
  12770. $post_data = [
  12771. 'model' => $model,
  12772. 'messages' => $messages,
  12773. // 'max_tokens' => 8192,
  12774. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  12775. 'frequency_penalty' => 0,
  12776. 'presence_penalty' => 0,
  12777. 'thinking' => ['type' => $thinkingMode],
  12778. 'response_format' => [
  12779. 'type' => 'text'
  12780. ],
  12781. 'stream' => false
  12782. ];
  12783. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12784. // 根据模型类型选择调用方法
  12785. $fullContent = '';
  12786. $usage = [];
  12787. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12788. // DeepSeek 官方模型使用 DeepSeek API
  12789. $chatResult = $this->chatOnly($post_data);
  12790. } else if (in_array($model, $this->gpt_text_models)) {
  12791. // GPT-5.4 模型使用 TokenRouter API
  12792. $chatResult = $this->gpt54ChatOnly($post_data);
  12793. } else {
  12794. // 其他模型使用火山引擎API
  12795. $chatResult = $this->volcEngineChatCompletion($post_data);
  12796. }
  12797. if (is_array($chatResult)) {
  12798. $fullContent = $chatResult['fullContent'];
  12799. $usage = $chatResult['usage'] ?? [];
  12800. }
  12801. // 仅记录 token 使用明细(不扣积分)
  12802. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  12803. 'model' => $model,
  12804. 'cid' => $cid,
  12805. 'source' => 'generateScriptWords',
  12806. ], $model);
  12807. return $fullContent;
  12808. }
  12809. /**
  12810. * 智能化解析集数信息
  12811. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  12812. *
  12813. * @param string $prompt 用户输入的提示词
  12814. * @return int|null 解析出的集数,如果没有找到则返回null
  12815. */
  12816. private function extractEpisodeNumber($prompt)
  12817. {
  12818. if (empty($prompt)) {
  12819. return null;
  12820. }
  12821. // 定义各种可能的表达模式
  12822. $patterns = [
  12823. // 基本模式:改成N集、调整成N集、修改成N集
  12824. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  12825. // 扩展模式:分成N集、拆分成N集、分割成N集
  12826. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  12827. // 数量模式:N集、共N集、总共N集
  12828. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  12829. // 制作模式:制作N集、生成N集、创建N集
  12830. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  12831. // 计划模式:计划N集、预计N集、打算N集
  12832. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  12833. // 需要模式:需要N集、要N集
  12834. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  12835. // 中文数字模式:改成三集、调整成五集等
  12836. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  12837. // 英文数字模式
  12838. '/(?: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',
  12839. ];
  12840. // 中文数字转阿拉伯数字的映射
  12841. $chineseNumbers = [
  12842. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  12843. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  12844. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  12845. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  12846. ];
  12847. // 逐个尝试匹配模式
  12848. foreach ($patterns as $pattern) {
  12849. if (preg_match($pattern, $prompt, $matches)) {
  12850. $number = trim($matches[1]);
  12851. // 如果是中文数字,转换为阿拉伯数字
  12852. if (isset($chineseNumbers[$number])) {
  12853. return $chineseNumbers[$number];
  12854. }
  12855. // 如果是阿拉伯数字,直接返回
  12856. if (is_numeric($number)) {
  12857. $episodeNum = intval($number);
  12858. // 合理性检查:集数应该在1-100之间
  12859. if ($episodeNum >= 1 && $episodeNum <= 100) {
  12860. return $episodeNum;
  12861. }
  12862. }
  12863. }
  12864. }
  12865. return null;
  12866. }
  12867. /**
  12868. * 调用火山引擎对话(Chat) API
  12869. *
  12870. * @param array $params 包含以下参数:
  12871. * - model: 模型ID(必填)
  12872. * - messages: 消息列表(必填)
  12873. * - stream: 是否流式输出(可选,默认false)
  12874. * - max_tokens: 最大输出token数(可选)
  12875. * - temperature: 采样温度(可选,默认1)
  12876. * - top_p: 核采样概率(可选,默认0.7)
  12877. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  12878. * - presence_penalty: 存在惩罚系数(可选,默认0)
  12879. * - stop: 停止词(可选)
  12880. * - tools: 工具列表(可选)
  12881. * @return array|Generator 非流式返回数组,流式返回生成器
  12882. */
  12883. public function volcEngineChatCompletion(array $params)
  12884. {
  12885. $apiKey = env('VOLC_AI_API_KEY');
  12886. if (empty($apiKey)) {
  12887. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  12888. }
  12889. // 构建请求参数
  12890. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  12891. $requestData = [
  12892. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  12893. 'messages' => $params['messages'] ?? [],
  12894. ];
  12895. if (!in_array($originalModel, $this->valid_text_models)) {
  12896. Utils::throwError('20003:该模型不支持!');
  12897. }
  12898. // 添加可选参数
  12899. if (isset($params['stream'])) {
  12900. $requestData['stream'] = $params['stream'];
  12901. }
  12902. if (isset($params['stream_options'])) {
  12903. $requestData['stream_options'] = $params['stream_options'];
  12904. }
  12905. if (isset($params['max_tokens'])) {
  12906. $requestData['max_tokens'] = $params['max_tokens'];
  12907. }else if (isset($params['max_completion_tokens'])) {
  12908. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  12909. }else {
  12910. $requestData['max_completion_tokens'] = 100000;
  12911. }
  12912. if (isset($params['temperature'])) {
  12913. $requestData['temperature'] = $params['temperature'];
  12914. }
  12915. if (isset($params['top_p'])) {
  12916. $requestData['top_p'] = $params['top_p'];
  12917. }
  12918. if (isset($params['frequency_penalty'])) {
  12919. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  12920. }
  12921. if (isset($params['presence_penalty'])) {
  12922. $requestData['presence_penalty'] = $params['presence_penalty'];
  12923. }
  12924. if (isset($params['stop'])) {
  12925. $requestData['stop'] = $params['stop'];
  12926. }
  12927. if (isset($params['tools'])) {
  12928. $requestData['tools'] = $params['tools'];
  12929. }
  12930. if (isset($params['tool_choice'])) {
  12931. $requestData['tool_choice'] = $params['tool_choice'];
  12932. }
  12933. if (isset($params['response_format'])) {
  12934. $requestData['response_format'] = $params['response_format'];
  12935. }
  12936. if (isset($params['thinking'])) {
  12937. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  12938. if (is_array($params['thinking'])) {
  12939. $requestData['thinking'] = $params['thinking'];
  12940. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  12941. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12942. }
  12943. } else {
  12944. $requestData['thinking'] = ['type' => $params['thinking']];
  12945. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12946. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12947. }
  12948. }
  12949. } else {
  12950. $requestData['thinking'] = ['type' => 'disabled'];
  12951. }
  12952. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12953. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12954. try {
  12955. // 判断是否为流式输出
  12956. $isStream = isset($params['stream']) && $params['stream'] === true;
  12957. if ($isStream) {
  12958. // 流式输出
  12959. // 流式请求默认声明返回 usage(未显式传参时)
  12960. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  12961. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12962. } else {
  12963. // 非流式输出
  12964. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12965. 'headers' => [
  12966. 'Authorization' => 'Bearer ' . $apiKey,
  12967. 'Content-Type' => 'application/json',
  12968. ],
  12969. 'json' => $requestData
  12970. ]);
  12971. $responseData = json_decode($response->getBody(), true);
  12972. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12973. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12974. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12975. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12976. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12977. }
  12978. return [
  12979. 'fullContent' => $fullContent,
  12980. 'fullReasoningContent' => $fullReasoningContent,
  12981. 'usage' => $usage
  12982. ];
  12983. }
  12984. } catch (\Exception $e) {
  12985. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12986. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12987. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12988. }
  12989. }
  12990. /**
  12991. * 火山引擎对话API流式输出
  12992. *
  12993. * @param Client $client HTTP客户端
  12994. * @param string $apiKey API密钥
  12995. * @param array $requestData 请求数据
  12996. * @return Generator
  12997. */
  12998. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12999. {
  13000. try {
  13001. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13002. 'headers' => [
  13003. 'Authorization' => 'Bearer ' . $apiKey,
  13004. 'Content-Type' => 'application/json',
  13005. ],
  13006. 'json' => $requestData,
  13007. 'stream' => true
  13008. ]);
  13009. $body = $response->getBody();
  13010. $buffer = '';
  13011. $fullContent = '';
  13012. $fullReasoningContent = '';
  13013. $usage = [];
  13014. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  13015. // 逐行读取流式响应
  13016. while (!$body->eof()) {
  13017. $chunk = $body->read(1024);
  13018. $buffer .= $chunk;
  13019. // 按行分割
  13020. $lines = explode("\n", $buffer);
  13021. $buffer = array_pop($lines);
  13022. foreach ($lines as $line) {
  13023. $line = trim($line);
  13024. if (empty($line)) {
  13025. continue;
  13026. }
  13027. // 检查是否是SSE数据行
  13028. if (strpos($line, 'data: ') !== 0) {
  13029. continue;
  13030. }
  13031. $data = substr($line, 6);
  13032. if ($data === '[DONE]') {
  13033. dLog('deepseek')->info('收到结束标记');
  13034. break 2;
  13035. }
  13036. try {
  13037. $json = json_decode($data, true);
  13038. if (json_last_error() !== JSON_ERROR_NONE) {
  13039. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  13040. continue;
  13041. }
  13042. if (isset($json['choices'][0]['delta'])) {
  13043. $delta = $json['choices'][0]['delta'];
  13044. // 处理思维链内容
  13045. if (isset($delta['reasoning_content'])) {
  13046. $fullReasoningContent .= $delta['reasoning_content'];
  13047. yield [
  13048. 'type' => 'reasoning',
  13049. 'content' => $delta['reasoning_content'],
  13050. 'full_reasoning' => $fullReasoningContent
  13051. ];
  13052. }
  13053. // 处理回答内容
  13054. if (isset($delta['content'])) {
  13055. $fullContent .= $delta['content'];
  13056. yield [
  13057. 'type' => 'content',
  13058. 'content' => $delta['content'],
  13059. ];
  13060. }
  13061. }
  13062. // 获取使用统计信息
  13063. if (isset($json['usage'])) {
  13064. $usage = $json['usage'];
  13065. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  13066. }
  13067. } catch (\Exception $e) {
  13068. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  13069. continue;
  13070. }
  13071. }
  13072. }
  13073. dLog('deepseek')->info('流式读取完成', [
  13074. 'content_length' => strlen($fullContent),
  13075. 'reasoning_length' => strlen($fullReasoningContent)
  13076. ]);
  13077. yield [
  13078. 'type' => 'done',
  13079. 'full_content' => $fullContent,
  13080. 'full_reasoning' => $fullReasoningContent,
  13081. 'usage' => $usage
  13082. ];
  13083. } catch (\Exception $e) {
  13084. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  13085. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  13086. throw $e;
  13087. }
  13088. }
  13089. /**
  13090. * 检查并创建图片生成任务
  13091. *
  13092. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  13093. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  13094. * @param string $nameKey 资源名称字段('role' 或 'scene')
  13095. * @param string $art_style 美术风格
  13096. * @return array 更新后的资源列表
  13097. */
  13098. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  13099. {
  13100. // 确保参数为数组
  13101. $merged_items = is_array($merged_items) ? $merged_items : [];
  13102. $global_items = is_array($global_items) ? $global_items : [];
  13103. // 构建全局资源映射表,用于快速查找
  13104. $global_map = [];
  13105. foreach ($global_items as $item) {
  13106. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13107. if ($itemKey === '') {
  13108. continue;
  13109. }
  13110. $global_map[$itemKey] = $item;
  13111. }
  13112. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  13113. foreach ($merged_items as &$item) {
  13114. $item_name = getProp($item, $nameKey);
  13115. $item_description = getProp($item, 'description');
  13116. // $item_url = getProp($item, 'url');
  13117. // // 如果已有图片URL,跳过
  13118. // if (!empty($item_url)) {
  13119. // continue;
  13120. // }
  13121. // 如果是旁白角色,跳过
  13122. if ($nameKey === 'role' && $item_name === '旁白') {
  13123. continue;
  13124. }
  13125. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13126. if ($itemKey === '') {
  13127. continue;
  13128. }
  13129. $need_create_task = false;
  13130. // 条件1:在全局资源中找不到匹配的名称
  13131. if (!isset($global_map[$itemKey])) {
  13132. $need_create_task = true;
  13133. } else {
  13134. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13135. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13136. $current_description = trim((string)$item_description);
  13137. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13138. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13139. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13140. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13141. $need_create_task = true;
  13142. }
  13143. }
  13144. // 如果需要创建任务,调用图片生成服务
  13145. if ($need_create_task) {
  13146. try {
  13147. // 优先使用 pic_prompt,如果没有则使用 description
  13148. $pic_prompt = getProp($item, 'pic_prompt');
  13149. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13150. // 添加美术风格前缀
  13151. if ($art_style) {
  13152. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13153. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13154. $description = "{$prefix}:{$description}";
  13155. }
  13156. $params = [
  13157. 'prompt' => $description,
  13158. 'ref_img_urls' => []
  13159. ];
  13160. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13161. $task_id = $task->id;
  13162. if ($task_id) {
  13163. $item['task_id'] = $task_id;
  13164. $item['task_status'] = 'processing';
  13165. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13166. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13167. }
  13168. } catch (\Exception $e) {
  13169. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13170. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13171. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13172. // 不抛出异常,继续处理其他资源
  13173. }
  13174. }
  13175. }
  13176. return $merged_items;
  13177. }
  13178. /**
  13179. * 同步新出现的主体和场景到全局
  13180. *
  13181. * @param int $anime_id 动漫ID
  13182. * @param array $merged_roles 合并后的角色列表
  13183. * @param array $merged_scenes 合并后的场景列表
  13184. * @param array $global_roles 全局角色列表
  13185. * @param array $global_scenes 全局场景列表
  13186. * @return void
  13187. */
  13188. private function syncNewResourcesToGlobal(
  13189. int $anime_id,
  13190. array $merged_roles,
  13191. array $merged_scenes,
  13192. array $global_roles,
  13193. array $global_scenes
  13194. ): void {
  13195. // 构建全局角色映射表
  13196. $global_role_map = [];
  13197. foreach ($global_roles as $role) {
  13198. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13199. if ($roleKey !== '') {
  13200. $global_role_map[$roleKey] = $role;
  13201. }
  13202. }
  13203. // 构建全局场景映射表
  13204. $global_scene_map = [];
  13205. foreach ($global_scenes as $scene) {
  13206. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13207. if ($sceneKey !== '') {
  13208. $global_scene_map[$sceneKey] = $scene;
  13209. }
  13210. }
  13211. $need_update = false;
  13212. $new_global_roles = $global_roles;
  13213. $new_global_scenes = $global_scenes;
  13214. // 检查并添加新角色到全局
  13215. foreach ($merged_roles as $role) {
  13216. $role_name = getProp($role, 'role');
  13217. // 跳过旁白
  13218. if ($role_name === '旁白') {
  13219. continue;
  13220. }
  13221. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13222. if ($roleKey === '') {
  13223. continue;
  13224. }
  13225. // 如果全局中不存在该角色,添加到全局
  13226. if (!isset($global_role_map[$roleKey])) {
  13227. $new_global_roles[] = [
  13228. 'role' => $role_name,
  13229. 'description' => getProp($role, 'description', ''),
  13230. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13231. 'voice_name' => getProp($role, 'voice_name', ''),
  13232. 'voice_type' => getProp($role, 'voice_type', ''),
  13233. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13234. 'url' => getProp($role, 'url', ''),
  13235. 'task_id' => getProp($role, 'task_id', ''),
  13236. 'task_status' => getProp($role, 'task_status', ''),
  13237. ];
  13238. $global_role_map[$roleKey] = true; // 标记已添加
  13239. $need_update = true;
  13240. dLog('deepseek')->info("新角色同步到全局", [
  13241. 'anime_id' => $anime_id,
  13242. 'role' => $role_name,
  13243. 'task_id' => getProp($role, 'task_id', ''),
  13244. ]);
  13245. }
  13246. // else {
  13247. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13248. // $global_role = $global_role_map[$roleKey];
  13249. // if (is_array($global_role)) {
  13250. // $updated = false;
  13251. // $update_fields = [];
  13252. // // 检查描述是否更新
  13253. // $current_description = trim((string)getProp($role, 'description'));
  13254. // $global_description = trim((string)getProp($global_role, 'description'));
  13255. // if ($current_description !== '' && $current_description !== $global_description) {
  13256. // $updated = true;
  13257. // $update_fields[] = 'description';
  13258. // }
  13259. // // 检查pic_prompt是否更新
  13260. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13261. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13262. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13263. // $updated = true;
  13264. // $update_fields[] = 'pic_prompt';
  13265. // }
  13266. // // 检查图片任务信息是否更新
  13267. // $current_task_id = getProp($role, 'task_id');
  13268. // $global_task_id = getProp($global_role, 'task_id');
  13269. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13270. // $updated = true;
  13271. // $update_fields[] = 'task_id';
  13272. // }
  13273. // // 如果有更新,同步到全局
  13274. // if ($updated) {
  13275. // foreach ($new_global_roles as &$global_role_item) {
  13276. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  13277. // if ($global_role_key === $roleKey) {
  13278. // if (in_array('description', $update_fields)) {
  13279. // $global_role_item['description'] = $current_description;
  13280. // }
  13281. // if (in_array('pic_prompt', $update_fields)) {
  13282. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  13283. // }
  13284. // if (in_array('task_id', $update_fields)) {
  13285. // $global_role_item['task_id'] = $current_task_id;
  13286. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  13287. // $global_role_item['url'] = getProp($role, 'url', '');
  13288. // }
  13289. // break;
  13290. // }
  13291. // }
  13292. // $need_update = true;
  13293. // dLog('deepseek')->info("角色信息更新到全局", [
  13294. // 'anime_id' => $anime_id,
  13295. // 'role' => $role_name,
  13296. // 'update_fields' => implode(',', $update_fields),
  13297. // ]);
  13298. // }
  13299. // }
  13300. // }
  13301. }
  13302. // 检查并添加新场景到全局
  13303. foreach ($merged_scenes as $scene) {
  13304. $scene_name = getProp($scene, 'scene');
  13305. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  13306. if ($sceneKey === '') {
  13307. continue;
  13308. }
  13309. // 如果全局中不存在该场景,添加到全局
  13310. if (!isset($global_scene_map[$sceneKey])) {
  13311. $new_global_scenes[] = [
  13312. 'scene' => $scene_name,
  13313. 'description' => getProp($scene, 'description', ''),
  13314. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  13315. 'url' => getProp($scene, 'url', ''),
  13316. 'task_id' => getProp($scene, 'task_id', ''),
  13317. 'task_status' => getProp($scene, 'task_status', ''),
  13318. ];
  13319. $global_scene_map[$sceneKey] = true; // 标记已添加
  13320. $need_update = true;
  13321. dLog('deepseek')->info("新场景同步到全局", [
  13322. 'anime_id' => $anime_id,
  13323. 'scene' => $scene_name,
  13324. 'task_id' => getProp($scene, 'task_id', ''),
  13325. ]);
  13326. }
  13327. // else {
  13328. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13329. // $global_scene = $global_scene_map[$sceneKey];
  13330. // if (is_array($global_scene)) {
  13331. // $updated = false;
  13332. // $update_fields = [];
  13333. // // 检查描述是否更新
  13334. // $current_description = trim((string)getProp($scene, 'description'));
  13335. // $global_description = trim((string)getProp($global_scene, 'description'));
  13336. // if ($current_description !== '' && $current_description !== $global_description) {
  13337. // $updated = true;
  13338. // $update_fields[] = 'description';
  13339. // }
  13340. // // 检查pic_prompt是否更新
  13341. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  13342. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  13343. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13344. // $updated = true;
  13345. // $update_fields[] = 'pic_prompt';
  13346. // }
  13347. // // 检查图片任务信息是否更新
  13348. // $current_task_id = getProp($scene, 'task_id');
  13349. // $global_task_id = getProp($global_scene, 'task_id');
  13350. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13351. // $updated = true;
  13352. // $update_fields[] = 'task_id';
  13353. // }
  13354. // // 如果有更新,同步到全局
  13355. // if ($updated) {
  13356. // foreach ($new_global_scenes as &$global_scene_item) {
  13357. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  13358. // if ($global_scene_key === $sceneKey) {
  13359. // if (in_array('description', $update_fields)) {
  13360. // $global_scene_item['description'] = $current_description;
  13361. // }
  13362. // if (in_array('pic_prompt', $update_fields)) {
  13363. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  13364. // }
  13365. // if (in_array('task_id', $update_fields)) {
  13366. // $global_scene_item['task_id'] = $current_task_id;
  13367. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  13368. // $global_scene_item['url'] = getProp($scene, 'url', '');
  13369. // }
  13370. // break;
  13371. // }
  13372. // }
  13373. // $need_update = true;
  13374. // dLog('deepseek')->info("场景信息更新到全局", [
  13375. // 'anime_id' => $anime_id,
  13376. // 'scene' => $scene_name,
  13377. // 'update_fields' => implode(',', $update_fields),
  13378. // ]);
  13379. // }
  13380. // }
  13381. // }
  13382. }
  13383. // 如果有新增或更新,更新数据库
  13384. if ($need_update) {
  13385. $update_data = [
  13386. 'roles' => json_encode($new_global_roles, 256),
  13387. 'scenes' => json_encode($new_global_scenes, 256),
  13388. 'updated_at' => date('Y-m-d H:i:s'),
  13389. ];
  13390. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13391. if ($result !== false) {
  13392. dLog('deepseek')->info("全局角色和场景更新成功", [
  13393. 'anime_id' => $anime_id,
  13394. 'roles_count' => count($new_global_roles),
  13395. 'scenes_count' => count($new_global_scenes),
  13396. ]);
  13397. } else {
  13398. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  13399. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  13400. }
  13401. }
  13402. }
  13403. }