DeepSeekService.php 868 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Models\MpTaskCenter;
  11. use App\Models\MpUserPointsDetail;
  12. use App\Services\AIGeneration\AIImageGenerationService;
  13. use App\Services\PointsService;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. use Smalot\PdfParser\Parser as PdfParser;
  20. use TCPDF;
  21. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  22. use Predis\Command\Traits\Get\Get;
  23. class DeepSeekService
  24. {
  25. private $url;
  26. private $api_key;
  27. private $sys_message;
  28. private $headers;
  29. private $valid_text_models;
  30. private $gpt_text_models;
  31. private $gemini_text_models;
  32. protected $aiImageGenerationService;
  33. protected $pointsService;
  34. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  35. $this->aiImageGenerationService = $aiImageGenerationService;
  36. $this->pointsService = $pointsService;
  37. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  38. $this->api_key = env('DEEPSEEK_API_KEY');
  39. $this->headers = [
  40. 'Authorization' => 'Bearer '.$this->api_key,
  41. 'Content-Type' => 'application/json; charset=UTF-8'
  42. ];
  43. // 火山引擎模型列表
  44. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  45. // GPT文本模型列表
  46. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  47. // Gemini文本模型列表
  48. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  49. $this->sys_message = [
  50. 'role' => 'system',
  51. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  52. 强制要求:\n
  53. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  54. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  55. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  56. 普通要求:\n
  57. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  58. 2.<分集剧本>的要求如下:
  59.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  60.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  61.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  62.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  63. \n\n
  64. 示例如下:\n
  65. ###剧本名:西昆仑
  66. ###故事梗概
  67. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  68. ###剧本亮点
  69. 亮点1:绝境奇药,生死一线
  70. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  71. 亮点2:结拜兄妹,化解尴尬
  72. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  73. 亮点3:纤发夺命,情愫暗涌
  74. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  75. ###人物关系
  76. 阿雪与梁萧之间存在兄妹之情。
  77. ###核心矛盾
  78. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  79. ###主体列表
  80. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  81. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  82. 阴阳球:天地异宝,能化生精气,救人于危难。
  83. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  84. ###美术风格
  85. 基础画风风格词:厚涂古风
  86. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  87. ###场景列表
  88. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  89. ###分集剧本
  90. ##分集01
  91. 第1集: 第一集的标题
  92. 场景描述:地点、时间、场景
  93. 运镜:固定近距离
  94. 出场角色:男主、女主
  95. 台词内容:
  96. 女主: 女主对话
  97. 男主:男主对话
  98. 女主: 女主对话
  99. 男主: 男主对话
  100. ##分集02
  101. 第2集: 第二集的标题
  102. 场景描述:地点、时间、场景
  103. 运镜:固定近距离
  104. 出场角色:男主、女主
  105. 台词内容:
  106. 女主: 女主对话
  107. 男主:男主对话
  108. 女主: 女主对话
  109. 男主: 男主对话"
  110. ];
  111. }
  112. /**
  113. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  114. *
  115. * @param array $data 请求参数
  116. * @return \Generator 返回生成器,用于流式输出
  117. */
  118. public function generateText($data) {
  119. // 获取请求参数
  120. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  121. $messages = getProp($data, 'messages', []);
  122. $systemPrompt = getProp($data, 'system_prompt', '');
  123. $prompt = getProp($data, 'prompt', '');
  124. $images = getProp($data, 'images', []); // 支持多张图片
  125. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  126. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  127. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  128. $isGeminiModel = in_array($model, $this->gemini_text_models);
  129. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  130. Utils::throwError('20003:仅Gemini模型支持视频输入');
  131. }
  132. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  133. $uid = Site::getUid();
  134. $chargeModality = '';
  135. $chargePoints = 0;
  136. $hasImageMedia = !empty($images) || !empty($imageUrls)
  137. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  138. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  139. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  140. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  141. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  142. $pricingModel = $this->geminiMultimodalPricingModel($model);
  143. if ($pricingModel !== '') {
  144. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  145. if ($chargePoints > 0) {
  146. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  147. }
  148. }
  149. }
  150. // 如果没有提供messages,则根据system_prompt、content和images构建
  151. if (empty($messages)) {
  152. $messages = [];
  153. // 添加系统提示词
  154. if (!empty($systemPrompt)) {
  155. $messages[] = [
  156. 'role' => 'system',
  157. 'content' => $systemPrompt
  158. ];
  159. }
  160. // 构建用户消息内容(支持文本+图片)
  161. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  162. $userMessage = [
  163. 'role' => 'user',
  164. 'content' => []
  165. ];
  166. // 添加文本内容
  167. if (!empty($prompt)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'text',
  170. 'text' => $prompt
  171. ];
  172. }
  173. // 处理上传的图片文件
  174. if (!empty($images)) {
  175. if (!is_array($images)) {
  176. $images = [$images];
  177. }
  178. foreach ($images as $image) {
  179. $imageBase64 = $this->processImageToBase64($image);
  180. if ($imageBase64) {
  181. $userMessage['content'][] = [
  182. 'type' => 'image_url',
  183. 'image_url' => [
  184. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  185. ]
  186. ];
  187. }
  188. }
  189. }
  190. // 处理图片URL
  191. if (!empty($imageUrls)) {
  192. if (!is_array($imageUrls)) {
  193. $imageUrls = [$imageUrls];
  194. }
  195. foreach ($imageUrls as $url) {
  196. if (!empty($url)) {
  197. $userMessage['content'][] = [
  198. 'type' => 'image_url',
  199. 'image_url' => [
  200. 'url' => $url
  201. ]
  202. ];
  203. }
  204. }
  205. }
  206. // 处理上传的视频文件(仅 Gemini)
  207. if (!empty($videos) && $isGeminiModel) {
  208. if (!is_array($videos)) {
  209. $videos = [$videos];
  210. }
  211. foreach ($videos as $video) {
  212. $inlineData = $this->processMediaToInlineData($video);
  213. if ($inlineData) {
  214. $userMessage['content'][] = [
  215. 'type' => 'video',
  216. 'inline_data' => $inlineData
  217. ];
  218. }
  219. }
  220. }
  221. // 处理视频URL(仅 Gemini)
  222. if (!empty($videoUrls) && $isGeminiModel) {
  223. if (!is_array($videoUrls)) {
  224. $videoUrls = [$videoUrls];
  225. }
  226. foreach ($videoUrls as $url) {
  227. if (!empty($url)) {
  228. $userMessage['content'][] = [
  229. 'type' => 'video_url',
  230. 'video_url' => ['url' => $url]
  231. ];
  232. }
  233. }
  234. }
  235. // 如果只有文本内容,简化为字符串格式
  236. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  237. $userMessage['content'] = $userMessage['content'][0]['text'];
  238. }
  239. $messages[] = $userMessage;
  240. }
  241. }
  242. // 验证messages不为空
  243. if (empty($messages)) {
  244. Utils::throwError('20003:请提供有效的对话内容');
  245. }
  246. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  247. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  248. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  249. if ($model === 'deepseek-chat') {
  250. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  251. $model = 'deepseek-v4-flash';
  252. $thinkingMode = 'disabled';
  253. } elseif ($model === 'deepseek-reasoner') {
  254. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'enabled';
  257. }
  258. // 构建请求参数
  259. $post_data = [
  260. 'model' => $model,
  261. 'messages' => $messages,
  262. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  263. 'temperature' => getProp($data, 'temperature', 1),
  264. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  265. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  266. 'thinking' => ['type' => $thinkingMode],
  267. 'stream' => true // 启用流式输出
  268. ];
  269. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  270. // 添加可选参数
  271. if (isset($data['top_p'])) {
  272. $post_data['top_p'] = $data['top_p'];
  273. }
  274. if (isset($data['response_format'])) {
  275. $post_data['response_format'] = $data['response_format'];
  276. }
  277. // 根据模型类型选择调用方法
  278. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  279. // DeepSeek 官方模型使用 DeepSeek API
  280. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  281. } else if (in_array($model, $this->gpt_text_models)) {
  282. // GPT 模型使用 TokenRouter API
  283. $streamGenerator = $this->gpt54StreamResponse($post_data);
  284. } else if (in_array($model, $this->gemini_text_models)) {
  285. // Gemini 模型使用 Gemini API
  286. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  287. } else if (in_array($model, $this->valid_text_models)) {
  288. // 火山引擎支持的模型使用火山引擎 API
  289. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  290. } else {
  291. Utils::throwError('20003:不支持的模型: ' . $model);
  292. }
  293. if ($chargePoints > 0) {
  294. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  295. }
  296. // 纯文本(不扣积分):流式生成成功后仅记录 token 使用明细
  297. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  298. }
  299. /**
  300. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  301. *
  302. * @param \Generator $generator
  303. * @param int $uid
  304. * @param string $model
  305. * @return \Generator
  306. */
  307. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  308. {
  309. $recorded = false;
  310. foreach ($generator as $chunk) {
  311. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  312. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  313. 'model' => $model,
  314. 'source' => $source,
  315. ], $model);
  316. $recorded = true;
  317. }
  318. yield $chunk;
  319. }
  320. }
  321. /**
  322. * 流式生成成功后再按 Gemini 多模态规则扣费
  323. *
  324. * @param \Generator $generator
  325. * @param int $uid
  326. * @param string $model
  327. * @param int $points
  328. * @param string $modality
  329. * @return \Generator
  330. */
  331. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  332. {
  333. $charged = false;
  334. foreach ($generator as $chunk) {
  335. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  336. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  337. if ($fullContent !== '') {
  338. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  339. $charged = true;
  340. }
  341. }
  342. yield $chunk;
  343. }
  344. }
  345. /**
  346. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  347. *
  348. * @param int $uid
  349. * @param string $model
  350. * @param int $points
  351. * @param string $modality
  352. * @param mixed $usage
  353. * @return void
  354. */
  355. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  356. {
  357. $result = $this->pointsService->recordChatCharge(
  358. $uid,
  359. $points,
  360. $this->pointsService->getTokensFromUsage($usage),
  361. [
  362. 'model' => $model,
  363. 'modality' => $modality,
  364. 'source' => 'generateText',
  365. ],
  366. '',
  367. $model
  368. );
  369. if (empty($result['charged'])) {
  370. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  371. }
  372. }
  373. /**
  374. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  375. *
  376. * @param string $model
  377. * @return string
  378. */
  379. private function geminiMultimodalPricingModel(string $model): string
  380. {
  381. $map = [
  382. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  383. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  384. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  385. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  386. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  387. ];
  388. return $map[$model] ?? '';
  389. }
  390. /**
  391. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  392. *
  393. * @param array $messages
  394. * @param array $mediaTypes
  395. * @return bool
  396. */
  397. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  398. {
  399. foreach ($messages as $message) {
  400. $content = getProp($message, 'content', '');
  401. if (!is_array($content)) {
  402. continue;
  403. }
  404. foreach ($content as $part) {
  405. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  406. return true;
  407. }
  408. }
  409. }
  410. return false;
  411. }
  412. public function createGenerateText($data) {
  413. $file = getProp($data, 'file');
  414. $episode_num = getProp($data, 'episode_num');
  415. $uid = Site::getUid();
  416. $cpid = Site::getCpid();
  417. if (!$file) {
  418. Utils::throwError('20003:请上传文件');
  419. }
  420. // 提取文件内容
  421. $content = $this->extractFileContent($file);
  422. if (!$content) {
  423. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  424. }
  425. // 拆分章节并校验章节总数、标题连续性
  426. if ($episode_num) {
  427. $this->validateGenerateTextChapters($content, (int)$episode_num);
  428. }
  429. // 获取原始文件名(不含扩展名)作为script_name
  430. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  431. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  432. // 字节安全剥离,不依赖服务器locale设置
  433. $originalName = $file->getClientOriginalName();
  434. $extension = $file->getClientOriginalExtension();
  435. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  436. ? substr($originalName, 0, -strlen($extension) - 1)
  437. : $originalName;
  438. if ($script_name === '') {
  439. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  440. }
  441. // 如果同一用户的剧本名存在则提示
  442. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  443. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  444. }
  445. // 插入数据到mp_scripts表
  446. $script_id = DB::table('mp_scripts')->insertGetId([
  447. 'script_name' => $script_name,
  448. 'user_id' => $uid,
  449. 'cpid' => $cpid,
  450. 'content' => $content,
  451. 'created_at' => date('Y-m-d H:i:s'),
  452. 'updated_at' => date('Y-m-d H:i:s')
  453. ]);
  454. return [
  455. 'script_id' => $script_id,
  456. 'script_name' => $script_name
  457. ];
  458. }
  459. /**
  460. * AI对话调用成功后的积分扣费(返回结果前调用)
  461. *
  462. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  463. *
  464. * @param int $uid
  465. * @param int $tokens
  466. * @param array $chargeInfo
  467. * @return void
  468. */
  469. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  470. {
  471. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  472. $model = (string)getProp($chargeInfo, 'model', '');
  473. $result = $this->pointsService->recordChatCharge(
  474. $uid,
  475. $this->pointsService->getChatChargePoints($model),
  476. $tokens,
  477. $chargeInfo,
  478. '',
  479. $model !== '' ? $model : 'deepseek'
  480. );
  481. if (empty($result['charged'])) {
  482. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  483. }
  484. }
  485. /**
  486. * 安全获取当前登录用户ID
  487. *
  488. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  489. *
  490. * @return int
  491. */
  492. private function getCurrentUid(): int
  493. {
  494. try {
  495. return (int)Site::getUid();
  496. } catch (\Throwable $e) {
  497. return 0;
  498. }
  499. }
  500. /**
  501. * 记录文生文 token 使用明细(仅记录,不扣积分)
  502. *
  503. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  504. *
  505. * @param int $uid 用户ID(0 时跳过)
  506. * @param int $tokens 消耗 token 数
  507. * @param array $chargeInfo 计费/来源信息(model、source 等)
  508. * @param string $apiType API 类型/模型标识
  509. * @return void
  510. */
  511. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  512. {
  513. try {
  514. $this->pointsService->recordTokenOnlyDetail(
  515. $uid,
  516. $tokens,
  517. $chargeInfo,
  518. MpUserPointsDetail::TYPE_CHAT,
  519. $apiType,
  520. ''
  521. );
  522. } catch (\Throwable $e) {
  523. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  524. 'uid' => $uid,
  525. 'source' => $chargeInfo['source'] ?? '',
  526. ]);
  527. }
  528. }
  529. /**
  530. * 拆分剧本内容并校验章节总数与标题连续性
  531. *
  532. * @param string $content
  533. * @param int $episodeNum
  534. * @return void
  535. */
  536. private function validateGenerateTextChapters($content, $episodeNum)
  537. {
  538. $chapters = splitContent($content);
  539. if (count($chapters) !== $episodeNum) {
  540. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  541. }
  542. if (empty($chapters)) {
  543. return;
  544. }
  545. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  546. $numbers = [];
  547. $unparsedIndex = null;
  548. foreach ($chapters as $index => $chapter) {
  549. $num = $this->parseChapterNumber($chapter['title']);
  550. if ($num === null) {
  551. $unparsedIndex = $index;
  552. break;
  553. }
  554. $numbers[] = $num;
  555. }
  556. if ($unparsedIndex === null) {
  557. $expected = 1;
  558. foreach ($numbers as $index => $num) {
  559. if ($num !== $expected) {
  560. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  561. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  562. }
  563. $expected++;
  564. }
  565. return;
  566. }
  567. // 标题格式无法用正则确认时,交给模型分析
  568. $titles = array_column($chapters, 'title');
  569. $aiResult = $this->validateChapterSequenceByAI($titles);
  570. if ($aiResult['valid'] === false) {
  571. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  572. if (isset($chapters[$badIndex - 1])) {
  573. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  574. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  575. }
  576. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  577. }
  578. if ($aiResult['valid'] === null) {
  579. if (isset($chapters[$unparsedIndex])) {
  580. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  581. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  582. }
  583. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  584. }
  585. }
  586. /**
  587. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  588. *
  589. * @param string $title
  590. * @return int|null
  591. */
  592. private function parseChapterNumber($title)
  593. {
  594. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  595. return null;
  596. }
  597. return $this->convertChineseNumber($match[1]);
  598. }
  599. /**
  600. * 中文数字转阿拉伯数字(支持到千)
  601. *
  602. * @param string $numStr
  603. * @return int
  604. */
  605. private function convertChineseNumber($numStr)
  606. {
  607. if (preg_match('/^\d+$/', $numStr)) {
  608. return (int)$numStr;
  609. }
  610. $map = [
  611. '零' => 0,
  612. '一' => 1,
  613. '二' => 2,
  614. '两' => 2,
  615. '三' => 3,
  616. '四' => 4,
  617. '五' => 5,
  618. '六' => 6,
  619. '七' => 7,
  620. '八' => 8,
  621. '九' => 9
  622. ];
  623. $total = 0;
  624. $section = 0;
  625. $length = mb_strlen($numStr);
  626. for ($i = 0; $i < $length; $i++) {
  627. $char = mb_substr($numStr, $i, 1);
  628. if (isset($map[$char])) {
  629. $section = $map[$char];
  630. } elseif ($char === '十') {
  631. $total += $section === 0 ? 10 : $section * 10;
  632. $section = 0;
  633. } elseif ($char === '百') {
  634. $total += $section === 0 ? 100 : $section * 100;
  635. $section = 0;
  636. } elseif ($char === '千') {
  637. $total += $section === 0 ? 1000 : $section * 1000;
  638. $section = 0;
  639. }
  640. }
  641. return $total + $section;
  642. }
  643. /**
  644. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  645. *
  646. * @param array $titles
  647. * @return array{valid: bool|null, invalid_index: int|null}
  648. */
  649. private function validateChapterSequenceByAI($titles)
  650. {
  651. $titleLines = [];
  652. foreach (array_slice($titles, 0, 200) as $index => $title) {
  653. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  654. }
  655. $result = [
  656. 'valid' => null,
  657. 'invalid_index' => null
  658. ];
  659. $post_data = [
  660. 'model' => 'deepseek-v4-flash',
  661. 'messages' => [
  662. [
  663. 'role' => 'system',
  664. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  665. ],
  666. [
  667. 'role' => 'user',
  668. 'content' => implode("\n", $titleLines),
  669. ],
  670. ],
  671. 'temperature' => 0,
  672. 'frequency_penalty' => 0,
  673. 'presence_penalty' => 0,
  674. 'stream' => false,
  675. ];
  676. try {
  677. $result = $this->chatOnly($post_data, 8);
  678. $content = trim((string)($result['fullContent'] ?? ''));
  679. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  680. $result['valid'] = strtolower($match[1]) === 'true';
  681. }
  682. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  683. $result['invalid_index'] = (int)$match[1];
  684. }
  685. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  686. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  687. 'model' => 'deepseek-v4-flash',
  688. 'source' => 'validateChapterSequenceByAI',
  689. ], 'deepseek-v4-flash');
  690. } catch (\Exception $e) {
  691. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  692. }
  693. return $result;
  694. }
  695. /**
  696. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  697. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  698. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  699. *
  700. * @param array $data 请求参数
  701. * @return \Generator
  702. */
  703. public function newGenerateTextStream($data) {
  704. $model = getProp($data, 'model', 'deepseek-v4-pro');
  705. $messages = getProp($data, 'messages', []);
  706. $systemPrompt = getProp($data, 'system_prompt', '');
  707. $prompt = getProp($data, 'prompt', '');
  708. $images = getProp($data, 'images', []);
  709. $imageUrls = getProp($data, 'image_urls', []);
  710. $responseFormat = getProp($data, 'response_format', 'text');
  711. $templateId = getProp($data, 'template_id', 0);
  712. $script_id = getProp($data, 'script_id', 0);
  713. $sequence = getProp($data, 'sequence', 0);
  714. $generateTaskId = 0;
  715. $uid = Site::getUid();
  716. if ($script_id > 0) {
  717. $existingTask = DB::table('mp_script_generate_tasks')
  718. ->where('uid', $uid)
  719. ->where('script_id', $script_id)
  720. ->orderByDesc('id')
  721. ->first();
  722. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  723. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  724. }
  725. }
  726. // 如果提供了script_id,从数据库获取剧本内容作为原文
  727. $originalContent = '';
  728. $hasValidScript = false;
  729. if ($script_id > 0) {
  730. $script = DB::table('mp_scripts')
  731. ->where('id', $script_id)
  732. ->where('is_deleted', 0)
  733. ->first();
  734. if (!$script) {
  735. Utils::throwError('20003:剧本不存在或已删除');
  736. }
  737. $originalContent = $script->content ?? '';
  738. if (empty($originalContent)) {
  739. Utils::throwError('20003:剧本内容为空');
  740. }
  741. $hasValidScript = true;
  742. if (!empty($prompt)) {
  743. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  744. } else {
  745. $prompt = "原文内容:\n" . $originalContent;
  746. }
  747. }
  748. // 如果提供了template_id,从数据库获取template_prompt
  749. if ($templateId > 0) {
  750. $template = DB::table('mp_prompt_templates')
  751. ->where('id', $templateId)
  752. ->where('is_deleted', 0)
  753. ->first();
  754. if (!$template) {
  755. Utils::throwError('20003:模板不存在或已删除');
  756. }
  757. $templatePrompt = $template->template_prompt ?? '';
  758. if (!empty($templatePrompt)) {
  759. if (!empty($prompt)) {
  760. $prompt = $templatePrompt . "\n\n" . $prompt;
  761. } else {
  762. $prompt = $templatePrompt;
  763. }
  764. }
  765. }
  766. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  767. if (empty($messages)) {
  768. $messages = [];
  769. if (!empty($systemPrompt)) {
  770. $messages[] = [
  771. 'role' => 'system',
  772. 'content' => $systemPrompt
  773. ];
  774. }
  775. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  776. $userMessage = [
  777. 'role' => 'user',
  778. 'content' => []
  779. ];
  780. if (!empty($prompt)) {
  781. $userMessage['content'][] = [
  782. 'type' => 'text',
  783. 'text' => $prompt
  784. ];
  785. }
  786. if (!empty($images)) {
  787. if (!is_array($images)) {
  788. $images = [$images];
  789. }
  790. foreach ($images as $image) {
  791. $imageBase64 = $this->processImageToBase64($image);
  792. if ($imageBase64) {
  793. $userMessage['content'][] = [
  794. 'type' => 'image_url',
  795. 'image_url' => [
  796. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  797. ]
  798. ];
  799. }
  800. }
  801. }
  802. if (!empty($imageUrls)) {
  803. if (!is_array($imageUrls)) {
  804. $imageUrls = [$imageUrls];
  805. }
  806. foreach ($imageUrls as $url) {
  807. if (!empty($url)) {
  808. $userMessage['content'][] = [
  809. 'type' => 'image_url',
  810. 'image_url' => [
  811. 'url' => $url
  812. ]
  813. ];
  814. }
  815. }
  816. }
  817. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  818. $userMessage['content'] = $userMessage['content'][0]['text'];
  819. }
  820. $messages[] = $userMessage;
  821. }
  822. }
  823. if (empty($messages)) {
  824. Utils::throwError('20003:请提供有效的对话内容');
  825. }
  826. // 模型兼容性处理
  827. $thinkingMode = getProp($data, 'thinking', 'disabled');
  828. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  829. if ($model === 'deepseek-chat') {
  830. $model = 'deepseek-v4-flash';
  831. $thinkingMode = 'disabled';
  832. } elseif ($model === 'deepseek-reasoner') {
  833. $model = 'deepseek-v4-flash';
  834. $thinkingMode = 'enabled';
  835. }
  836. // 构建请求参数(流式)
  837. $post_data = [
  838. 'model' => $model,
  839. 'messages' => $messages,
  840. 'temperature' => getProp($data, 'temperature', 1),
  841. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  842. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  843. 'thinking' => ['type' => $thinkingMode],
  844. 'stream' => true
  845. ];
  846. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  847. if (isset($data['top_p'])) {
  848. $post_data['top_p'] = $data['top_p'];
  849. }
  850. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  851. if ($responseFormat === 'json') {
  852. $hasJsonKeyword = false;
  853. foreach ($post_data['messages'] as $message) {
  854. if (isset($message['content'])) {
  855. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  856. if (stripos($content, 'json') !== false) {
  857. $hasJsonKeyword = true;
  858. break;
  859. }
  860. }
  861. }
  862. if (!$hasJsonKeyword) {
  863. $lastMessageIndex = count($post_data['messages']) - 1;
  864. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  865. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  866. if (is_string($lastContent)) {
  867. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  868. } elseif (is_array($lastContent)) {
  869. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  870. if ($contentPart['type'] === 'text') {
  871. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  872. break;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. $post_data['response_format'] = ['type' => 'json_object'];
  879. }
  880. // 如果提供了script_id,创建剧本资产生成任务
  881. if ($script_id > 0) {
  882. $uid = Site::getUid();
  883. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  884. 'uid' => $uid,
  885. 'script_id' => $script_id,
  886. 'sequence' => $sequence,
  887. 'status' => 'processing',
  888. 'prompt' => getProp($data, 'prompt', ''),
  889. 'started_at' => date('Y-m-d H:i:s'),
  890. 'created_at' => date('Y-m-d H:i:s'),
  891. 'updated_at' => date('Y-m-d H:i:s')
  892. ]);
  893. }
  894. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  895. if ($hasValidScript) {
  896. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  897. }
  898. // 根据模型类型选择流式调用方法
  899. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  900. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  901. } elseif (in_array($model, $this->gpt_text_models)) {
  902. $streamGenerator = $this->gpt54StreamResponse($post_data);
  903. } elseif (in_array($model, $this->gemini_text_models)) {
  904. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  905. } elseif (in_array($model, $this->valid_text_models)) {
  906. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  907. } else {
  908. Utils::throwError('20003:不支持的模型: ' . $model);
  909. }
  910. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  911. return $this->wrapNewGenerateTextStream($streamGenerator, [
  912. 'uid' => $uid,
  913. 'model' => $model,
  914. 'generate_task_id' => $generateTaskId,
  915. 'has_valid_script' => $hasValidScript,
  916. 'script_id' => $script_id,
  917. 'sequence' => $sequence,
  918. 'original_prompt' => getProp($data, 'prompt', ''),
  919. 'response_format' => $responseFormat,
  920. ]);
  921. }
  922. /**
  923. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  924. *
  925. * @param \Generator $generator
  926. * @param array $ctx
  927. * @return \Generator
  928. */
  929. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  930. {
  931. $fullContent = '';
  932. $usage = [];
  933. $finished = false;
  934. try {
  935. foreach ($generator as $chunk) {
  936. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  937. $fullContent .= (string)getProp($chunk, 'content', '');
  938. }
  939. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  940. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  941. $usage = getProp($chunk, 'usage', []);
  942. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  943. if (($ctx['response_format'] ?? 'text') === 'json') {
  944. $fullContent = $this->extractJsonContent($fullContent);
  945. }
  946. $finished = true;
  947. }
  948. yield $chunk;
  949. }
  950. if ($finished) {
  951. if (!empty($ctx['generate_task_id'])) {
  952. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  953. 'status' => 'success',
  954. 'result' => $fullContent,
  955. 'completed_at' => date('Y-m-d H:i:s'),
  956. 'updated_at' => date('Y-m-d H:i:s'),
  957. ]);
  958. }
  959. if ($ctx['has_valid_script'] && $fullContent !== '') {
  960. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  961. 'model' => $ctx['model'],
  962. 'script_id' => $ctx['script_id'],
  963. 'sequence' => $ctx['sequence'],
  964. 'source' => 'newGenerateText',
  965. ]);
  966. }
  967. if (!empty($ctx['script_id'])) {
  968. $now = now();
  969. DB::table('mp_script_records')->insert([
  970. [
  971. 'uid' => $ctx['uid'],
  972. 'script_id' => $ctx['script_id'],
  973. 'sequence' => $ctx['sequence'],
  974. 'role' => 'user',
  975. 'content' => $ctx['original_prompt'],
  976. 'created_at' => $now,
  977. 'updated_at' => $now,
  978. ],
  979. [
  980. 'uid' => $ctx['uid'],
  981. 'script_id' => $ctx['script_id'],
  982. 'sequence' => $ctx['sequence'],
  983. 'role' => 'assistant',
  984. 'content' => $fullContent,
  985. 'created_at' => $now,
  986. 'updated_at' => $now,
  987. ],
  988. ]);
  989. }
  990. }
  991. } catch (\Throwable $e) {
  992. if (!empty($ctx['generate_task_id'])) {
  993. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  994. 'status' => 'failed',
  995. 'error_message' => $e->getMessage(),
  996. 'completed_at' => date('Y-m-d H:i:s'),
  997. 'updated_at' => date('Y-m-d H:i:s'),
  998. ]);
  999. }
  1000. yield [
  1001. 'type' => 'error',
  1002. 'message' => $e->getMessage(),
  1003. ];
  1004. }
  1005. }
  1006. /**
  1007. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1008. *
  1009. * @param string $content
  1010. * @return string
  1011. */
  1012. private function extractJsonContent(string $content): string
  1013. {
  1014. $content = trim($content);
  1015. if ($content === '') {
  1016. return $content;
  1017. }
  1018. // 剥离 ```json ... ``` 代码块
  1019. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1020. $content = trim($m[1]);
  1021. }
  1022. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1023. $first = strpos($content, '{');
  1024. $last = strrpos($content, '}');
  1025. if ($first !== false && $last !== false && $last > $first) {
  1026. $content = substr($content, $first, $last - $first + 1);
  1027. }
  1028. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1029. json_decode($content, true);
  1030. if (json_last_error() !== JSON_ERROR_NONE) {
  1031. return trim($content);
  1032. }
  1033. return $content;
  1034. }
  1035. /**
  1036. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1037. *
  1038. * @param array $data 请求参数
  1039. * @return array 返回结果数组
  1040. */
  1041. public function newGenerateText($data) {
  1042. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1043. if ((int)getProp($data, 'stream', 0) === 1) {
  1044. return $this->newGenerateTextStream($data);
  1045. }
  1046. // 获取请求参数
  1047. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1048. $messages = getProp($data, 'messages', []);
  1049. $systemPrompt = getProp($data, 'system_prompt', '');
  1050. $prompt = getProp($data, 'prompt', '');
  1051. $images = getProp($data, 'images', []); // 支持多张图片
  1052. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1053. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1054. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1055. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1056. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1057. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1058. $generateTaskId = 0;
  1059. $uid = Site::getUid();
  1060. if ($script_id > 0) {
  1061. $existingTask = DB::table('mp_script_generate_tasks')
  1062. ->where('uid', $uid)
  1063. ->where('script_id', $script_id)
  1064. ->orderByDesc('id')
  1065. ->first();
  1066. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1067. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1068. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1069. }
  1070. }
  1071. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1072. $originalContent = '';
  1073. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1074. if ($script_id > 0) {
  1075. $script = DB::table('mp_scripts')
  1076. ->where('id', $script_id)
  1077. ->where('is_deleted', 0)
  1078. ->first();
  1079. if (!$script) {
  1080. Utils::throwError('20003:剧本不存在或已删除');
  1081. }
  1082. $originalContent = $script->content ?? '';
  1083. if (empty($originalContent)) {
  1084. Utils::throwError('20003:剧本内容为空');
  1085. }
  1086. $hasValidScript = true;
  1087. // 将剧本内容添加到提示词前面
  1088. if (!empty($originalContent)) {
  1089. if (!empty($prompt)) {
  1090. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1091. } else {
  1092. $prompt = "原文内容:\n" . $originalContent;
  1093. }
  1094. }
  1095. }
  1096. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1097. if ($templateId > 0) {
  1098. $template = DB::table('mp_prompt_templates')
  1099. ->where('id', $templateId)
  1100. ->where('is_deleted', 0)
  1101. ->first();
  1102. if (!$template) {
  1103. Utils::throwError('20003:模板不存在或已删除');
  1104. }
  1105. $templatePrompt = $template->template_prompt ?? '';
  1106. // 将模板提示词和用户输入的prompt组合
  1107. // 模板为准,用户输入作为补充要求
  1108. if (!empty($templatePrompt)) {
  1109. if (!empty($prompt)) {
  1110. $prompt = $templatePrompt . "\n\n" . $prompt;
  1111. } else {
  1112. $prompt = $templatePrompt;
  1113. }
  1114. }
  1115. }
  1116. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1117. if (empty($messages)) {
  1118. $messages = [];
  1119. // 添加系统提示词
  1120. if (!empty($systemPrompt)) {
  1121. $messages[] = [
  1122. 'role' => 'system',
  1123. 'content' => $systemPrompt
  1124. ];
  1125. }
  1126. // 构建用户消息内容(支持文本+图片)
  1127. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1128. $userMessage = [
  1129. 'role' => 'user',
  1130. 'content' => []
  1131. ];
  1132. // 添加文本内容
  1133. if (!empty($prompt)) {
  1134. $userMessage['content'][] = [
  1135. 'type' => 'text',
  1136. 'text' => $prompt
  1137. ];
  1138. }
  1139. // 处理上传的图片文件
  1140. if (!empty($images)) {
  1141. if (!is_array($images)) {
  1142. $images = [$images];
  1143. }
  1144. foreach ($images as $image) {
  1145. $imageBase64 = $this->processImageToBase64($image);
  1146. if ($imageBase64) {
  1147. $userMessage['content'][] = [
  1148. 'type' => 'image_url',
  1149. 'image_url' => [
  1150. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1151. ]
  1152. ];
  1153. }
  1154. }
  1155. }
  1156. // 处理图片URL
  1157. if (!empty($imageUrls)) {
  1158. if (!is_array($imageUrls)) {
  1159. $imageUrls = [$imageUrls];
  1160. }
  1161. foreach ($imageUrls as $url) {
  1162. if (!empty($url)) {
  1163. $userMessage['content'][] = [
  1164. 'type' => 'image_url',
  1165. 'image_url' => [
  1166. 'url' => $url
  1167. ]
  1168. ];
  1169. }
  1170. }
  1171. }
  1172. // 如果只有文本内容,简化为字符串格式
  1173. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1174. $userMessage['content'] = $userMessage['content'][0]['text'];
  1175. }
  1176. $messages[] = $userMessage;
  1177. }
  1178. }
  1179. // 验证messages不为空
  1180. if (empty($messages)) {
  1181. Utils::throwError('20003:请提供有效的对话内容');
  1182. }
  1183. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1184. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1185. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1186. if ($model === 'deepseek-chat') {
  1187. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1188. $model = 'deepseek-v4-flash';
  1189. $thinkingMode = 'disabled';
  1190. } elseif ($model === 'deepseek-reasoner') {
  1191. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1192. $model = 'deepseek-v4-flash';
  1193. $thinkingMode = 'enabled';
  1194. }
  1195. // 构建请求参数(非流式)
  1196. $post_data = [
  1197. 'model' => $model,
  1198. 'messages' => $messages,
  1199. 'temperature' => getProp($data, 'temperature', 1),
  1200. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1201. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1202. 'thinking' => ['type' => $thinkingMode],
  1203. 'stream' => false // 非流式输出
  1204. ];
  1205. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1206. // 添加可选参数
  1207. if (isset($data['top_p'])) {
  1208. $post_data['top_p'] = $data['top_p'];
  1209. }
  1210. // 新增: 根据response_format设置响应格式
  1211. if ($responseFormat === 'json') {
  1212. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1213. $hasJsonKeyword = false;
  1214. foreach ($post_data['messages'] as $message) {
  1215. if (isset($message['content'])) {
  1216. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1217. if (stripos($content, 'json') !== false) {
  1218. $hasJsonKeyword = true;
  1219. break;
  1220. }
  1221. }
  1222. }
  1223. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1224. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1225. if (!$hasJsonKeyword) {
  1226. $lastMessageIndex = count($post_data['messages']) - 1;
  1227. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1228. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1229. // 如果content是字符串,直接追加
  1230. if (is_string($lastContent)) {
  1231. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1232. }
  1233. // 如果content是数组(包含文本和图片),在文本部分追加
  1234. else if (is_array($lastContent)) {
  1235. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1236. if ($contentPart['type'] === 'text') {
  1237. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1238. break;
  1239. }
  1240. }
  1241. }
  1242. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1243. }
  1244. }
  1245. // 设置response_format参数(所有支持的模型)
  1246. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1247. // DeepSeek模型
  1248. $post_data['response_format'] = ['type' => 'json_object'];
  1249. } else if (in_array($model, $this->gpt_text_models)) {
  1250. // GPT模型
  1251. $post_data['response_format'] = ['type' => 'json_object'];
  1252. } else if (in_array($model, $this->valid_text_models)) {
  1253. // 火山引擎模型
  1254. $post_data['response_format'] = ['type' => 'json_object'];
  1255. }
  1256. }
  1257. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1258. if ($script_id > 0) {
  1259. $uid = Site::getUid();
  1260. // 创建新的生成任务
  1261. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1262. 'uid' => $uid,
  1263. 'script_id' => $script_id,
  1264. 'sequence' => $sequence,
  1265. 'status' => 'processing',
  1266. 'prompt' => getProp($data, 'prompt', ''),
  1267. 'started_at' => date('Y-m-d H:i:s'),
  1268. 'created_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s')
  1270. ]);
  1271. }
  1272. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1273. if ($hasValidScript) {
  1274. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1275. }
  1276. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  1277. try {
  1278. $aiResult = null;
  1279. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1280. // DeepSeek 官方模型使用现有的 chatOnly 方法
  1281. $result = $this->chatOnly($post_data);
  1282. // 记录实际使用的模型
  1283. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  1284. $aiResult = [
  1285. 'content' => $result['fullContent'],
  1286. 'reasoning_content' => $result['fullReasoningContent'],
  1287. 'usage' => $result['usage'],
  1288. 'model' => $model,
  1289. 'finish_reason' => 'stop'
  1290. ];
  1291. } else if (in_array($model, $this->gpt_text_models)) {
  1292. // GPT 模型使用现有的 gpt54ChatOnly 方法
  1293. $result = $this->gpt54ChatOnly($post_data);
  1294. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  1295. $aiResult = [
  1296. 'content' => $result['fullContent'],
  1297. 'reasoning_content' => '',
  1298. 'usage' => $result['usage'],
  1299. 'model' => $model,
  1300. 'finish_reason' => 'stop'
  1301. ];
  1302. } else if (in_array($model, $this->gemini_text_models)) {
  1303. // Gemini 模型使用 Gemini API(非流式)
  1304. $result = $this->geminiChatOnly($post_data, $model);
  1305. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  1306. $aiResult = [
  1307. 'content' => $result['fullContent'],
  1308. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  1309. 'usage' => $result['usage'],
  1310. 'model' => $model,
  1311. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1312. ];
  1313. } else if (in_array($model, $this->valid_text_models)) {
  1314. // 火山引擎支持的模型使用火山引擎 API(非流式)
  1315. $post_data['stream'] = false;
  1316. $result = $this->volcEngineChatCompletion($post_data);
  1317. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  1318. 'requested_model' => $model,
  1319. 'result_keys' => array_keys($result),
  1320. 'has_fullContent' => isset($result['fullContent']),
  1321. 'has_content' => isset($result['content'])
  1322. ]);
  1323. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  1324. $aiResult = [
  1325. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1326. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1327. 'usage' => $result['usage'] ?? [],
  1328. 'model' => $model,
  1329. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1330. ];
  1331. } else {
  1332. Utils::throwError('20003:不支持的模型: ' . $model);
  1333. }
  1334. } catch (\Exception $e) {
  1335. // 生成失败,更新任务状态
  1336. if ($generateTaskId) {
  1337. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1338. 'status' => 'failed',
  1339. 'error_message' => $e->getMessage(),
  1340. 'completed_at' => date('Y-m-d H:i:s'),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. }
  1344. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1345. }
  1346. // 生成成功,更新任务状态
  1347. if ($generateTaskId && $aiResult) {
  1348. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1349. 'status' => 'success',
  1350. 'result' => getProp($aiResult, 'content', ''),
  1351. 'completed_at' => date('Y-m-d H:i:s'),
  1352. 'updated_at' => date('Y-m-d H:i:s')
  1353. ]);
  1354. $aiResult['generate_task_id'] = $generateTaskId;
  1355. }
  1356. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1357. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1358. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1359. 'model' => $model,
  1360. 'script_id' => $script_id,
  1361. 'sequence' => $sequence,
  1362. 'source' => 'newGenerateText',
  1363. ]);
  1364. }
  1365. // 新增: 如果提供了script_id,保存对话记录
  1366. if ($script_id > 0 && $aiResult) {
  1367. try {
  1368. $uid = Site::getUid();
  1369. $now = now();
  1370. // 获取用户原始的prompt(不包含剧本内容)
  1371. $originalPrompt = getProp($data, 'prompt', '');
  1372. $recordsToInsert = [
  1373. [
  1374. 'uid' => $uid,
  1375. 'script_id' => $script_id,
  1376. 'sequence' => $sequence,
  1377. 'role' => 'user',
  1378. 'content' => $originalPrompt,
  1379. 'created_at' => $now,
  1380. 'updated_at' => $now,
  1381. ],
  1382. [
  1383. 'uid' => $uid,
  1384. 'script_id' => $script_id,
  1385. 'sequence' => $sequence,
  1386. 'role' => 'assistant',
  1387. 'content' => $aiResult['content'],
  1388. 'created_at' => $now,
  1389. 'updated_at' => $now,
  1390. ]
  1391. ];
  1392. DB::table('mp_script_records')->insert($recordsToInsert);
  1393. // 获取刚插入的记录ID(假设按插入顺序返回)
  1394. $insertedRecords = DB::table('mp_script_records')
  1395. ->where('uid', $uid)
  1396. ->where('script_id', $script_id)
  1397. ->where('sequence', $sequence)
  1398. ->orderBy('id', 'desc')
  1399. ->limit(2)
  1400. ->get()
  1401. ->map(function ($record) {
  1402. return [
  1403. 'rid' => $record->id,
  1404. 'script_id' => $record->script_id,
  1405. 'sequence' => $record->sequence,
  1406. 'role' => $record->role,
  1407. 'content' => $record->content,
  1408. 'created_at' => $record->created_at,
  1409. ];
  1410. })
  1411. ->reverse()
  1412. ->values()
  1413. ->toArray();
  1414. // 将记录信息添加到返回结果中
  1415. $aiResult['records'] = $insertedRecords;
  1416. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1417. } catch (\Exception $e) {
  1418. // 记录错误但不影响主流程
  1419. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1420. }
  1421. }
  1422. return $aiResult;
  1423. }
  1424. /**
  1425. * 通用 Gemini 文生文方法(支持流式和非流式)
  1426. *
  1427. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1428. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1429. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1430. * system_prompt 系统提示词(可选)
  1431. * prompt 用户提示词(可选)
  1432. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1433. * image_urls 图片/视频URL列表(可选,同上)
  1434. * temperature 温度(可选,默认 1)
  1435. * top_p 核采样(可选)
  1436. * max_tokens 最大输出 token(可选,默认 8192)
  1437. * response_format text/json(可选)
  1438. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1439. * thinking_budget 思考预算(可选,默认 20)
  1440. * stream 是否流式(可选,默认 false)
  1441. *
  1442. * @param array $data 请求参数
  1443. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1444. */
  1445. public function geminiGenerateText($data) {
  1446. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1447. $isStream = (bool)getProp($data, 'stream', false);
  1448. if (!in_array($model, $this->gemini_text_models)) {
  1449. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1450. }
  1451. $requestData = $this->buildGeminiRequestBody($data, $model);
  1452. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1453. if ($isStream) {
  1454. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1455. return $this->wrapGenerateTextTokenRecord(
  1456. $this->geminiStreamResponse($requestData, $model),
  1457. $this->getCurrentUid(),
  1458. $model,
  1459. 'geminiGenerateText'
  1460. );
  1461. }
  1462. // 非流式:成功后记录 token 使用明细(不扣积分)
  1463. $result = $this->geminiChatOnly($requestData, $model);
  1464. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1465. 'model' => $model,
  1466. 'source' => 'geminiGenerateText',
  1467. ], $model);
  1468. return $result;
  1469. }
  1470. /**
  1471. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1472. */
  1473. private function geminiMediaMaxBytes() {
  1474. return 14 * 1024 * 1024;
  1475. }
  1476. /**
  1477. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1478. */
  1479. private function buildGeminiRequestBody($data, $model) {
  1480. $messages = getProp($data, 'messages', []);
  1481. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1482. if (empty($messages)) {
  1483. $systemPrompt = getProp($data, 'system_prompt', '');
  1484. $prompt = getProp($data, 'prompt', '');
  1485. $images = getProp($data, 'images', []);
  1486. $imageUrls = getProp($data, 'image_urls', []);
  1487. $messages = [];
  1488. if (!empty($systemPrompt)) {
  1489. $messages[] = [
  1490. 'role' => 'system',
  1491. 'content' => $systemPrompt
  1492. ];
  1493. }
  1494. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1495. $userMessage = ['role' => 'user', 'content' => []];
  1496. if (!empty($prompt)) {
  1497. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1498. }
  1499. if (!empty($images)) {
  1500. if (!is_array($images)) {
  1501. $images = [$images];
  1502. }
  1503. foreach ($images as $image) {
  1504. $inlineData = $this->processMediaToInlineData($image);
  1505. if ($inlineData) {
  1506. $userMessage['content'][] = [
  1507. 'type' => 'image',
  1508. 'inline_data' => $inlineData
  1509. ];
  1510. }
  1511. }
  1512. }
  1513. if (!empty($imageUrls)) {
  1514. if (!is_array($imageUrls)) {
  1515. $imageUrls = [$imageUrls];
  1516. }
  1517. foreach ($imageUrls as $url) {
  1518. if (!empty($url)) {
  1519. $inlineData = $this->processMediaToInlineData($url);
  1520. if ($inlineData) {
  1521. $userMessage['content'][] = [
  1522. 'type' => 'image',
  1523. 'inline_data' => $inlineData
  1524. ];
  1525. }
  1526. }
  1527. }
  1528. }
  1529. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1530. $userMessage['content'] = $userMessage['content'][0]['text'];
  1531. }
  1532. $messages[] = $userMessage;
  1533. }
  1534. }
  1535. if (empty($messages)) {
  1536. Utils::throwError('20003:请提供有效的对话内容');
  1537. }
  1538. // 转换为 Gemini contents 格式
  1539. $systemInstruction = '';
  1540. $contents = [];
  1541. foreach ($messages as $message) {
  1542. $role = getProp($message, 'role', 'user');
  1543. $content = getProp($message, 'content', '');
  1544. if ($role === 'system') {
  1545. if (is_array($content)) {
  1546. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1547. } else {
  1548. $systemInstruction = (string)$content;
  1549. }
  1550. continue;
  1551. }
  1552. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1553. $parts = [];
  1554. if (is_array($content)) {
  1555. foreach ($content as $part) {
  1556. $partType = getProp($part, 'type', 'text');
  1557. if ($partType === 'text') {
  1558. $text = (string)getProp($part, 'text', '');
  1559. if ($text !== '') {
  1560. $parts[] = ['text' => $text];
  1561. }
  1562. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1563. if (in_array($partType, ['image_url', 'video_url'])) {
  1564. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1565. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1566. } elseif (isset($part['inline_data'])) {
  1567. // 已处理过的 inline_data 直接使用
  1568. $parts[] = ['inline_data' => $part['inline_data']];
  1569. continue;
  1570. } else {
  1571. $url = '';
  1572. }
  1573. $inlineData = $this->processMediaToInlineData($url);
  1574. if ($inlineData) {
  1575. $parts[] = ['inline_data' => $inlineData];
  1576. }
  1577. }
  1578. }
  1579. } else {
  1580. $text = (string)$content;
  1581. if ($text !== '') {
  1582. $parts[] = ['text' => $text];
  1583. }
  1584. }
  1585. if (!empty($parts)) {
  1586. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1587. }
  1588. }
  1589. if (empty($contents)) {
  1590. Utils::throwError('20003:请提供有效的对话内容');
  1591. }
  1592. // 构建生成配置
  1593. $generationConfig = [];
  1594. if (getProp($data, 'temperature', null) !== null) {
  1595. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1596. }
  1597. if (getProp($data, 'top_p', null) !== null) {
  1598. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1599. }
  1600. if (getProp($data, 'frequency_penalty', null) !== null) {
  1601. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1602. }
  1603. if (getProp($data, 'presence_penalty', null) !== null) {
  1604. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1605. }
  1606. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1607. if ($maxOutputTokens <= 0) {
  1608. $maxOutputTokens = 8192;
  1609. }
  1610. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1611. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1612. $maxOutputTokens = 32768;
  1613. }
  1614. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1615. // response_format 映射:text -> text/plain,json -> application/json
  1616. $responseFormat = getProp($data, 'response_format', 'text');
  1617. if (is_array($responseFormat)) {
  1618. $responseFormat = getProp($responseFormat, 'type', 'text');
  1619. }
  1620. if (in_array($responseFormat, ['json', 'json_object'])) {
  1621. $generationConfig['responseMimeType'] = 'application/json';
  1622. } else {
  1623. $generationConfig['responseMimeType'] = 'text/plain';
  1624. }
  1625. $requestData = [
  1626. 'contents' => $contents,
  1627. 'generationConfig' => $generationConfig,
  1628. ];
  1629. if ($systemInstruction !== '') {
  1630. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1631. }
  1632. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1633. $thinkingMode = getProp($data, 'thinking', null);
  1634. if (is_array($thinkingMode)) {
  1635. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1636. }
  1637. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1638. if ($thinkingMode === null) {
  1639. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1640. }
  1641. if ($thinkingMode === 'enabled') {
  1642. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1643. if ($thinkingBudget <= 0) {
  1644. $thinkingBudget = 20;
  1645. }
  1646. $requestData['generationConfig']['thinkingConfig'] = [
  1647. 'thinkingBudget' => $thinkingBudget
  1648. ];
  1649. } elseif ($defaultThinking) {
  1650. // 该模型仅支持思考模式,传 0 会返回 400
  1651. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1652. } else {
  1653. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1654. }
  1655. return $requestData;
  1656. }
  1657. /**
  1658. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1659. *
  1660. * 模型名 -> env 变量名映射:
  1661. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1662. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1663. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1664. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1665. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1666. */
  1667. private function getGeminiApiKey($model) {
  1668. $map = [
  1669. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1670. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1671. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1672. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1673. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1674. ];
  1675. if (isset($map[$model])) {
  1676. $key = env($map[$model]);
  1677. if (!empty($key)) {
  1678. return $key;
  1679. }
  1680. }
  1681. return env('GEMINI_API_KEY', '');
  1682. }
  1683. /**
  1684. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1685. */
  1686. private function geminiChatOnly($requestData, $model) {
  1687. $apiKey = $this->getGeminiApiKey($model);
  1688. if (empty($apiKey)) {
  1689. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1690. }
  1691. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1692. if (isset($requestData['messages'])) {
  1693. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1694. }
  1695. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1696. . '/models/' . $model . ':generateContent';
  1697. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1698. $headers = [
  1699. 'Authorization' => 'Bearer ' . $apiKey,
  1700. 'Content-Type' => 'application/json'
  1701. ];
  1702. $maxRetries = $this->gptRetryTimes();
  1703. $interval = $this->gptRetryInterval();
  1704. $attempt = 0;
  1705. while (true) {
  1706. try {
  1707. $response = $client->post($url, [
  1708. 'json' => $requestData,
  1709. 'headers' => $headers
  1710. ]);
  1711. $responseArr = json_decode($response->getBody()->getContents(), true);
  1712. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1713. $fullContent = $this->extractGeminiContent($responseArr);
  1714. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1715. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1716. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1717. ? $responseArr['candidates'][0]['finishReason']
  1718. : '';
  1719. return [
  1720. 'fullContent' => $fullContent,
  1721. 'fullReasoningContent' => $fullReasoningContent,
  1722. 'usage' => $usage,
  1723. 'finish_reason' => $finishReason
  1724. ];
  1725. } catch (\Exception $e) {
  1726. $retryable = true;
  1727. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1728. $status = $e->getResponse()->getStatusCode();
  1729. $retryable = $status >= 500 || $status == 429;
  1730. }
  1731. if (!$retryable || $attempt >= $maxRetries) {
  1732. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1733. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1734. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1735. }
  1736. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1737. 'retry' => $attempt + 1,
  1738. 'max_retries' => $maxRetries,
  1739. 'error' => $e->getMessage()
  1740. ]);
  1741. sleep($interval);
  1742. $attempt++;
  1743. }
  1744. }
  1745. }
  1746. /**
  1747. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1748. */
  1749. private function geminiStreamResponse($requestData, $model) {
  1750. $apiKey = $this->getGeminiApiKey($model);
  1751. if (empty($apiKey)) {
  1752. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1753. }
  1754. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1755. if (isset($requestData['messages'])) {
  1756. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1757. }
  1758. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1759. . '/models/' . $model . ':generateContent?alt=sse';
  1760. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1761. $headers = [
  1762. 'Authorization' => 'Bearer ' . $apiKey,
  1763. 'Content-Type' => 'application/json'
  1764. ];
  1765. try {
  1766. $response = $client->post($url, [
  1767. 'json' => $requestData,
  1768. 'headers' => $headers,
  1769. 'stream' => true
  1770. ]);
  1771. $body = $response->getBody();
  1772. $fullContent = '';
  1773. $fullReasoningContent = '';
  1774. $usage = [];
  1775. $buffer = '';
  1776. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1777. while (!$body->eof()) {
  1778. $chunk = $body->read(1024);
  1779. $buffer .= $chunk;
  1780. $lines = explode("\n", $buffer);
  1781. $buffer = array_pop($lines);
  1782. foreach ($lines as $line) {
  1783. $line = trim($line);
  1784. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1785. continue;
  1786. }
  1787. $data = substr($line, 6);
  1788. if ($data === '[DONE]') {
  1789. break 2;
  1790. }
  1791. try {
  1792. $json = json_decode($data, true);
  1793. if (json_last_error() !== JSON_ERROR_NONE) {
  1794. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1795. continue;
  1796. }
  1797. // 思考内容(thoughts)
  1798. $thoughts = $this->extractGeminiThoughts($json);
  1799. if ($thoughts !== '') {
  1800. $fullReasoningContent .= $thoughts;
  1801. yield [
  1802. 'type' => 'reasoning',
  1803. 'content' => $thoughts,
  1804. 'full_reasoning' => $fullReasoningContent
  1805. ];
  1806. }
  1807. // 回答内容
  1808. $partText = $this->extractGeminiContent($json);
  1809. if ($partText !== '') {
  1810. $fullContent .= $partText;
  1811. yield [
  1812. 'type' => 'content',
  1813. 'content' => $partText,
  1814. ];
  1815. }
  1816. // 使用统计
  1817. if (isset($json['usageMetadata'])) {
  1818. $usage = $json['usageMetadata'];
  1819. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1820. }
  1821. } catch (\Exception $e) {
  1822. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1823. continue;
  1824. }
  1825. }
  1826. }
  1827. dLog('deepseek')->info('Gemini流式读取完成', [
  1828. 'content_length' => strlen($fullContent),
  1829. 'reasoning_length' => strlen($fullReasoningContent)
  1830. ]);
  1831. yield [
  1832. 'type' => 'done',
  1833. 'full_content' => $fullContent,
  1834. 'full_reasoning' => $fullReasoningContent,
  1835. 'usage' => $usage
  1836. ];
  1837. } catch (\Exception $e) {
  1838. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1839. yield [
  1840. 'type' => 'error',
  1841. 'msg' => $e->getMessage(),
  1842. 'code' => $e->getCode()
  1843. ];
  1844. }
  1845. }
  1846. /**
  1847. * 从 Gemini 响应中提取回答文本
  1848. */
  1849. private function extractGeminiContent($responseArr) {
  1850. $text = '';
  1851. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1852. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1853. if (isset($part['text'])) {
  1854. $text .= $part['text'];
  1855. }
  1856. }
  1857. }
  1858. return $text;
  1859. }
  1860. /**
  1861. * 从 Gemini 响应中提取思考内容
  1862. */
  1863. private function extractGeminiReasoningContent($responseArr) {
  1864. $reasoning = '';
  1865. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1866. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1867. if (isset($thought['text'])) {
  1868. $reasoning .= $thought['text'];
  1869. }
  1870. }
  1871. }
  1872. return $reasoning;
  1873. }
  1874. /**
  1875. * 从 Gemini 流式响应中提取本次增量思考内容
  1876. */
  1877. private function extractGeminiThoughts($responseArr) {
  1878. $thoughts = '';
  1879. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1880. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1881. if (isset($thought['text'])) {
  1882. $thoughts .= $thought['text'];
  1883. }
  1884. }
  1885. }
  1886. return $thoughts;
  1887. }
  1888. /**
  1889. * 提取消息数组中的纯文本
  1890. */
  1891. private function extractGeminiTextFromParts($parts) {
  1892. $text = '';
  1893. if (is_array($parts)) {
  1894. foreach ($parts as $part) {
  1895. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1896. $text .= (string)getProp($part, 'text', '');
  1897. }
  1898. }
  1899. }
  1900. return $text;
  1901. }
  1902. /**
  1903. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1904. *
  1905. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1906. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1907. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1908. *
  1909. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1910. * @return array|null ['mime_type' => string, 'data' => string]
  1911. */
  1912. private function processMediaToInlineData($media) {
  1913. if (empty($media)) {
  1914. return null;
  1915. }
  1916. $localPath = null;
  1917. $isTempFile = false;
  1918. try {
  1919. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1920. if (is_string($media) && strpos($media, 'data:') === 0) {
  1921. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1922. return [
  1923. 'mime_type' => $matches[1],
  1924. 'data' => $matches[2]
  1925. ];
  1926. }
  1927. return null;
  1928. }
  1929. // 2. 获取本地文件路径
  1930. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1931. $localPath = $this->downloadMediaToTemp($media);
  1932. $isTempFile = true;
  1933. } elseif (is_string($media)) {
  1934. $localPath = $media;
  1935. } else {
  1936. // Laravel UploadedFile 对象
  1937. $localPath = $media->getRealPath();
  1938. }
  1939. if (!$localPath || !file_exists($localPath)) {
  1940. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1941. return null;
  1942. }
  1943. $fileSize = filesize($localPath);
  1944. $maxBytes = $this->geminiMediaMaxBytes();
  1945. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1946. $mimeType = $this->detectMediaMime($localPath);
  1947. $isVideo = strpos($mimeType, 'video/') === 0;
  1948. $needCompress = $fileSize > $maxBytes;
  1949. $duration = 0;
  1950. if ($isVideo) {
  1951. $duration = $this->getMediaDuration($localPath);
  1952. if ($duration > 300) {
  1953. $needCompress = true;
  1954. }
  1955. }
  1956. $finalPath = $localPath;
  1957. $compressedPath = null;
  1958. if ($needCompress && $this->ffmpegAvailable()) {
  1959. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1960. if ($compressed && file_exists($compressed)) {
  1961. $compressedPath = $compressed;
  1962. if (filesize($compressed) < $fileSize || $isVideo) {
  1963. $finalPath = $compressed;
  1964. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1965. } else {
  1966. @unlink($compressed);
  1967. $compressedPath = null;
  1968. }
  1969. }
  1970. }
  1971. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1972. $finalSize = filesize($finalPath);
  1973. if ($finalSize > $maxBytes) {
  1974. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1975. 'path' => $localPath,
  1976. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1977. 'limit_mb' => 14
  1978. ]);
  1979. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1980. }
  1981. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1982. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1983. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1984. }
  1985. $data = base64_encode(file_get_contents($finalPath));
  1986. return [
  1987. 'mime_type' => $mimeType,
  1988. 'data' => $data
  1989. ];
  1990. } catch (\App\Exceptions\ApiException $e) {
  1991. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1992. throw $e;
  1993. } catch (\Exception $e) {
  1994. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1995. return null;
  1996. } finally {
  1997. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1998. @unlink($compressedPath);
  1999. }
  2000. if ($isTempFile && $localPath && file_exists($localPath)) {
  2001. @unlink($localPath);
  2002. }
  2003. }
  2004. }
  2005. /**
  2006. * 下载远程多媒体到临时目录
  2007. *
  2008. * @return string|null 本地临时文件路径
  2009. */
  2010. private function downloadMediaToTemp($url) {
  2011. try {
  2012. $tempDir = storage_path('app/temp/gemini');
  2013. if (!is_dir($tempDir)) {
  2014. mkdir($tempDir, 0775, true);
  2015. }
  2016. $extension = 'tmp';
  2017. $pathInfo = parse_url($url, PHP_URL_PATH);
  2018. if ($pathInfo) {
  2019. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2020. if ($ext && strlen($ext) <= 10) {
  2021. $extension = strtolower($ext);
  2022. }
  2023. }
  2024. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2025. $client = new Client(['timeout' => 300, 'verify' => false]);
  2026. $response = $client->get($url, ['sink' => $tmpFile]);
  2027. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2028. @unlink($tmpFile);
  2029. return null;
  2030. }
  2031. return $tmpFile;
  2032. } catch (\Exception $e) {
  2033. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2034. return null;
  2035. }
  2036. }
  2037. /**
  2038. * 检测多媒体文件 MIME 类型
  2039. */
  2040. private function detectMediaMime($filePath) {
  2041. $imageInfo = @getimagesize($filePath);
  2042. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2043. return $imageInfo['mime'];
  2044. }
  2045. // 视频按扩展名粗略判断
  2046. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2047. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2048. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2049. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2050. if (isset($videoExts[$ext])) {
  2051. return $videoExts[$ext];
  2052. }
  2053. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2054. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2055. if (isset($imageExts[$ext])) {
  2056. return $imageExts[$ext];
  2057. }
  2058. return 'application/octet-stream';
  2059. }
  2060. /**
  2061. * 获取多媒体时长(秒),非视频或失败返回 0
  2062. */
  2063. private function getMediaDuration($filePath) {
  2064. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2065. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2066. $output = trim((string)shell_exec($cmd));
  2067. $duration = (float)$output;
  2068. return $duration > 0 ? $duration : 0;
  2069. }
  2070. /**
  2071. * 检查 ffmpeg 是否可用
  2072. */
  2073. private function ffmpegAvailable() {
  2074. static $available = null;
  2075. if ($available !== null) {
  2076. return $available;
  2077. }
  2078. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2079. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2080. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2081. $available = false;
  2082. return $available;
  2083. }
  2084. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2085. $output = shell_exec($cmd);
  2086. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2087. return $available;
  2088. }
  2089. /**
  2090. * 使用 ffmpeg 压缩多媒体文件
  2091. *
  2092. * @param string $inputFile 输入文件路径
  2093. * @param bool $isVideo 是否为视频
  2094. * @param float $duration 视频时长(秒),非视频传 0
  2095. * @return string|null 压缩后的文件路径,失败返回 null
  2096. */
  2097. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2098. try {
  2099. $tempDir = storage_path('app/temp/gemini');
  2100. if (!is_dir($tempDir)) {
  2101. mkdir($tempDir, 0775, true);
  2102. }
  2103. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2104. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2105. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2106. if ($isVideo) {
  2107. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2108. $speedFactor = 1.0;
  2109. if ($duration > 300) {
  2110. $speedFactor = $duration / 300;
  2111. }
  2112. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2113. $finalDuration = $duration / max(1.0, $speedFactor);
  2114. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2115. $targetBitrate = max(300, min(6000, $targetBitrate));
  2116. $filters = [];
  2117. $filters[] = 'scale=min(1280,iw):-2';
  2118. $filters[] = 'fps=24';
  2119. if ($speedFactor > 1.0) {
  2120. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2121. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2122. $fullCount = (int)ceil($speedFactor / 2.0);
  2123. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2124. if ($lastTempo < 0.5) {
  2125. $fullCount++;
  2126. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2127. }
  2128. for ($i = 0; $i < $fullCount; $i++) {
  2129. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2130. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2131. }
  2132. }
  2133. $filterStr = implode(',', $filters);
  2134. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2135. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2136. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2137. } else {
  2138. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2139. $imageInfo = @getimagesize($inputFile);
  2140. $scaleW = 2048;
  2141. $scaleH = 2048;
  2142. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2143. if ($imageInfo[0] >= $imageInfo[1]) {
  2144. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2145. $scaleW = 2048;
  2146. } else {
  2147. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2148. $scaleH = 2048;
  2149. }
  2150. }
  2151. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2152. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2153. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2154. }
  2155. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2156. $output = shell_exec($cmd);
  2157. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2158. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2159. 'input' => $inputFile,
  2160. 'output' => $output
  2161. ]);
  2162. @unlink($outputFile);
  2163. return null;
  2164. }
  2165. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2166. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2167. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2168. ]);
  2169. return $outputFile;
  2170. } catch (\Exception $e) {
  2171. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2172. return null;
  2173. }
  2174. }
  2175. /**
  2176. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2177. *
  2178. * @param array $data
  2179. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2180. */
  2181. public function getScriptGenerateTasks($data) {
  2182. $uid = Site::getUid();
  2183. return DB::table('mp_script_generate_tasks as t')
  2184. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2185. ->where('t.uid', $uid)
  2186. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2187. ->orderByDesc('t.id')
  2188. ->paginate(15);
  2189. }
  2190. public function saveScriptChatHistory($data) {
  2191. $uid = Site::getUid();
  2192. $rid = getProp($data, 'rid');
  2193. $script_id = getProp($data, 'script_id');
  2194. $sequence = getProp($data, 'sequence', 0);
  2195. $content = getProp($data, 'content');
  2196. if (!$rid) {
  2197. Utils::throwError('20003:请选择对话记录ID');
  2198. }
  2199. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2200. if (!$record) {
  2201. Utils::throwError('20003:对话记录不存在');
  2202. }
  2203. if (!$script_id) {
  2204. Utils::throwError('20003:请选择剧本');
  2205. }
  2206. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2207. if (!$script) {
  2208. Utils::throwError('20003:剧本不存在');
  2209. }
  2210. // 批量插入数据
  2211. return DB::table('mp_script_records')->where('id', $rid)->update([
  2212. 'content' => $content,
  2213. 'updated_at' => date('Y-m-d H:i:s')
  2214. ]);
  2215. }
  2216. /**
  2217. * 获取剧本的历史对话记录
  2218. *
  2219. * @param array $data 请求参数
  2220. * @return array 返回历史记录数组
  2221. */
  2222. public function getScriptChatHistory($data) {
  2223. $uid = Site::getUid();
  2224. $script_id = getProp($data, 'script_id');
  2225. $rid = getProp($data, 'rid');
  2226. $sequence = getProp($data, 'sequence', null);
  2227. if (!$script_id) {
  2228. Utils::throwError('20003:请提供剧本ID');
  2229. }
  2230. // 验证剧本是否存在
  2231. $script = DB::table('mp_scripts')
  2232. ->where('id', $script_id)
  2233. ->where('is_deleted', 0)
  2234. ->first();
  2235. if (!$script) {
  2236. Utils::throwError('20003:剧本不存在');
  2237. }
  2238. // 构建查询
  2239. $query = DB::table('mp_script_records')
  2240. ->where('script_id', $script_id);
  2241. // ->where('uid', $uid);
  2242. // 如果提供了 sequence,则过滤指定剧集
  2243. if ($sequence !== null) {
  2244. $query->where('sequence', $sequence);
  2245. }
  2246. // 记录ID筛选
  2247. if ($rid) {
  2248. $query->where('id', $rid);
  2249. }
  2250. // 查询记录并按 id 正序排序
  2251. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2252. ->orderBy('created_at', 'asc')
  2253. ->orderBy('id', 'asc')
  2254. ->get()
  2255. ->map(function ($record) {
  2256. return [
  2257. 'rid' => $record->id,
  2258. 'script_id' => $record->script_id,
  2259. 'sequence' => $record->sequence,
  2260. 'role' => $record->role,
  2261. 'content' => $record->content,
  2262. 'products' => $record->products ? json_decode($record->products) : [],
  2263. 'created_at' => $record->created_at,
  2264. ];
  2265. })
  2266. ->toArray();
  2267. return $records;
  2268. }
  2269. /**
  2270. * 处理图片转换为base64
  2271. *
  2272. * @param mixed $image 图片文件对象或文件路径
  2273. * @return string|null base64编码的图片数据
  2274. */
  2275. private function processImageToBase64($image) {
  2276. try {
  2277. // 获取文件路径
  2278. if (is_string($image)) {
  2279. $filePath = $image;
  2280. } else {
  2281. // Laravel UploadedFile 对象
  2282. $filePath = $image->getRealPath();
  2283. }
  2284. if (!file_exists($filePath)) {
  2285. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2286. return null;
  2287. }
  2288. // 验证是否为图片文件
  2289. $imageInfo = @getimagesize($filePath);
  2290. if ($imageInfo === false) {
  2291. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2292. return null;
  2293. }
  2294. // 读取图片并转换为base64
  2295. $imageData = file_get_contents($filePath);
  2296. $base64Image = base64_encode($imageData);
  2297. dLog('deepseek')->info('图片转换成功', [
  2298. 'size' => strlen($imageData),
  2299. 'type' => $imageInfo['mime']
  2300. ]);
  2301. return $base64Image;
  2302. } catch (\Exception $e) {
  2303. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2304. return null;
  2305. }
  2306. }
  2307. private function getArtStylePromptMappings($art_style='')
  2308. {
  2309. // 优先从画风表读取(入库后以表数据为准,保持原返回结构:['画风名' => ['aliases' => [...], 'prompt' => "..."]]
  2310. $dbRows = DB::table('mp_art_styles')
  2311. ->where('is_deleted', 0)
  2312. ->orderBy('id')
  2313. ->get(['art_style', 'aliases', 'prompt']);
  2314. if ($dbRows->isNotEmpty()) {
  2315. $arr = [];
  2316. foreach ($dbRows as $row) {
  2317. $arr[$row->art_style] = [
  2318. 'aliases' => is_string($row->aliases) ? json_decode($row->aliases, true) : [],
  2319. 'prompt' => (string)$row->prompt,
  2320. ];
  2321. }
  2322. if ($art_style) {
  2323. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2324. }
  2325. return $arr;
  2326. }
  2327. $arr = [
  2328. '唯美真人风格' => [
  2329. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2330. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2331. ],
  2332. '真人古风风格' => [
  2333. 'aliases' => ['真人古风风格', '真人古风'],
  2334. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2335. ],
  2336. '日系动漫风格' => [
  2337. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2338. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2339. ],
  2340. '国漫风格' => [
  2341. 'aliases' => ['国漫风格', '国漫'],
  2342. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2343. ],
  2344. 'Q版卡通风格' => [
  2345. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2346. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2347. ],
  2348. '简约扁平风格' => [
  2349. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2350. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2351. ],
  2352. '武侠风格' => [
  2353. 'aliases' => ['武侠风格', '武侠'],
  2354. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2355. ],
  2356. '古风仙侠风格' => [
  2357. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2358. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2359. ],
  2360. '新中式水墨风格' => [
  2361. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2362. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2363. ],
  2364. '写实插画风格' => [
  2365. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2366. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2367. ],
  2368. '3D卡通风格' => [
  2369. 'aliases' => ['3D卡通风格', '3D卡通'],
  2370. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2371. ],
  2372. '条漫风格' => [
  2373. 'aliases' => ['条漫风格', '条漫'],
  2374. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2375. ],
  2376. '赛博朋克风格' => [
  2377. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2378. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2379. ],
  2380. '暗黑悬疑风格' => [
  2381. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2382. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2383. ],
  2384. '治愈清新风格' => [
  2385. 'aliases' => ['治愈清新风格', '治愈清新'],
  2386. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2387. ],
  2388. '3D真人风格' => [
  2389. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2390. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2391. ],
  2392. ];
  2393. if($art_style) {
  2394. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2395. }
  2396. return $arr;
  2397. $arr = [
  2398. '唯美真人风格' => [
  2399. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2400. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2401. 2. 色彩色调
  2402. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2403. 3. 画质精度
  2404. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2405. 4. 画面观感
  2406. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2407. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2408. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2409. ],
  2410. '真人古风风格' => [
  2411. 'aliases' => ['真人古风风格', '真人古风'],
  2412. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2413. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2414. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2415. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2416. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2417. ],
  2418. '日系动漫风格' => [
  2419. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2420. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2421. 正向提示词(中文)
  2422. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2423. 必须遵守规则
  2424. • 全程保持日系动漫风格,不混入其他画风
  2425. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2426. • 画面适配所选画面比例,构图居中,主体突出
  2427. • 线条干净、色彩统一,不杂乱、不突兀
  2428. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2429. ],
  2430. '国漫风格' => [
  2431. 'aliases' => ['国漫风格', '国漫'],
  2432. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2433. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2434. 必须遵守规则
  2435. • 严格保持国漫画风,不串风格、不混画风
  2436. • 角色形象统一,不随意改变五官、身材、服饰
  2437. • 画面构图稳定,适合漫剧叙事展示
  2438. • 色调统一,不出现脏色、杂色
  2439. 禁止/避免词汇
  2440. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2441. ],
  2442. 'Q版卡通风格' => [
  2443. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2444. 'prompt' => "风格说明
  2445. 头大身小,造型可爱圆润,简约干净
  2446. 正向提示词(中文)
  2447. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2448. 必须遵守规则
  2449. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2450. • 角色造型统一,表情可爱,不诡异
  2451. • 画面简洁清爽,无多余复杂元素
  2452. • 色彩明亮柔和,不刺眼
  2453. 禁止/避免词汇
  2454. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2455. ],
  2456. '简约扁平风格' => [
  2457. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2458. 'prompt' => "风格说明
  2459. 色块简洁、无复杂渐变,现代极简风
  2460. 正向提示词(中文)
  2461. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2462. 必须遵守规则
  2463. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2464. • 构图简洁,主体突出,无多余装饰
  2465. • 色彩统一、干净,不杂乱
  2466. 禁止/避免词汇
  2467. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2468. ],
  2469. '武侠风格' => [
  2470. 'aliases' => ['武侠风格', '武侠'],
  2471. 'prompt' => "风格说明
  2472. 江湖气息,线条硬朗,动作感强
  2473. 正向提示词(中文)
  2474. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2475. 必须遵守规则
  2476. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2477. • 角色形象、服饰、身材比例统一
  2478. • 画面动作自然,不扭曲、不畸形
  2479. 禁止/避免词汇
  2480. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2481. ],
  2482. '古风仙侠风格' => [
  2483. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2484. 'prompt' => "风格说明
  2485. 飘逸汉服、云雾仙气、唯美空灵
  2486. 正向提示词(中文)
  2487. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2488. 必须遵守规则
  2489. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2490. • 角色服饰、发型、形象前后一致
  2491. • 场景仙气飘逸,色调清雅统一
  2492. • 画面唯美柔和,不阴暗、不诡异
  2493. 禁止/避免词汇
  2494. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2495. ],
  2496. '新中式水墨风格' => [
  2497. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2498. 'prompt' => "风格说明
  2499. 淡墨渲染,毛笔笔触,留白意境
  2500. 正向提示词(中文)
  2501. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2502. 必须遵守规则
  2503. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2504. • 色调淡雅统一,不浓艳杂乱
  2505. • 画面干净有意境,不堆砌元素
  2506. 禁止/避免词汇
  2507. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2508. ],
  2509. '写实插画风格' => [
  2510. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2511. 'prompt' => "风格说明
  2512. 接近真人比例,光影真实,质感细腻
  2513. 正向提示词(中文)
  2514. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2515. 必须遵守规则
  2516. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2517. • 角色五官、身材、服饰高度统一
  2518. • 画面清晰、光影自然、不扭曲
  2519. 禁止/避免词汇
  2520. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2521. ],
  2522. '3D卡通风格' => [
  2523. 'aliases' => ['3D卡通风格', '3D卡通'],
  2524. 'prompt' => "风格说明
  2525. 3D建模质感,柔和渲染,圆润可爱
  2526. 正向提示词(中文)
  2527. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2528. 必须遵守规则
  2529. • 保持3D卡通统一质感,不出现2D杂乱线条
  2530. • 角色模型、比例、形象前后一致
  2531. • 画面干净,不模糊、不穿模
  2532. 禁止/避免词汇
  2533. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2534. ],
  2535. '条漫风格' => [
  2536. 'aliases' => ['条漫风格', '条漫'],
  2537. 'prompt' => "风格说明
  2538. 纵向分镜,上下滑动阅读,轻量化
  2539. 正向提示词(中文)
  2540. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2541. 必须遵守规则
  2542. • 保持条漫纵向阅读逻辑,构图简洁
  2543. • 画风统一,不混写实、3D、水墨
  2544. • 画面干净,不杂乱
  2545. 禁止/避免词汇
  2546. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2547. ],
  2548. '赛博朋克风格' => [
  2549. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2550. 'prompt' => "风格说明
  2551. 霓虹灯光、未来都市、暗色调、科技机械
  2552. 正向提示词(中文)
  2553. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2554. 必须遵守规则
  2555. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2556. • 色调以暗调+霓虹为主,色彩统一
  2557. • 画面科技感强,不杂乱
  2558. 禁止/避免词汇
  2559. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2560. ],
  2561. '暗黑悬疑风格' => [
  2562. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2563. 'prompt' => "风格说明
  2564. 低饱和、冷色调、阴影重、神秘压抑
  2565. 正向提示词(中文)
  2566. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2567. 必须遵守规则
  2568. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2569. • 画面氛围压抑神秘,但不低俗、不血腥
  2570. • 角色形象统一,不崩坏
  2571. 禁止/避免词汇
  2572. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2573. ],
  2574. '治愈清新风格' => [
  2575. 'aliases' => ['治愈清新风格', '治愈清新'],
  2576. 'prompt' => "风格说明
  2577. 马卡龙色系、柔光、温暖干净
  2578. 正向提示词(中文)
  2579. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2580. 必须遵守规则
  2581. • 保持治愈清新统一色调,不阴暗、不诡异
  2582. • 画面柔和干净,无杂乱元素
  2583. • 角色形象柔和可爱,不狰狞
  2584. 禁止/避免词汇
  2585. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2586. ],
  2587. ];
  2588. return $arr;
  2589. }
  2590. public function getArtStylePromptByInput($inputArtStyle): string
  2591. {
  2592. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2593. if ($normalizedInput === '') {
  2594. return '';
  2595. }
  2596. return $this->getArtStylePromptMappings($normalizedInput);
  2597. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2598. // foreach ($mapping['aliases'] as $alias) {
  2599. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2600. // if ($normalizedAlias === '') {
  2601. // continue;
  2602. // }
  2603. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2604. // return $mapping['prompt'];
  2605. // }
  2606. // }
  2607. // }
  2608. return '';
  2609. }
  2610. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2611. // 优先从画风表读取;character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2612. $row = DB::table('mp_art_styles')
  2613. ->where('art_style', $inputArtStyle)
  2614. ->where('is_deleted', 0)
  2615. ->first(['character_prefix', 'scene_prefix', 'prompt']);
  2616. if ($row) {
  2617. $prompt = (string)$row->prompt;
  2618. $result = [
  2619. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2620. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2621. ];
  2622. // 前缀与通用提示词均不存在时返回空数组
  2623. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2624. return [];
  2625. }
  2626. return $result;
  2627. }
  2628. $stylePrefixes = [
  2629. '唯美真人风格' => [
  2630. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2631. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2632. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2633. ],
  2634. '真人古风风格' => [
  2635. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2636. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2637. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2638. ],
  2639. '日系动漫风格' => [
  2640. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2641. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2642. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2643. ],
  2644. '国漫风格' => [
  2645. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2646. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2647. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2648. ],
  2649. 'Q版卡通风格' => [
  2650. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2651. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2652. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2653. ],
  2654. '简约扁平风格' => [
  2655. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2656. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2657. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2658. ],
  2659. '武侠风格' => [
  2660. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2661. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2662. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2663. ],
  2664. '古风仙侠风格' => [
  2665. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2666. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2667. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2668. ],
  2669. '新中式水墨风格' => [
  2670. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2671. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2672. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2673. ],
  2674. '写实插画风格' => [
  2675. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2676. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2677. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2678. ],
  2679. '3D卡通风格' => [
  2680. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2681. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2682. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2683. ],
  2684. '条漫风格' => [
  2685. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2686. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2687. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2688. ],
  2689. '赛博朋克风格' => [
  2690. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2691. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2692. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2693. ],
  2694. '暗黑悬疑风格' => [
  2695. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2696. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2697. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2698. ],
  2699. '治愈清新风格' => [
  2700. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2701. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2702. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2703. ]
  2704. ];
  2705. if (isset($stylePrefixes[$inputArtStyle])) {
  2706. $item = $stylePrefixes[$inputArtStyle];
  2707. $prompt = (string)($item['prompt'] ?? '');
  2708. // 前缀缺失时用通用 prompt 兜底
  2709. $result = [
  2710. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2711. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2712. ];
  2713. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2714. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2715. return [];
  2716. }
  2717. return $result;
  2718. }
  2719. return [];
  2720. }
  2721. private function normalizeArtStyleInput($value): string
  2722. {
  2723. $value = trim((string)$value);
  2724. if ($value === '') {
  2725. return '';
  2726. }
  2727. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2728. return mb_strtolower($value, 'UTF-8');
  2729. }
  2730. private function replaceArtStyleSection(string $content, string $artStyle): string
  2731. {
  2732. if ($content === '' || $artStyle === '') {
  2733. return $content;
  2734. }
  2735. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2736. if (!preg_match($pattern, $content)) {
  2737. return $content;
  2738. }
  2739. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2740. }
  2741. /**
  2742. * DeepSeek流式输出处理方法
  2743. *
  2744. * @param array $post_data DeepSeek API请求参数
  2745. * @return \Generator 返回生成器,用于流式输出
  2746. */
  2747. private function unwrapJsonWrappedContent($content) {
  2748. $trimmed = ltrim((string)$content);
  2749. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2750. return $content;
  2751. }
  2752. $decoded = json_decode($trimmed, true);
  2753. if (!is_array($decoded)) {
  2754. return $content;
  2755. }
  2756. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2757. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2758. return $decoded[$key];
  2759. }
  2760. }
  2761. return $content;
  2762. }
  2763. private function deepSeekStreamResponse($post_data) {
  2764. // 设置最大输出tokens
  2765. $post_data['max_tokens'] = 300000;
  2766. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2767. $post_data['stream_options'] = ['include_usage' => true];
  2768. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2769. $response = $client->post($this->url, [
  2770. 'json' => $post_data,
  2771. 'headers' => $this->headers,
  2772. 'stream' => true // 启用流式响应
  2773. ]);
  2774. $body = $response->getBody();
  2775. $fullContent = '';
  2776. $fullReasoningContent = '';
  2777. $usage = [];
  2778. $buffer = '';
  2779. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2780. // 逐行读取流式响应
  2781. while (!$body->eof()) {
  2782. $chunk = $body->read(1024); // 每次读取 1KB
  2783. $buffer .= $chunk;
  2784. // 按行分割
  2785. $lines = explode("\n", $buffer);
  2786. // 保留最后一个不完整的行
  2787. $buffer = array_pop($lines);
  2788. foreach ($lines as $line) {
  2789. $line = trim($line);
  2790. // 跳过空行
  2791. if (empty($line)) {
  2792. continue;
  2793. }
  2794. // 检查是否是 SSE 数据行
  2795. if (strpos($line, 'data: ') !== 0) {
  2796. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2797. continue;
  2798. }
  2799. $data = substr($line, 6); // 移除 "data: " 前缀
  2800. if ($data === '[DONE]') {
  2801. dLog('deepseek')->info('收到结束标记');
  2802. break 2; // 跳出两层循环
  2803. }
  2804. try {
  2805. $json = json_decode($data, true);
  2806. if (json_last_error() !== JSON_ERROR_NONE) {
  2807. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2808. continue;
  2809. }
  2810. if (isset($json['choices'][0]['delta'])) {
  2811. $delta = $json['choices'][0]['delta'];
  2812. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2813. if (isset($delta['reasoning_content'])) {
  2814. $fullReasoningContent .= $delta['reasoning_content'];
  2815. yield [
  2816. 'type' => 'reasoning',
  2817. 'content' => $delta['reasoning_content'],
  2818. 'full_reasoning' => $fullReasoningContent
  2819. ];
  2820. }
  2821. // 处理最终回答内容
  2822. if (isset($delta['content'])) {
  2823. $fullContent .= $delta['content'];
  2824. yield [
  2825. 'type' => 'content',
  2826. 'content' => $delta['content'],
  2827. ];
  2828. }
  2829. }
  2830. // 获取使用统计信息
  2831. if (isset($json['usage'])) {
  2832. $usage = $json['usage'];
  2833. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2834. }
  2835. } catch (\Exception $e) {
  2836. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2837. continue;
  2838. }
  2839. }
  2840. }
  2841. dLog('deepseek')->info('流式读取完成', [
  2842. 'content_length' => strlen($fullContent),
  2843. 'reasoning_length' => strlen($fullReasoningContent)
  2844. ]);
  2845. yield [
  2846. 'type' => 'done',
  2847. 'full_content' => $fullContent,
  2848. 'full_reasoning' => $fullReasoningContent,
  2849. 'usage' => $usage
  2850. ];
  2851. }
  2852. /**
  2853. * GPT 重试次数(env 可配置,默认 5 次)
  2854. */
  2855. private function gptRetryTimes()
  2856. {
  2857. return (int)env('GPT_RETRY_TIMES', 5);
  2858. }
  2859. /**
  2860. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2861. */
  2862. private function gptRetryInterval()
  2863. {
  2864. return (int)env('GPT_RETRY_INTERVAL', 10);
  2865. }
  2866. /**
  2867. * 判断 GPT 请求异常是否可重试
  2868. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2869. */
  2870. private function isGptRetryableException(\Exception $e)
  2871. {
  2872. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2873. return false;
  2874. }
  2875. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2876. $status = $e->getResponse()->getStatusCode();
  2877. return $status >= 500 || $status == 429;
  2878. }
  2879. return true;
  2880. }
  2881. /**
  2882. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2883. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2884. */
  2885. private function checkGptServiceAvailable($apiKey = null)
  2886. {
  2887. if ($apiKey === null) {
  2888. $apiKey = env('GPT_54_API_KEY');
  2889. }
  2890. if (empty($apiKey)) {
  2891. return false;
  2892. }
  2893. try {
  2894. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2895. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2896. 'headers' => [
  2897. 'Authorization' => 'Bearer ' . $apiKey,
  2898. 'Content-Type' => 'application/json'
  2899. ]
  2900. ]);
  2901. $status = $response->getStatusCode();
  2902. return $status < 500 && $status != 429;
  2903. } catch (\Exception $e) {
  2904. return false;
  2905. }
  2906. }
  2907. /**
  2908. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2909. * 全部失败抛出友好错误
  2910. */
  2911. private function ensureGptServiceAvailable($apiKey = null)
  2912. {
  2913. $maxRetries = $this->gptRetryTimes();
  2914. $interval = $this->gptRetryInterval();
  2915. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2916. if ($this->checkGptServiceAvailable($apiKey)) {
  2917. return;
  2918. }
  2919. if ($attempt < $maxRetries) {
  2920. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2921. 'retry' => $attempt + 1,
  2922. 'max_retries' => $maxRetries
  2923. ]);
  2924. sleep($interval);
  2925. }
  2926. }
  2927. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2928. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2929. 'max_retries' => $maxRetries,
  2930. 'interval' => $interval
  2931. ]);
  2932. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2933. }
  2934. /**
  2935. * GPT 流式输出处理方法
  2936. *
  2937. * @param array $post_data GPT API请求参数
  2938. * @return \Generator 返回生成器,用于流式输出
  2939. */
  2940. private function gpt54StreamResponse($post_data) {
  2941. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  2942. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  2943. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  2944. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  2945. $usedLunaFallback = false;
  2946. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  2947. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  2948. if (empty($apiKey)) {
  2949. Utils::throwError('20003:GPT API Key未配置');
  2950. }
  2951. // 先探活,服务不可用时自动重试
  2952. $this->ensureGptServiceAvailable($apiKey);
  2953. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  2954. // 移除 thinking 参数,GPT-5.4 不支持
  2955. if (isset($post_data['thinking'])) {
  2956. unset($post_data['thinking']);
  2957. }
  2958. if (isset($post_data['reasoning_effort'])) {
  2959. unset($post_data['reasoning_effort']);
  2960. }
  2961. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  2962. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  2963. $post_data['max_completion_tokens'] = 100000;
  2964. $post_data['max_tokens'] = 100000;
  2965. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2966. $post_data['stream_options'] = ['include_usage' => true];
  2967. $maxRetries = $this->gptRetryTimes();
  2968. $interval = $this->gptRetryInterval();
  2969. $attempt = 0;
  2970. while (true) {
  2971. $fullContent = '';
  2972. $usage = [];
  2973. $buffer = '';
  2974. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  2975. $isJsonRequest = isset($post_data['response_format'])
  2976. && is_array($post_data['response_format'])
  2977. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  2978. $suspectJsonWrap = false;
  2979. $pendingContent = '';
  2980. $requestStartedAt = microtime(true);
  2981. $headers = [
  2982. 'Authorization' => 'Bearer ' . $apiKey,
  2983. 'Content-Type' => 'application/json',
  2984. 'Accept' => 'text/event-stream'
  2985. ];
  2986. try {
  2987. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2988. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2989. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2990. 'json' => $post_data,
  2991. 'headers' => $headers,
  2992. 'stream' => true // 启用流式响应
  2993. ]);
  2994. $body = $response->getBody();
  2995. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2996. // 逐行读取流式响应
  2997. while (!$body->eof()) {
  2998. // 长时间没有任何内容返回时,切换备用 Key 重试
  2999. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3000. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3001. }
  3002. $chunk = $body->read(1024); // 每次读取 1KB
  3003. $buffer .= $chunk;
  3004. // 按行分割
  3005. $lines = explode("\n", $buffer);
  3006. // 保留最后一个不完整的行
  3007. $buffer = array_pop($lines);
  3008. foreach ($lines as $line) {
  3009. $line = trim($line);
  3010. // 跳过空行
  3011. if (empty($line)) {
  3012. continue;
  3013. }
  3014. // 检查是否是 SSE 数据行
  3015. if (strpos($line, 'data: ') !== 0) {
  3016. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3017. continue;
  3018. }
  3019. $data = substr($line, 6); // 移除 "data: " 前缀
  3020. if ($data === '[DONE]') {
  3021. dLog('deepseek')->info('收到结束标记');
  3022. break 2; // 跳出 foreach 和流读取循环
  3023. }
  3024. try {
  3025. $json = json_decode($data, true);
  3026. if (json_last_error() !== JSON_ERROR_NONE) {
  3027. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3028. continue;
  3029. }
  3030. if (isset($json['choices'][0]['delta'])) {
  3031. $delta = $json['choices'][0]['delta'];
  3032. // 处理回答内容
  3033. if (isset($delta['content'])) {
  3034. $fullContent .= $delta['content'];
  3035. $trimmed = ltrim($fullContent);
  3036. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3037. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3038. $suspectJsonWrap = true;
  3039. }
  3040. if (!$suspectJsonWrap) {
  3041. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3042. $chunkSize = 256;
  3043. $chunkLength = mb_strlen($delta['content']);
  3044. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3045. yield [
  3046. 'type' => 'content',
  3047. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3048. ];
  3049. }
  3050. } else {
  3051. $pendingContent .= $delta['content'];
  3052. }
  3053. }
  3054. }
  3055. // 获取使用统计信息
  3056. if (isset($json['usage'])) {
  3057. $usage = $json['usage'];
  3058. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3059. }
  3060. } catch (\Exception $e) {
  3061. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3062. continue;
  3063. }
  3064. }
  3065. }
  3066. dLog('deepseek')->info('流式读取完成', [
  3067. 'content_length' => strlen($fullContent)
  3068. ]);
  3069. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3070. if ($suspectJsonWrap) {
  3071. $decoded = json_decode(trim($fullContent), true);
  3072. $unwrapped = null;
  3073. if (is_array($decoded)) {
  3074. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3075. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3076. $unwrapped = $decoded[$key];
  3077. break;
  3078. }
  3079. }
  3080. }
  3081. if ($unwrapped !== null) {
  3082. $fullContent = $unwrapped;
  3083. $chunkSize = 256;
  3084. $contentLength = mb_strlen($fullContent);
  3085. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3086. yield [
  3087. 'type' => 'content',
  3088. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3089. ];
  3090. }
  3091. } elseif ($pendingContent !== '') {
  3092. // 误判:补发暂缓内容,避免内容丢失
  3093. yield [
  3094. 'type' => 'content',
  3095. 'content' => $pendingContent,
  3096. ];
  3097. }
  3098. }
  3099. yield [
  3100. 'type' => 'done',
  3101. 'full_content' => $fullContent,
  3102. 'full_reasoning' => '',
  3103. 'usage' => $usage
  3104. ];
  3105. return;
  3106. } catch (\Exception $e) {
  3107. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3108. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3109. $usedLunaFallback = true;
  3110. $apiKey = $lunaApiKey;
  3111. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3112. continue;
  3113. }
  3114. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3115. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3116. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3117. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3118. throw $e;
  3119. }
  3120. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3121. 'retry' => $attempt + 1,
  3122. 'max_retries' => $maxRetries,
  3123. 'error' => $e->getMessage()
  3124. ]);
  3125. sleep($interval);
  3126. $attempt++;
  3127. }
  3128. }
  3129. }
  3130. // 与推理模型对话
  3131. public function chatWithReasoner($data) {
  3132. $content = getProp($data, 'content');
  3133. $model = getProp($data, 'model', 'r1');
  3134. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3135. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3136. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3137. if ($model == 'r1') {
  3138. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3139. $thinkingMode = 'disabled';
  3140. } else {
  3141. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3142. $thinkingMode = 'disabled';
  3143. }
  3144. // 获取可选情感(根据音色可支持情感选)
  3145. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3146. $emotion_list = [];
  3147. foreach ($timbre_emotion as $emotion) {
  3148. $tmp = explode(',', $emotion);
  3149. $emotion_list = array_merge($emotion_list, $tmp);
  3150. }
  3151. $emotion_list = array_unique($emotion_list);
  3152. $emotion_str = implode('、', $emotion_list);
  3153. // // 获取可选情感
  3154. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3155. // $emotion_str = implode('、', $emotion_list);
  3156. // 是否启用情感
  3157. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3158. if ($enable_emotion) {
  3159. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3160. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3161. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3162. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3163. }else {
  3164. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3165. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3166. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3167. }
  3168. $messages = [
  3169. [
  3170. 'role' => 'system',
  3171. 'content' => $sys_content
  3172. ],
  3173. [
  3174. 'role' => 'user',
  3175. 'content' => $content
  3176. ]
  3177. ];
  3178. $post_data = [
  3179. 'model' => $model,
  3180. 'messages' => $messages,
  3181. // 'max_tokens' => 8192,
  3182. 'temperature' => 1,
  3183. 'frequency_penalty' => 0,
  3184. 'presence_penalty' => 0,
  3185. 'thinking' => ['type' => $thinkingMode],
  3186. 'response_format' => [
  3187. 'type' => 'text'
  3188. ],
  3189. 'stream' => false
  3190. ];
  3191. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3192. // 根据模型类型选择调用方法
  3193. $fullContent = '';
  3194. $usage = [];
  3195. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3196. // DeepSeek 官方模型使用 DeepSeek API
  3197. $chatResult = $this->chatOnly($post_data);
  3198. } else if (in_array($model, $this->gpt_text_models)) {
  3199. // GPT-5.4 模型使用 TokenRouter API
  3200. $chatResult = $this->gpt54ChatOnly($post_data);
  3201. } else {
  3202. // 其他模型使用火山引擎API
  3203. $chatResult = $this->volcEngineChatCompletion($post_data);
  3204. }
  3205. if (is_array($chatResult)) {
  3206. $fullContent = $chatResult['fullContent'];
  3207. $usage = $chatResult['usage'];
  3208. }
  3209. // 处理获取到的剧本数据
  3210. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3211. $result = [
  3212. 'origin_content' => $fullContent,
  3213. 'roles' => getProp($script_content, 'roles'),
  3214. 'words' => getProp($script_content, 'words'),
  3215. ];
  3216. // 仅记录 token 使用明细(不扣积分)
  3217. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3218. 'model' => $model,
  3219. 'source' => 'chatWithReasoner',
  3220. ], $model);
  3221. return $result;
  3222. }
  3223. public function resetParagraphAudio($data) {
  3224. $bid = getProp($data, 'bid');
  3225. $cid = getProp($data, 'cid');
  3226. $version_id = getProp($data, 'version_id');
  3227. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3228. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3229. 'generate_status' => '待制作',
  3230. 'updated_at' => date('Y-m-d H:i:s')
  3231. ]);
  3232. }
  3233. public function saveParagraphAudio($data) {
  3234. $bid = getProp($data, 'bid');
  3235. $cid = getProp($data, 'cid');
  3236. $version_id = getProp($data, 'version_id');
  3237. $sequence = getProp($data, 'sequence');
  3238. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3239. // 获取所有情感
  3240. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3241. $emotion_list = array_flip($emotion_list);
  3242. // 获取音色支持情感
  3243. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3244. $timbre_emotion = explode(',', $timbre_emotion);
  3245. $emotion = getProp($data, 'emotion');
  3246. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3247. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3248. $list = [
  3249. 'bid' => $bid,
  3250. 'cid' => $cid,
  3251. 'version_id' => $version_id,
  3252. 'sequence' => $sequence,
  3253. 'role' => getProp($data, 'role'),
  3254. 'gender' => getProp($data, 'gender'),
  3255. 'text' => trim(getProp($data, 'text')),
  3256. 'emotion' => $emotion,
  3257. 'emotion_type' => $emotion_type,
  3258. 'voice_type' => getProp($data, 'voice_type'),
  3259. 'voice_name' => getProp($data, 'voice_name'),
  3260. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3261. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3262. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3263. 'pitch' => getProp($data, 'pitch', 0),
  3264. // 'paragraph_audio_url' => '',
  3265. 'generate_status' => '制作中',
  3266. 'error_msg' => '',
  3267. 'updated_at' => date('Y-m-d H:i:s')
  3268. ];
  3269. $continue = false;
  3270. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3271. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3272. $list['generate_status'] = '制作成功';
  3273. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3274. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3275. $continue = true;
  3276. }
  3277. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3278. if ($id) {
  3279. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3280. }else {
  3281. $list['created_at'] = date('Y-m-d H:i:s');
  3282. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3283. $boolen = $id ? true : false;
  3284. }
  3285. // 如果更新成功则加入查询队列
  3286. if ($boolen) {
  3287. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3288. Redis::sadd($redis_key, $id);
  3289. }
  3290. if ($boolen && !$continue) {
  3291. $boolen = false;
  3292. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3293. // 根据ID通过API通知合成音频
  3294. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3295. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3296. $response = $result->getBody()->getContents();
  3297. $response_arr = json_decode($response, true);
  3298. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3299. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3300. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3301. Utils::throwError('20003:通知火山生成段落音频失败');
  3302. }
  3303. $boolen = true;
  3304. }
  3305. return $boolen;
  3306. }
  3307. public function insertAudioEffect($data) {
  3308. $audio_id = getProp($data, 'audio_id');
  3309. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3310. $bid = getProp($chapter_audio, 'bid');
  3311. $version_id = getProp($chapter_audio, 'version_id');
  3312. $cid = getProp($chapter_audio, 'cid');
  3313. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3314. $audio_effect_json = getProp($data, 'audio_effect_json');
  3315. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3316. try {
  3317. DB::beginTransaction();
  3318. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3319. if (!$count) {
  3320. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3321. }else {
  3322. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3323. }
  3324. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3325. 'audio_effect_status' => '添加中',
  3326. 'audio_effect_json' => $audio_effect_json,
  3327. 'updated_at' => date('Y-m-d H:i:s')
  3328. ]);
  3329. if (!$boolen1) {
  3330. DB::rollBack();
  3331. Utils::throwError('20003:更新生成数据失败');
  3332. }
  3333. $id = DB::table('mp_audio_tasks')->insertGetId([
  3334. 'audio_id' => $audio_id,
  3335. 'generate_status' => '执行中',
  3336. 'generate_json' => json_encode([], 256),
  3337. 'bid' => $bid,
  3338. 'book_name' => getProp($chapter_audio, 'book_name'),
  3339. 'version_id' => $version_id,
  3340. 'version_name' => getProp($chapter_audio, 'version_name'),
  3341. 'cid' => $cid,
  3342. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3343. 'task_name' => $task_name,
  3344. 'created_at' => date('Y-m-d H:i:s'),
  3345. 'updated_at' => date('Y-m-d H:i:s')
  3346. ]);
  3347. if (!$id) {
  3348. DB::rollBack();
  3349. Utils::throwError('20003:创建任务失败');
  3350. }
  3351. }catch (\Exception $e) {
  3352. DB::rollBack();
  3353. Utils::throwError('20003:'.$e->getMessage());
  3354. }
  3355. DB::commit();
  3356. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3357. // 根据ID通过API通知合成音频
  3358. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3359. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3360. $response = $result->getBody()->getContents();
  3361. $response_arr = json_decode($response, true);
  3362. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3363. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3364. Log::info('通知火山插入音效失败: '.$error_msg);
  3365. Utils::throwError('20003:通知火山插入音效失败');
  3366. }
  3367. return true;
  3368. }
  3369. public function insertBgm($data) {
  3370. $audio_id = getProp($data, 'audio_id');
  3371. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3372. $bid = getProp($chapter_audio, 'bid');
  3373. $version_id = getProp($chapter_audio, 'version_id');
  3374. $cid = getProp($chapter_audio, 'cid');
  3375. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3376. $bgm_json = getProp($data, 'bgm_json');
  3377. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3378. if (!$bgm_json) {
  3379. $bgm_json = getProp($data, 'audio_effect_json');
  3380. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3381. }
  3382. try {
  3383. DB::beginTransaction();
  3384. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3385. if (!$count) {
  3386. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3387. }else {
  3388. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3389. }
  3390. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3391. 'bgm_status' => '添加中',
  3392. 'bgm_json' => $bgm_json,
  3393. 'updated_at' => date('Y-m-d H:i:s')
  3394. ]);
  3395. if (!$boolen1) {
  3396. DB::rollBack();
  3397. Utils::throwError('20003:更新生成数据失败');
  3398. }
  3399. $id = DB::table('mp_audio_tasks')->insertGetId([
  3400. 'audio_id' => $audio_id,
  3401. 'generate_status' => '执行中',
  3402. 'generate_json' => json_encode([], 256),
  3403. 'bid' => $bid,
  3404. 'book_name' => getProp($chapter_audio, 'book_name'),
  3405. 'version_id' => $version_id,
  3406. 'version_name' => getProp($chapter_audio, 'version_name'),
  3407. 'cid' => $cid,
  3408. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3409. 'task_name' => $task_name,
  3410. 'created_at' => date('Y-m-d H:i:s'),
  3411. 'updated_at' => date('Y-m-d H:i:s')
  3412. ]);
  3413. if (!$id) {
  3414. DB::rollBack();
  3415. Utils::throwError('20003:创建任务失败');
  3416. }
  3417. }catch (\Exception $e) {
  3418. DB::rollBack();
  3419. Utils::throwError('20003:'.$e->getMessage());
  3420. }
  3421. DB::commit();
  3422. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3423. // 根据ID通过API通知合成音频
  3424. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3425. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3426. $response = $result->getBody()->getContents();
  3427. $response_arr = json_decode($response, true);
  3428. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3429. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3430. Log::info('通知火山插入bgm失败: '.$error_msg);
  3431. Utils::throwError('20003:通知火山插入bgm失败');
  3432. }
  3433. return true;
  3434. }
  3435. public function getParagraphAudios($data) {
  3436. $bid = getProp($data, 'bid');
  3437. $cid = getProp($data, 'cid');
  3438. $version_id = getProp($data, 'version_id');
  3439. $sequence = getProp($data, 'sequence');
  3440. // 获取已生成的音频
  3441. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3442. if ($sequence) $query->where('sequence', $sequence);
  3443. $paragraph_audios = $query->orderBy('sequence')->get();
  3444. $result = [];
  3445. foreach($paragraph_audios as $item) {
  3446. $result[] = [
  3447. 'sequence' => getProp($item, 'sequence'),
  3448. 'role' => getProp($item, 'role'),
  3449. 'gender' => getProp($item, 'gender'),
  3450. 'text' => trim(getProp($item, 'text')),
  3451. 'emotion' => getProp($item, 'emotion'),
  3452. 'emotion_type' => getProp($item, 'emotion_type'),
  3453. 'voice_type' => getProp($item, 'voice_type'),
  3454. 'voice_name' => getProp($item, 'voice_name'),
  3455. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3456. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3457. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3458. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3459. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3460. ];
  3461. }
  3462. return $result;
  3463. }
  3464. // 新增合成任务
  3465. public function addGenerateTask($data) {
  3466. $bid = getProp($data, 'bid');
  3467. $cid = getProp($data, 'cid');
  3468. $version_id = getProp($data, 'version_id');
  3469. $generate_json = getProp($data, 'generate_json');
  3470. // 获取已生成的音频
  3471. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3472. $paragraph_list = [];
  3473. foreach($paragraph_audios as $item) {
  3474. $paragraph_list[getProp($item, 'sequence')] = [
  3475. 'role' => getProp($item, 'role'),
  3476. 'gender' => getProp($item, 'gender'),
  3477. 'text' => trim(getProp($item, 'text')),
  3478. 'emotion' => getProp($item, 'emotion'),
  3479. 'emotion_type' => getProp($item, 'emotion_type'),
  3480. 'voice_type' => getProp($item, 'voice_type'),
  3481. 'voice_name' => getProp($item, 'voice_name'),
  3482. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3483. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3484. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3485. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3486. ];
  3487. }
  3488. // 更新角色-音色信息
  3489. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3490. $existed_role_info = json_decode($existed_role_info, true);
  3491. if (!$existed_role_info) $existed_role_info = [];
  3492. // 获取情感信息
  3493. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3494. $emotion_list = array_flip($emotion_list);
  3495. // 获取音色对应情感组
  3496. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3497. $timbre_emotion_list = [];
  3498. foreach($timbre_emotions as $item) {
  3499. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3500. }
  3501. // 构造生成音频的json
  3502. $words = json_decode($generate_json, true);
  3503. // 最终合成前的参数组
  3504. $mp_chapter_paragraph_audios = [];
  3505. $sequence = 1;
  3506. $complete_paragraph_sequences = [];
  3507. foreach($words as &$word) {
  3508. 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:参数格式有误');
  3509. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3510. $role = getProp($word, 'role');
  3511. $word['gender'] = (int)$word['gender'];
  3512. // 判断音色对应情感是否支持,不支持则调整为中性
  3513. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3514. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3515. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3516. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3517. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3518. }else {
  3519. $word['emotion'] = '中性';
  3520. $word['emotion_type'] = 'neutral';
  3521. }
  3522. $existed_role_info[$role] = [
  3523. 'timbre_type' => $word['voice_type'],
  3524. 'timbre_name' => $word['voice_name'],
  3525. 'emotion' => $word['emotion'],
  3526. 'emotion_type' => $word['emotion_type'],
  3527. 'speed_ratio' => $word['speed_ratio'],
  3528. 'loudness_ratio'=> $word['loudness_ratio'],
  3529. 'emotion_scale' => $word['emotion_scale'],
  3530. 'pitch' => $word['pitch']
  3531. ];
  3532. $word['paragraph_audio_url'] = '';
  3533. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3534. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3535. // 如果音频存在并且参数都未改变则使用已生成的音频
  3536. if (getProp($paragraph, 'paragraph_audio_url')) {
  3537. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3538. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3539. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3540. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3541. // {
  3542. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3543. // }
  3544. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3545. }
  3546. $tmp = $word;
  3547. // 组装章节分句音频数据
  3548. // $tmp['sequence'] = getProp($word, 'sequence');
  3549. // $tmp['text'] = getProp($word, 'text');
  3550. // $tmp['emotion'] = getProp($word, 'emotion');
  3551. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3552. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3553. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3554. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3555. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3556. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3557. $tmp['bid'] = $bid;
  3558. $tmp['version_id'] = $version_id;
  3559. $tmp['cid'] = $cid;
  3560. $tmp['sequence'] = $sequence;
  3561. $tmp['created_at'] = date('Y-m-d H:i:s');
  3562. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3563. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3564. $mp_chapter_paragraph_audios[] = $tmp;
  3565. $complete_paragraph_sequences[] = $sequence;
  3566. $sequence++;
  3567. }
  3568. $generate_json = json_encode($words, 256);
  3569. // 判断是否有未生成字幕的段落
  3570. $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();
  3571. if ($no_subtitle_sequences) {
  3572. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3573. }
  3574. try {
  3575. DB::beginTransaction();
  3576. $role_info = json_encode($existed_role_info, 256);
  3577. $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')]);
  3578. if (!$boolen) {
  3579. DB::rollBack();
  3580. Utils::throwError('20003:更新角色信息失败');
  3581. }
  3582. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3583. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3584. if (!$count) {
  3585. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3586. }else {
  3587. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3588. }
  3589. $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')]);
  3590. if (!$boolen1) {
  3591. DB::rollBack();
  3592. Utils::throwError('20003:更新生成数据失败');
  3593. }
  3594. $id = DB::table('mp_audio_tasks')->insertGetId([
  3595. 'audio_id' => getProp($chapter_audio, 'id'),
  3596. 'generate_status' => '执行中',
  3597. 'generate_json' => $generate_json,
  3598. 'bid' => $bid,
  3599. 'book_name' => getProp($chapter_audio, 'book_name'),
  3600. 'version_id' => $version_id,
  3601. 'version_name' => getProp($chapter_audio, 'version_name'),
  3602. 'cid' => $cid,
  3603. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3604. 'task_name' => $task_name,
  3605. 'created_at' => date('Y-m-d H:i:s'),
  3606. 'updated_at' => date('Y-m-d H:i:s')
  3607. ]);
  3608. if (!$id) {
  3609. DB::rollBack();
  3610. Utils::throwError('20003:创建任务失败');
  3611. }
  3612. // 删除不在段落序号范围内的其他数据
  3613. if ($complete_paragraph_sequences) {
  3614. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3615. }
  3616. // // 删除章节分句音频数据并重新插入
  3617. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3618. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3619. // if (!$boolen3) {
  3620. // DB::rollBack();
  3621. // Utils::throwError('20003:更新章节分句音频失败');
  3622. // }
  3623. } catch (\Exception $e) {
  3624. DB::rollBack();
  3625. Utils::throwError('20003:'.$e->getMessage());
  3626. }
  3627. DB::commit();
  3628. // 通知火山生成音频
  3629. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3630. // 根据ID通过API通知合成音频
  3631. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3632. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3633. $response = $result->getBody()->getContents();
  3634. $response_arr = json_decode($response, true);
  3635. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3636. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3637. Log::info('通知火山生成音频失败: '.$error_msg);
  3638. Utils::throwError('20003:通知火山生成音频失败');
  3639. }
  3640. return true;
  3641. }
  3642. public function timbreList($data) {
  3643. $gender = getProp($data, 'gender');
  3644. $timbre_name = getProp($data, 'voice_name');
  3645. $category_id = getProp($data, 'category_id');
  3646. $age_stage = getProp($data, 'age_stage');
  3647. $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');
  3648. if ($gender) {
  3649. $query->where('gender', $gender);
  3650. }
  3651. if ($timbre_name) {
  3652. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3653. }
  3654. if ($category_id) {
  3655. $query->where(function ($query) use ($category_id) {
  3656. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3657. });
  3658. }
  3659. if ($age_stage) {
  3660. $query->where('age_stage', $age_stage);
  3661. }
  3662. $list = $query->get()->map(function ($value) {
  3663. $value = (array)$value;
  3664. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3665. return $value;
  3666. })->toArray();
  3667. return $list;
  3668. }
  3669. // 生成火山临时token
  3670. public function setStsToken() {
  3671. // ************* 配置参数 *************
  3672. $method = 'GET';
  3673. $service = 'sts';
  3674. $host = 'open.volcengineapi.com';
  3675. $region = env('VOLC_REGION');
  3676. $endpoint = 'https://open.volcengineapi.com';
  3677. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3678. $access_key = env('VOLC_AK');
  3679. $secret_key = env('VOLC_SK');
  3680. // 获取缓存中的token,如果没有则请求接口
  3681. $token = Redis::get('volc_sts_token');
  3682. if (!$token) {
  3683. // 查询参数
  3684. $query_parameters = [
  3685. 'Action' => 'AssumeRole',
  3686. 'RoleSessionName' => 'user@zw',
  3687. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3688. 'Version' => '2018-01-01'
  3689. ];
  3690. // 生成URL编码的查询字符串
  3691. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3692. // 获取签名头信息
  3693. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3694. // 构建完整URL
  3695. $request_url = $endpoint . '?' . $request_parameters;
  3696. $client = new Client(['verify' => false]);
  3697. $response = $client->get($request_url, ['headers' => $headers]);
  3698. $response_arr = json_decode($response->getBody()->getContents(), true);
  3699. $result = [
  3700. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3701. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3702. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3703. 'Region' => env('VOLC_REGION'),
  3704. 'Endpoint' => env('VOLC_END_POINT'),
  3705. 'Bucket' => env('VOLC_BUCKET'),
  3706. ];
  3707. // 缓存token
  3708. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3709. return $result;
  3710. } else {
  3711. return json_decode($token, true);
  3712. }
  3713. // $response = $response['Response'];
  3714. // $access_key = $response['Credentials']['AccessKeyId'];
  3715. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3716. // $security_token = $response['Credentials']['SecurityToken'];
  3717. // $expiration = $response['Credentials']['Expiration'];
  3718. // dd($response_arr);
  3719. }
  3720. public function emotionGroups($data) {
  3721. $id = getProp($data, 'group_id');
  3722. $group_name = getProp($data, 'group_name');
  3723. $voice_type = getProp($data, 'voice_type');
  3724. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3725. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3726. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3727. if ($group_name) {
  3728. $query->where('group_name', 'like', "%{$group_name}%");
  3729. }
  3730. if ($id) {
  3731. $query->where('id', $id);
  3732. }
  3733. if ($voice_type) {
  3734. $query->where('voice_type', $voice_type);
  3735. }
  3736. return $query->orderBy('id')->get()->map(function ($value) {
  3737. return (array)$value;
  3738. })->toArray();
  3739. }
  3740. private function sign($key, $msg) {
  3741. return hash_hmac('sha256', $msg, $key, true);
  3742. }
  3743. // 生成签名密钥
  3744. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3745. $kDate = $this->sign($key, $dateStamp);
  3746. $kRegion = $this->sign($kDate, $regionName);
  3747. $kService = $this->sign($kRegion, $serviceName);
  3748. $kSigning = $this->sign($kService, 'request');
  3749. return $kSigning;
  3750. }
  3751. // 获取签名头信息
  3752. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3753. $contenttype = 'application/x-www-form-urlencoded';
  3754. $accept = 'application/json';
  3755. // 获取当前UTC时间
  3756. $t = new DateTime('now', new DateTimeZone('UTC'));
  3757. $xdate = $t->format('Ymd\THis\Z');
  3758. $datestamp = $t->format('Ymd');
  3759. // 1. 拼接规范请求串
  3760. $canonical_uri = '/';
  3761. $canonical_querystring = $request_parameters;
  3762. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3763. $signed_headers = 'content-type;host;x-date';
  3764. // 空请求体的SHA256哈希
  3765. $payload_hash = hash('sha256', '');
  3766. $canonical_request = implode("\n", [
  3767. $method,
  3768. $canonical_uri,
  3769. $canonical_querystring,
  3770. $canonical_headers,
  3771. $signed_headers,
  3772. $payload_hash
  3773. ]);
  3774. // 2. 拼接待签名字符串
  3775. $algorithm = 'HMAC-SHA256';
  3776. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3777. $hashed_canonical_request = hash('sha256', $canonical_request);
  3778. $string_to_sign = implode("\n", [
  3779. $algorithm,
  3780. $xdate,
  3781. $credential_scope,
  3782. $hashed_canonical_request
  3783. ]);
  3784. // 3. 计算签名
  3785. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3786. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3787. // 4. 添加签名到请求头
  3788. $authorization_header = sprintf(
  3789. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3790. $algorithm,
  3791. $access_key,
  3792. $credential_scope,
  3793. $signed_headers,
  3794. $signature
  3795. );
  3796. return [
  3797. 'Accept' => $accept,
  3798. 'Content-Type' => $contenttype,
  3799. 'X-Date' => $xdate,
  3800. 'Authorization' => $authorization_header
  3801. ];
  3802. }
  3803. // 文字合成语音(火山引擎)
  3804. public function tts($data) {
  3805. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3806. $headers = [
  3807. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3808. 'Content-Type' => 'application/json; charset=UTF-8'
  3809. ];
  3810. $post_data = [
  3811. 'app' => [
  3812. 'appid' => env('VOLC_APPID'),
  3813. 'token' => env('VOLC_TOKEN'),
  3814. 'cluster' => 'volcano_tts'
  3815. ],
  3816. 'user' => [
  3817. 'uid' => 'mp_audio'
  3818. ],
  3819. // 'audio' => [
  3820. // 'voice_type' =>
  3821. // ],
  3822. ];
  3823. }
  3824. public function scriptList($data) {
  3825. $uid = Site::getUid();
  3826. $script_id = getProp($data, 'script_id');
  3827. $script_name = getProp($data, 'script_name');
  3828. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3829. if ($script_id) {
  3830. $query->where('id', $script_id);
  3831. }
  3832. if ($script_name) {
  3833. $query->where('script_name', 'like', "%{$script_name}%");
  3834. }
  3835. return $query->orderBy('created_at', 'desc')->paginate(12);
  3836. }
  3837. public function scripts($data) {
  3838. $uid = Site::getUid();
  3839. $script_id = getProp($data, 'script_id');
  3840. $script_name = getProp($data, 'script_name');
  3841. $is_products = getProp($data, 'is_products');
  3842. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3843. if ($script_id) {
  3844. $query->where('id', $script_id);
  3845. }
  3846. if ($is_products !== '') {
  3847. $query->where('is_products', $is_products);
  3848. }
  3849. if ($script_name) {
  3850. $query->where('script_name', 'like', "%{$script_name}%");
  3851. }
  3852. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3853. return (array)$value;
  3854. })->toArray();
  3855. }
  3856. public function scriptInfo($data) {
  3857. $uid = Site::getUid();
  3858. $script_id = getProp($data, 'script_id');
  3859. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3860. // ->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();
  3861. ->selectRaw('id as script_id, script_name')->first();
  3862. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3863. $script = (array)$script;
  3864. // 获取分集组信息
  3865. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3866. ->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')
  3867. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3868. $value = (array)$value;
  3869. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3870. return (array)$value;
  3871. })->toArray();
  3872. $script['group'] = $groups;
  3873. return $script;
  3874. }
  3875. public function createScript($data) {
  3876. $script_name = getProp($data, 'script_name');
  3877. $uid = Site::getUid(); // 获取当前用户ID
  3878. $cpid = Site::getCpid(); // 获取当前公司组ID
  3879. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3880. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3881. $script_name .= '_'.date('YmdHis');
  3882. }
  3883. return DB::table('mp_scripts')->insertGetId([
  3884. 'script_name' => $script_name,
  3885. 'user_id' => $uid,
  3886. 'cpid' => $cpid,
  3887. 'created_at' => date('Y-m-d H:i:s'),
  3888. 'updated_at' => date('Y-m-d H:i:s')
  3889. ]);
  3890. }
  3891. public function editScript($data) {
  3892. $script_id = getProp($data, 'script_id');
  3893. $script_name = getProp($data, 'script_name');
  3894. $uid = Site::getUid(); // 获取当前用户ID
  3895. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3896. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3897. if ($id && (int)$id !== (int)$script_id) {
  3898. $script_name .= '_'.date('YmdHis');
  3899. }
  3900. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3901. 'script_name' => $script_name,
  3902. 'updated_at' => date('Y-m-d H:i:s')
  3903. ]);
  3904. }
  3905. public function delScript($data) {
  3906. $script_id = getProp($data, 'script_id');
  3907. $uid = Site::getUid(); // 获取当前用户ID
  3908. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3909. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3910. 'is_deleted' => 1,
  3911. 'updated_at' => date('Y-m-d H:i:s')
  3912. ]);
  3913. }
  3914. public function createEpisode($data) {
  3915. $script_id = getProp($data, 'script_id');
  3916. $group_name = getProp($data, 'group_name');
  3917. $remark = getProp($data, 'remark');
  3918. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3919. $uid = Site::getUid(); // 获取当前用户ID
  3920. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3921. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3922. $group_name .= '_'.date('YmdHis');
  3923. }
  3924. return DB::table('mp_script_episode_group')->insertGetId([
  3925. 'script_id' => $script_id,
  3926. 'group_name' => $group_name,
  3927. 'user_id' => $uid,
  3928. 'remark' => $remark,
  3929. 'created_at' => date('Y-m-d H:i:s'),
  3930. 'updated_at' => date('Y-m-d H:i:s')
  3931. ]);
  3932. }
  3933. public function editEpisode($data) {
  3934. $group_id = getProp($data, 'group_id');
  3935. $start_episode_number = getProp($data, 'start_episode_number');
  3936. $end_episode_number = getProp($data, 'end_episode_number');
  3937. $group_name = getProp($data, 'group_name');
  3938. $uid = Site::getUid(); // 获取当前用户ID
  3939. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3940. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3941. if ($id && (int)$id !== (int)$group_id) {
  3942. $group_name .= '_'.date('YmdHis');
  3943. }
  3944. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3945. 'group_name' => $group_name,
  3946. 'start_episode_number' => $start_episode_number,
  3947. 'end_episode_number' => $end_episode_number,
  3948. 'updated_at' => date('Y-m-d H:i:s')
  3949. ]);
  3950. }
  3951. public function delEpisode($data) {
  3952. $group_id = getProp($data, 'group_id');
  3953. $uid = Site::getUid(); // 获取当前用户ID
  3954. if (!$group_id) Utils::throwError('20003:请选择分集');
  3955. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3956. 'is_deleted' => 1,
  3957. 'updated_at' => date('Y-m-d H:i:s')
  3958. ]);
  3959. }
  3960. /**
  3961. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3962. *
  3963. * @param array $data 包含以下参数:
  3964. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3965. * - question: 用户问题(可选)
  3966. * - model: 使用的模型(r1 或 v3,默认 v3)
  3967. * @return \Generator 返回生成器,用于流式输出
  3968. */
  3969. public function generateEpisodes($data) {
  3970. $script_id = getProp($data, 'script_id');
  3971. $group_id = getProp($data, 'group_id');
  3972. // $file = getProp($data, 'file');
  3973. $file = '';
  3974. $content = getProp($data, 'content', '');
  3975. // $bid = getProp($data, 'bid', 0);
  3976. $bid = 0;
  3977. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3978. if (!$group) {
  3979. Utils::throwError('20003:剧本分集不存在');
  3980. }
  3981. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3982. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3983. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3984. $prompt = getProp($data, 'prompt');
  3985. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3986. $model = getProp($data, 'model');
  3987. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3988. Utils::throwError('20003:该模型不存在!');
  3989. }
  3990. // 检查是否存在重叠的剧集序号范围
  3991. $exists_groups = DB::table('mp_script_episode_group')
  3992. ->where('script_id', $script_id)
  3993. ->where('id', '<>', $group_id) // 排除当前组
  3994. ->where('is_deleted', 0)
  3995. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3996. // 检查新范围是否与现有范围重叠
  3997. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3998. // 新范围的开始在现有范围内
  3999. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4000. ->where('end_episode_number', '>=', $start_episode_sequence);
  4001. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4002. // 新范围的结束在现有范围内
  4003. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4004. ->where('end_episode_number', '>=', $end_episode_sequence);
  4005. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4006. // 新范围完全包含现有范围
  4007. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4008. ->where('end_episode_number', '<=', $end_episode_sequence);
  4009. });
  4010. })
  4011. ->select('start_episode_number', 'end_episode_number')
  4012. ->get();
  4013. if ($exists_groups->isNotEmpty()) {
  4014. $conflict_ranges = [];
  4015. foreach ($exists_groups as $group) {
  4016. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4017. }
  4018. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4019. }
  4020. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4021. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4022. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4023. if ($model === 'deepseek-chat') {
  4024. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4025. $model = 'deepseek-v4-flash';
  4026. $thinkingMode = 'disabled';
  4027. } elseif ($model === 'deepseek-reasoner') {
  4028. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4029. $model = 'deepseek-v4-flash';
  4030. $thinkingMode = 'enabled';
  4031. }
  4032. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4033. if (!$script) {
  4034. Utils::throwError('20003:剧本不存在');
  4035. }
  4036. $content = getProp($group, 'content');
  4037. if (!$file && !$content && !$bid) {
  4038. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4039. }
  4040. // 提取文件内容
  4041. if ($file) {
  4042. $content = $this->extractFileContent($file);
  4043. if (!$content) {
  4044. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4045. }
  4046. } elseif ($bid) {
  4047. $content = $this->getContentByBid($bid);
  4048. if (!$content) {
  4049. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4050. }
  4051. } elseif ($content) {
  4052. $content = filterContent($content);
  4053. } elseif ($prompt) {
  4054. $content = filterContent($prompt);
  4055. } else {
  4056. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4057. }
  4058. // 构建消息
  4059. $messages = [
  4060. $this->sys_message,
  4061. [
  4062. 'role' => 'user',
  4063. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4064. ]
  4065. ];
  4066. $post_data = [
  4067. 'model' => $model,
  4068. 'messages' => $messages,
  4069. // 'max_tokens' => 8192,
  4070. 'temperature' => 0.7,
  4071. 'frequency_penalty' => 0,
  4072. 'presence_penalty' => 0,
  4073. 'thinking' => ['type' => $thinkingMode],
  4074. 'response_format' => ['type' => 'text'],
  4075. 'stream' => true
  4076. ];
  4077. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4078. // 根据模型类型选择调用方法
  4079. $fullContent = '';
  4080. $fullReasoningContent = '';
  4081. $usage = [];
  4082. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4083. // DeepSeek 官方模型使用 DeepSeek API
  4084. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4085. } else if (in_array($model, $this->gpt_text_models)) {
  4086. // GPT-5.4 模型使用 TokenRouter API
  4087. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4088. } else if (in_array($model, $this->gemini_text_models)) {
  4089. // Gemini 模型使用 Gemini API
  4090. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4091. } else {
  4092. // 其他模型使用火山引擎API
  4093. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4094. }
  4095. // 处理流式输出
  4096. foreach ($streamGenerator as $chunk) {
  4097. if (isset($chunk['type'])) {
  4098. if ($chunk['type'] === 'done') {
  4099. // 最终结果
  4100. $fullContent = $chunk['full_content'];
  4101. $fullReasoningContent = $chunk['full_reasoning'];
  4102. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4103. } else {
  4104. // 逐块yield数据
  4105. yield $chunk;
  4106. }
  4107. }
  4108. }
  4109. dLog('deepseek')->info('完整内容: '.$fullContent);
  4110. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4111. // 处理完整内容并返回最终结果
  4112. $script_arr = [];
  4113. if ($fullContent) {
  4114. $script_arr = extractScriptContent($fullContent);
  4115. }
  4116. logDB('deepseek', 'info', '解析内容', $script_arr);
  4117. if (!$script_arr['episodes']) {
  4118. Utils::throwError('20003:未生成剧本相关信息');
  4119. // yield [
  4120. // 'type' => 'done',
  4121. // 'script' => $script_arr,
  4122. // 'msg' => '未生成剧本相关信息',
  4123. // 'answer' => $fullContent,
  4124. // 'reasoning' => $fullReasoningContent,
  4125. // 'usage' => $usage
  4126. // ];
  4127. // return ;
  4128. }
  4129. try {
  4130. DB::beginTransaction();
  4131. // // 返回前保存剧本内容
  4132. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4133. // 'content' => $content,
  4134. // 'updated_at' => date('Y-m-d H:i:s')
  4135. // ]);
  4136. // if (!$boolen) {
  4137. // Utils::throwError('20003:保存剧本内容失败');
  4138. // }
  4139. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4140. // 'start_episode_number' => $start_episode_sequence,
  4141. // 'end_episode_number' => $end_episode_sequence,
  4142. // 'updated_at' => date('Y-m-d H:i:s')
  4143. // ]);
  4144. // if (!$boolen1) {
  4145. // Utils::throwError('20003:保存分集失败');
  4146. // }
  4147. $episode_content = '';
  4148. $episodes = [];
  4149. foreach ($script_arr['episodes'] as $item) {
  4150. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4151. // $episodes[] = [
  4152. // 'script_id' => $script_id,
  4153. // 'episode_number' => $item['episode_number'],
  4154. // 'episode_name' => $item['episode_name'],
  4155. // 'episode_content' => $item['episode_content'],
  4156. // 'created_at' => date('Y-m-d H:i:s'),
  4157. // 'updated_at' => date('Y-m-d H:i:s'),
  4158. // ];
  4159. }
  4160. if ($episode_content) {
  4161. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4162. 'episode_content' => $episode_content,
  4163. 'updated_at' => date('Y-m-d H:i:s')
  4164. ]);
  4165. if (!$boolen2) {
  4166. Utils::throwError('20003:保存分集内容失败');
  4167. }
  4168. }else {
  4169. Utils::throwError('20003:分集剧本解析失败');
  4170. }
  4171. }catch (\Exception $e) {
  4172. DB::rollBack();
  4173. Utils::throwError('20003:'.$e->getMessage());
  4174. }
  4175. DB::commit();
  4176. // 仅记录 token 使用明细(不扣积分)
  4177. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4178. 'model' => $model,
  4179. 'script_id' => $script_id,
  4180. 'group_id' => $group_id,
  4181. 'source' => 'generateEpisodes',
  4182. ], $model);
  4183. yield [
  4184. 'type' => 'done',
  4185. 'script' => $script_arr,
  4186. 'episode_content' => $episode_content,
  4187. 'answer' => $fullContent,
  4188. 'reasoning' => $fullReasoningContent,
  4189. 'usage' => $usage
  4190. ];
  4191. }
  4192. public function chatWithFileStream($data) {
  4193. $script_id = getProp($data, 'script_id');
  4194. $group_id = getProp($data, 'group_id');
  4195. $file = getProp($data, 'file');
  4196. $content = getProp($data, 'content', '');
  4197. $bid = getProp($data, 'bid', 0);
  4198. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4199. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4200. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4201. $prompt = getProp($data, 'prompt');
  4202. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4203. if (!empty($prompt)) {
  4204. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4205. }
  4206. $question = getProp($data, 'question', $baseQuestion);
  4207. $model = getProp($data, 'model');
  4208. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4209. Utils::throwError('20003:该模型不存在!');
  4210. }
  4211. // 检查是否存在重叠的剧集序号范围
  4212. $exists_groups = DB::table('mp_script_episode_group')
  4213. ->where('script_id', $script_id)
  4214. ->where('id', '<>', $group_id)
  4215. ->where('is_deleted', 0)
  4216. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4217. // 检查新范围是否与现有范围重叠
  4218. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4219. // 新范围的开始在现有范围内
  4220. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4221. ->where('end_episode_number', '>=', $start_episode_sequence);
  4222. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4223. // 新范围的结束在现有范围内
  4224. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4225. ->where('end_episode_number', '>=', $end_episode_sequence);
  4226. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4227. // 新范围完全包含现有范围
  4228. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4229. ->where('end_episode_number', '<=', $end_episode_sequence);
  4230. });
  4231. })
  4232. ->select('start_episode_number', 'end_episode_number')
  4233. ->get();
  4234. if ($exists_groups->isNotEmpty()) {
  4235. $conflict_ranges = [];
  4236. foreach ($exists_groups as $group) {
  4237. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4238. }
  4239. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4240. }
  4241. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4242. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4243. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4244. if ($model === 'deepseek-chat') {
  4245. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4246. $model = 'deepseek-v4-flash';
  4247. $thinkingMode = 'disabled';
  4248. } elseif ($model === 'deepseek-reasoner') {
  4249. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4250. $model = 'deepseek-v4-flash';
  4251. $thinkingMode = 'enabled';
  4252. }
  4253. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4254. if (!$script) {
  4255. Utils::throwError('20003:剧本不存在');
  4256. }
  4257. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4258. if (!$group) {
  4259. Utils::throwError('20003:剧本分集不存在');
  4260. }
  4261. if (!$file && !$content && !$bid) {
  4262. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4263. }
  4264. // 提取文件内容
  4265. if ($file) {
  4266. $content = $this->extractFileContent($file);
  4267. if (!$content) {
  4268. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4269. }
  4270. } elseif ($bid) {
  4271. $content = $this->getContentByBid($bid);
  4272. if (!$content) {
  4273. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4274. }
  4275. } elseif ($content) {
  4276. $content = filterContent($content);
  4277. } elseif ($prompt) {
  4278. $content = filterContent($prompt);
  4279. } else {
  4280. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4281. }
  4282. // 构建消息
  4283. $messages = [
  4284. [
  4285. 'role' => 'system',
  4286. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4287. 强制要求:\n
  4288. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4289. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4290. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4291. 普通要求:\n
  4292. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4293. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4294. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4295. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4296. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4297. 示例如下:\n
  4298. ###剧本名:西昆仑
  4299. ###故事梗概
  4300. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4301. ###剧本亮点
  4302. 亮点1:绝境奇药,生死一线
  4303. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4304. 亮点2:结拜兄妹,化解尴尬
  4305. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4306. 亮点3:纤发夺命,情愫暗涌
  4307. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4308. ###人物关系
  4309. 阿雪与梁萧之间存在兄妹之情。
  4310. ###核心矛盾
  4311. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4312. ###主体列表
  4313. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4314. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4315. 阴阳球:天地异宝,能化生精气,救人于危难。
  4316. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4317. ###美术风格
  4318. 基础画风风格词:厚涂古风
  4319. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4320. ###场景列表
  4321. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4322. [
  4323. 'role' => 'user',
  4324. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4325. ]
  4326. ];
  4327. $post_data = [
  4328. 'model' => $model,
  4329. 'messages' => $messages,
  4330. // 'max_tokens' => 8192,
  4331. 'temperature' => 0.7,
  4332. 'frequency_penalty' => 0,
  4333. 'presence_penalty' => 0,
  4334. 'thinking' => ['type' => $thinkingMode],
  4335. 'response_format' => ['type' => 'text'],
  4336. 'stream' => true
  4337. ];
  4338. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4339. // 根据模型类型选择调用方法
  4340. $fullContent = '';
  4341. $fullReasoningContent = '';
  4342. $usage = [];
  4343. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4344. // DeepSeek 官方模型使用 DeepSeek API
  4345. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4346. } else if (in_array($model, $this->gpt_text_models)) {
  4347. // GPT-5.4 模型使用 TokenRouter API
  4348. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4349. } else if (in_array($model, $this->gemini_text_models)) {
  4350. // Gemini 模型使用 Gemini API
  4351. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4352. } else {
  4353. // 其他模型使用火山引擎API
  4354. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4355. }
  4356. // 处理流式输出
  4357. foreach ($streamGenerator as $chunk) {
  4358. if (isset($chunk['type'])) {
  4359. if ($chunk['type'] === 'done') {
  4360. // 最终结果
  4361. $fullContent = $chunk['full_content'];
  4362. $fullReasoningContent = $chunk['full_reasoning'];
  4363. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4364. } else {
  4365. // 逐块yield数据
  4366. yield $chunk;
  4367. }
  4368. }
  4369. }
  4370. dLog('deepseek')->info('完整内容: '.$fullContent);
  4371. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4372. // 处理完整内容并返回最终结果
  4373. $script_arr = [];
  4374. if ($fullContent) {
  4375. $script_arr = extractScriptContent($fullContent);
  4376. }
  4377. logDB('deepseek', 'info', '解析内容', $script_arr);
  4378. if (!$script_arr['roles']) {
  4379. Utils::throwError('20003:未生成剧本相关信息');
  4380. // yield [
  4381. // 'type' => 'done',
  4382. // 'script' => $script_arr,
  4383. // 'msg' => '未生成剧本相关信息',
  4384. // 'answer' => $fullContent,
  4385. // 'reasoning' => $fullReasoningContent,
  4386. // 'usage' => $usage
  4387. // ];
  4388. }
  4389. try {
  4390. DB::beginTransaction();
  4391. // // 返回前保存剧本内容
  4392. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4393. // 'content' => $content,
  4394. // 'status' => '解析完成',
  4395. // 'updated_at' => date('Y-m-d H:i:s')
  4396. // ]);
  4397. // if (!$boolen) {
  4398. // Utils::throwError('20003:保存剧本内容失败');
  4399. // }
  4400. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4401. 'start_episode_number' => $start_episode_sequence,
  4402. 'end_episode_number' => $end_episode_sequence,
  4403. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4404. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4405. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4406. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4407. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4408. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4409. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4410. 'status' => '解析完成',
  4411. 'content' => $content,
  4412. 'updated_at' => date('Y-m-d H:i:s')
  4413. ]);
  4414. if (!$boolen1) {
  4415. Utils::throwError('20003:保存分集失败');
  4416. }
  4417. // $episodes = [];
  4418. // foreach ($script_arr['episodes'] as $item) {
  4419. // $episodes[] = [
  4420. // 'script_id' => $script_id,
  4421. // 'episode_number' => $item['episode_number'],
  4422. // 'episode_name' => $item['episode_name'],
  4423. // 'episode_content' => $item['episode_content'],
  4424. // 'created_at' => date('Y-m-d H:i:s'),
  4425. // 'updated_at' => date('Y-m-d H:i:s'),
  4426. // ];
  4427. // }
  4428. // if ($episodes) {
  4429. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4430. // if (!$boolen2) {
  4431. // Utils::throwError('20003:保存分集内容失败');
  4432. // }
  4433. // }else {
  4434. // Utils::throwError('20003:分集剧本解析失败');
  4435. // }
  4436. }catch (\Exception $e) {
  4437. DB::rollBack();
  4438. Utils::throwError('20003:'.$e->getMessage());
  4439. }
  4440. DB::commit();
  4441. // 仅记录 token 使用明细(不扣积分)
  4442. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4443. 'model' => $model,
  4444. 'script_id' => $script_id,
  4445. 'group_id' => $group_id,
  4446. 'source' => 'chatWithFileStream',
  4447. ], $model);
  4448. yield [
  4449. 'type' => 'done',
  4450. 'script' => $script_arr,
  4451. 'answer' => $fullContent,
  4452. 'reasoning' => $fullReasoningContent,
  4453. 'usage' => $usage
  4454. ];
  4455. }
  4456. /**
  4457. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4458. *
  4459. * @param array $data 包含以下参数:
  4460. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4461. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4462. * - model: 使用的模型(r1 或 v3,默认 v3)
  4463. * @return array
  4464. */
  4465. public function chatWithFile($data) {
  4466. $script_id = getProp($data, 'script_id');
  4467. $file = getProp($data, 'file');
  4468. $content = getProp($data, 'content', '');
  4469. $bid = getProp($data, 'bid', 0);
  4470. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4471. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4472. $prompt = getProp($data, 'prompt');
  4473. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4474. if (!empty($prompt)) {
  4475. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4476. }
  4477. $question = getProp($data, 'question', $baseQuestion);
  4478. // 处理文本模型
  4479. $model = getProp($data, 'model');
  4480. if (!$model) {
  4481. // 用户没有输入,使用默认值
  4482. $model = 'doubao-seed-2-0-mini-260215';
  4483. }
  4484. // 验证模型是否在可用模型表中
  4485. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4486. $model = 'doubao-seed-2-0-mini-260215';
  4487. }
  4488. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4489. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4490. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4491. if ($model === 'deepseek-chat') {
  4492. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4493. $model = 'deepseek-v4-flash';
  4494. $thinkingMode = 'disabled';
  4495. } elseif ($model === 'deepseek-reasoner') {
  4496. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4497. $model = 'deepseek-v4-flash';
  4498. $thinkingMode = 'enabled';
  4499. }
  4500. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4501. if (!$script) {
  4502. Utils::throwError('20003:剧本不存在');
  4503. }
  4504. if (!$file && !$content && !$bid) {
  4505. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4506. }
  4507. // 提取文件内容
  4508. if ($file) {
  4509. $content = $this->extractFileContent($file);
  4510. if (!$content) {
  4511. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4512. }
  4513. } elseif ($bid) {
  4514. $content = $this->getContentByBid($bid);
  4515. if (!$content) {
  4516. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4517. }
  4518. } elseif ($content) {
  4519. $content = filterContent($content);
  4520. } elseif ($prompt) {
  4521. $content = filterContent($prompt);
  4522. } else {
  4523. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4524. }
  4525. // 构建消息
  4526. $messages = [
  4527. $this->sys_message,
  4528. [
  4529. 'role' => 'user',
  4530. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4531. ]
  4532. ];
  4533. $post_data = [
  4534. 'model' => $model,
  4535. 'messages' => $messages,
  4536. // 'max_tokens' => 8192,
  4537. 'temperature' => 0.7,
  4538. 'frequency_penalty' => 0,
  4539. 'presence_penalty' => 0,
  4540. 'thinking' => ['type' => $thinkingMode],
  4541. 'response_format' => ['type' => 'text'],
  4542. 'stream' => false
  4543. ];
  4544. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4545. // 根据模型类型选择调用方法
  4546. $fullContent = '';
  4547. $usage = [];
  4548. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4549. // DeepSeek 官方模型使用 DeepSeek API
  4550. $chatResult = $this->chatOnly($post_data);
  4551. } else if (in_array($model, $this->gpt_text_models)) {
  4552. // GPT-5.4 模型使用 TokenRouter API
  4553. $chatResult = $this->gpt54ChatOnly($post_data);
  4554. } else {
  4555. // 其他模型使用火山引擎API
  4556. $chatResult = $this->volcEngineChatCompletion($post_data);
  4557. }
  4558. if (is_array($chatResult)) {
  4559. $fullContent = $chatResult['fullContent'];
  4560. $usage = $chatResult['usage'];
  4561. }
  4562. $script_arr = [];
  4563. // 处理结果
  4564. if ($fullContent) {
  4565. $script_arr = extractScriptContent($fullContent);
  4566. }
  4567. // 返回前保存剧本内容
  4568. DB::table('mp_scripts')->where('id', $script_id)->update([
  4569. 'content' => $content,
  4570. 'updated_at' => date('Y-m-d H:i:s')
  4571. ]);
  4572. // 仅记录 token 使用明细(不扣积分)
  4573. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4574. 'model' => $model,
  4575. 'script_id' => $script_id,
  4576. 'source' => 'chatWithFile',
  4577. ], $model);
  4578. return [
  4579. 'script' => $script_arr,
  4580. 'answer' => $fullContent,
  4581. 'usage' => $usage
  4582. ];
  4583. }
  4584. public function getEpisodeContent($data) {
  4585. $group_id = getProp($data, 'group_id');
  4586. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4587. }
  4588. public function saveEpisodeContent($data) {
  4589. $script_id = getProp($data, 'script_id');
  4590. $group_id = getProp($data, 'group_id');
  4591. $start_episode_sequence = getProp($data, 'start_episode_number');
  4592. $end_episode_sequence = getProp($data, 'end_episode_number');
  4593. // 检查是否存在重叠的剧集序号范围
  4594. $exists_groups = DB::table('mp_script_episode_group')
  4595. ->where('script_id', $script_id)
  4596. ->where('id', '<>', $group_id) // 排除当前组
  4597. ->where('is_deleted', 0)
  4598. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4599. // 检查新范围是否与现有范围重叠
  4600. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4601. // 新范围的开始在现有范围内
  4602. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4603. ->where('end_episode_number', '>=', $start_episode_sequence);
  4604. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4605. // 新范围的结束在现有范围内
  4606. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4607. ->where('end_episode_number', '>=', $end_episode_sequence);
  4608. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4609. // 新范围完全包含现有范围
  4610. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4611. ->where('end_episode_number', '<=', $end_episode_sequence);
  4612. });
  4613. })
  4614. ->select('start_episode_number', 'end_episode_number')
  4615. ->get();
  4616. if ($exists_groups->isNotEmpty()) {
  4617. $conflict_ranges = [];
  4618. foreach ($exists_groups as $group) {
  4619. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4620. }
  4621. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4622. }
  4623. $episode_content = getProp($data, 'episode_content');
  4624. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4625. 'content' => $episode_content,
  4626. 'start_episode_number' => $start_episode_sequence,
  4627. 'end_episode_number' => $end_episode_sequence,
  4628. 'updated_at' => date('Y-m-d H:i:s')
  4629. ]);
  4630. $script_arr =getProp($data, 'script', []);
  4631. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4632. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4633. $script_id = getProp($data, 'script_id');
  4634. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4635. try {
  4636. DB::beginTransaction();
  4637. $update_data = [
  4638. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4639. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4640. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4641. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4642. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4643. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4644. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4645. 'status' => 3,
  4646. 'start_episode_sequence' => $start_episode_sequence,
  4647. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4648. 'episode_num' => count($script_arr['episodes']),
  4649. 'updated_at' => date('Y-m-d H:i:s')
  4650. ];
  4651. // 保存剧本内容
  4652. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4653. if (!$boolen) {
  4654. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4655. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4656. Utils::throwError('20003:剧本内容保存失败');
  4657. }
  4658. // 保存分集内容
  4659. // 删除历史分集内容
  4660. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4661. $episodes = [];
  4662. $sequence = 1;
  4663. foreach ($script_arr['episodes'] as $episode) {
  4664. $segment_number = 1;
  4665. foreach($episode['segments'] as $segment) {
  4666. $episodes[] = [
  4667. 'script_id' => $script_id,
  4668. 'episode_number' => $episode['episode_number'],
  4669. 'title' => $episode['title'],
  4670. // 'content' => $episode['content'],
  4671. 'content' => '',
  4672. 'segment_number' => $segment_number,
  4673. 'segment_content' => $segment['segment_content'],
  4674. 'sequence' => $sequence,
  4675. 'created_at' => date('Y-m-d H:i:s'),
  4676. 'updated_at' => date('Y-m-d H:i:s')
  4677. ];
  4678. $sequence++;
  4679. $segment_number++;
  4680. }
  4681. }
  4682. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4683. if (!$boolen2) {
  4684. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4685. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4686. Utils::throwError('20003:分集内容保存失败');
  4687. }
  4688. } catch (\Exception $e) {
  4689. DB::rollBack();
  4690. Utils::throwError('20003:'.$e->getMessage());
  4691. }
  4692. DB::commit();
  4693. return true;
  4694. }
  4695. public function getBookContent($data) {
  4696. $bid = getProp($data, 'bid');
  4697. $start_sequence = getProp($data, 'start_sequence');
  4698. $end_sequence = getProp($data, 'end_sequence');
  4699. $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])
  4700. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4701. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4702. return $return_content;
  4703. }
  4704. public function exportScript($data) {
  4705. $filename = getProp($data, 'filename');
  4706. $script_id = getProp($data, 'script_id');
  4707. $group_id = getProp($data, 'group_id');
  4708. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4709. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4710. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4711. $script = (array)$script;
  4712. // 获取分集组信息
  4713. if ($group_id) {
  4714. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4715. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4716. ->get()->map(function($value) {
  4717. return (array)$value;
  4718. })->toArray();
  4719. }else {
  4720. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4721. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4722. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4723. return (array)$value;
  4724. })->toArray();
  4725. }
  4726. if (!$groups) Utils::throwError('20003:分集不存在');
  4727. $script['group'] = $groups;
  4728. $export_type = getProp($data, 'export_type', 'txt');
  4729. // 生成文件名
  4730. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4731. // 根据导出类型生成不同格式的文件
  4732. switch ($export_type) {
  4733. case 'txt':
  4734. return $this->exportScriptAsTxt($script, $filename);
  4735. case 'pdf':
  4736. return $this->exportScriptAsPdf($script, $filename);
  4737. default:
  4738. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4739. }
  4740. }
  4741. /**
  4742. * 导出剧本为TXT格式
  4743. */
  4744. private function exportScriptAsTxt($script, $filename) {
  4745. // 构建TXT内容
  4746. $content = $this->buildScriptContent($script);
  4747. // 设置响应头,直接下载
  4748. header('Content-Type: text/plain; charset=utf-8');
  4749. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4750. header('Content-Length: ' . strlen($content));
  4751. // 输出内容并结束
  4752. echo $content;
  4753. exit();
  4754. }
  4755. /**
  4756. * 导出剧本为PDF格式
  4757. */
  4758. private function exportScriptAsPdf($script, $filename) {
  4759. // 使用HTML转PDF的方式来更好地支持中文
  4760. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4761. // 创建PDF实例
  4762. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4763. // 设置文档信息
  4764. $pdf->SetCreator('剧本导出系统');
  4765. $pdf->SetAuthor('系统');
  4766. $pdf->SetTitle($script['script_name']);
  4767. $pdf->SetSubject('剧本导出');
  4768. // 设置边距
  4769. $pdf->SetMargins(15, 15, 15);
  4770. $pdf->SetAutoPageBreak(TRUE, 15);
  4771. // 添加页面
  4772. $pdf->AddPage();
  4773. // 注册并使用 simsun.ttf 字体
  4774. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4775. // 使用HTML内容生成PDF
  4776. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4777. // 直接输出PDF文件供下载
  4778. header('Content-Type: application/pdf');
  4779. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4780. // 直接输出PDF内容
  4781. $pdf->Output($filename . '.pdf', 'D');
  4782. exit();
  4783. }
  4784. /**
  4785. * 构建用于PDF的HTML内容
  4786. */
  4787. private function buildScriptHtmlForPdf($script) {
  4788. $html = '<style>
  4789. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4790. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4791. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4792. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4793. .info { margin-bottom: 8px; }
  4794. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4795. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4796. .segment { margin-bottom: 10px; margin-left: 20px; }
  4797. .episode-content { white-space: pre-wrap; }
  4798. </style>';
  4799. // 标题
  4800. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4801. // 处理分组数据
  4802. if (!empty($script['group']) && is_array($script['group'])) {
  4803. $groups = (array)$script['group'];
  4804. foreach ($groups as $group) {
  4805. $html .= '<div class="group">';
  4806. // 分组标题
  4807. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4808. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4809. // 故事梗概
  4810. if (!empty($group['intro'])) {
  4811. $html .= '<h3>故事梗概</h3>';
  4812. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4813. }
  4814. // 剧本亮点
  4815. if (!empty($group['highlights'])) {
  4816. $html .= '<h3>剧本亮点</h3>';
  4817. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4818. }
  4819. // 人物关系
  4820. if (!empty($group['role_relationship'])) {
  4821. $html .= '<h3>人物关系</h3>';
  4822. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4823. }
  4824. // 核心矛盾
  4825. if (!empty($group['core_contradiction'])) {
  4826. $html .= '<h3>核心矛盾</h3>';
  4827. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4828. }
  4829. // 主体列表
  4830. if (!empty($group['roles']) && is_array($group['roles'])) {
  4831. $html .= '<h3>主体列表</h3>';
  4832. $html .= '<ul>';
  4833. foreach ($group['roles'] as $role) {
  4834. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4835. }
  4836. $html .= '</ul>';
  4837. }
  4838. // 美术风格
  4839. if (!empty($group['art_style'])) {
  4840. $html .= '<h3>美术风格</h3>';
  4841. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4842. }
  4843. // 场景列表
  4844. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4845. $html .= '<h3>场景列表</h3>';
  4846. $html .= '<ul>';
  4847. foreach ($group['scenes'] as $scene) {
  4848. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4849. }
  4850. $html .= '</ul>';
  4851. }
  4852. // 分集剧本
  4853. if (!empty($group['episode_content'])) {
  4854. $html .= '<h3>分集剧本</h3>';
  4855. // 去除零宽字符和其他不可见字符
  4856. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4857. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4858. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4859. }
  4860. $html .= '</div>';
  4861. }
  4862. }
  4863. return $html;
  4864. }
  4865. /**
  4866. * 构建PDF内容
  4867. */
  4868. private function buildPdfContent($pdf, $script) {
  4869. // 标题
  4870. $pdf->SetFont('dejavusans', 'B', 18);
  4871. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4872. $pdf->Ln(5);
  4873. // 基本信息
  4874. $pdf->SetFont('dejavusans', '', 12);
  4875. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4876. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4877. $pdf->Ln(5);
  4878. // 剧本简介
  4879. if (!empty($script['intro'])) {
  4880. $pdf->SetFont('dejavusans', 'B', 14);
  4881. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4882. $pdf->SetFont('dejavusans', '', 12);
  4883. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4884. $pdf->Ln(3);
  4885. }
  4886. // 亮点
  4887. if (!empty($script['highlights'])) {
  4888. $pdf->SetFont('dejavusans', 'B', 14);
  4889. $pdf->Cell(0, 10, '亮点', 0, 1);
  4890. $pdf->SetFont('dejavusans', '', 12);
  4891. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4892. $pdf->Ln(3);
  4893. }
  4894. // 核心矛盾
  4895. if (!empty($script['core_contradiction'])) {
  4896. $pdf->SetFont('dejavusans', 'B', 14);
  4897. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4898. $pdf->SetFont('dejavusans', '', 12);
  4899. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4900. $pdf->Ln(3);
  4901. }
  4902. // 艺术风格
  4903. if (!empty($script['art_style'])) {
  4904. $pdf->SetFont('dejavusans', 'B', 14);
  4905. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4906. $pdf->SetFont('dejavusans', '', 12);
  4907. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4908. $pdf->Ln(3);
  4909. }
  4910. // 备注
  4911. if (!empty($script['remark'])) {
  4912. $pdf->SetFont('dejavusans', 'B', 14);
  4913. $pdf->Cell(0, 10, '备注', 0, 1);
  4914. $pdf->SetFont('dejavusans', '', 12);
  4915. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4916. $pdf->Ln(3);
  4917. }
  4918. // 角色列表
  4919. if (!empty($script['roles']) && is_array($script['roles'])) {
  4920. $pdf->SetFont('dejavusans', 'B', 14);
  4921. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4922. $pdf->SetFont('dejavusans', '', 12);
  4923. foreach ($script['roles'] as $index => $role) {
  4924. if (is_array($role) || is_object($role)) {
  4925. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4926. } else {
  4927. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4928. }
  4929. }
  4930. $pdf->Ln(3);
  4931. }
  4932. // 角色关系
  4933. if (!empty($script['role_relationship'])) {
  4934. $pdf->SetFont('dejavusans', 'B', 14);
  4935. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4936. $pdf->SetFont('dejavusans', '', 12);
  4937. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4938. $pdf->Ln(3);
  4939. }
  4940. // 场景列表
  4941. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4942. $pdf->SetFont('dejavusans', 'B', 14);
  4943. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4944. $pdf->SetFont('dejavusans', '', 12);
  4945. foreach ($script['scenes'] as $index => $scene) {
  4946. if (is_array($scene) || is_object($scene)) {
  4947. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4948. } else {
  4949. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4950. }
  4951. }
  4952. $pdf->Ln(5);
  4953. }
  4954. // 分集内容
  4955. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4956. $pdf->SetFont('dejavusans', 'B', 16);
  4957. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4958. $pdf->Ln(3);
  4959. foreach ($script['episodes'] as $episode) {
  4960. // 检查是否需要新页面
  4961. if ($pdf->GetY() > 250) {
  4962. $pdf->AddPage();
  4963. }
  4964. $pdf->SetFont('dejavusans', 'B', 14);
  4965. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4966. if (!empty($episode['title'])) {
  4967. $episodeTitle .= ':' . $episode['title'];
  4968. }
  4969. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4970. // 处理分段内容
  4971. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4972. $pdf->SetFont('dejavusans', '', 12);
  4973. foreach ($episode['segments'] as $segment) {
  4974. if (!empty($segment['segment_content'])) {
  4975. // 如果有分段编号,显示分段标题
  4976. if (!empty($segment['segment_number'])) {
  4977. $pdf->SetFont('dejavusans', 'B', 12);
  4978. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4979. $pdf->SetFont('dejavusans', '', 12);
  4980. }
  4981. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4982. $pdf->Ln(2);
  4983. }
  4984. }
  4985. }
  4986. $pdf->Ln(5);
  4987. }
  4988. }
  4989. }
  4990. /**
  4991. * 构建剧本文本内容
  4992. */
  4993. private function buildScriptContent($script) {
  4994. $content = '';
  4995. $groups = $script['group'];
  4996. $groups = (array)$groups;
  4997. foreach ($groups as $group) {
  4998. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4999. // 剧本基本信息
  5000. if (!empty($group['intro'])) {
  5001. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5002. }
  5003. if (!empty($group['highlights'])) {
  5004. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5005. }
  5006. if (!empty($group['role_relationship'])) {
  5007. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5008. }
  5009. if (!empty($group['core_contradiction'])) {
  5010. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5011. }
  5012. if (!empty($group['roles']) && is_array($group['roles'])) {
  5013. $content .= "###主体列表\n";
  5014. foreach ($group['roles'] as $role) {
  5015. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5016. }
  5017. $content .= "\n\n";
  5018. }
  5019. if (!empty($group['art_style'])) {
  5020. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5021. }
  5022. // 场景信息
  5023. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5024. $content .= "###场景列表\n";
  5025. foreach ($group['scenes'] as $scene) {
  5026. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5027. }
  5028. $content .= "\n\n";
  5029. }
  5030. // 分集内容
  5031. if (!empty($group['episode_content'])) {
  5032. $content .= "###分集剧本\n";
  5033. $content .= $group['episode_content'];
  5034. // foreach ($script['episodes'] as $episode) {
  5035. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5036. // // if (!empty($episode['episode_name'])) {
  5037. // // $content .= ":" . $episode['episode_name'];
  5038. // // }
  5039. // // $content .= "\n";
  5040. // $content .= $episode['episode_content'] . "\n\n";
  5041. // }
  5042. }
  5043. }
  5044. return $content;
  5045. }
  5046. /**
  5047. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5048. *
  5049. * @param array $data 包含以下参数:
  5050. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5051. * - question: 用户问题(可选)
  5052. * - model: 使用的模型(r1 或 v3,默认 v3)
  5053. * @return \Generator 返回生成器,用于流式输出
  5054. */
  5055. public function addChat($data) {
  5056. $uid = Site::getUid();
  5057. $anime_id = getProp($data, 'anime_id');
  5058. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5059. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5060. if (!$anime) Utils::throwError('20003:对话不存在');
  5061. $file = getProp($data, 'file');
  5062. $content = getProp($data, 'content', '');
  5063. $bid = getProp($data, 'bid', 0);
  5064. $script_id = getProp($data, 'script_id', 0);
  5065. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5066. $prompt = getProp($data, 'prompt');
  5067. $user_anime_name = getProp($anime, 'anime_name');
  5068. // 处理文本模型
  5069. $model = getProp($data, 'model');
  5070. if (!$model) {
  5071. // 用户没有输入,从anime表获取
  5072. $model = getProp($anime, 'model');
  5073. if (!$model) {
  5074. // anime表也没有,使用默认值
  5075. $model = 'doubao-seed-2-0-mini-260215';
  5076. }
  5077. }
  5078. // 验证模型是否在可用模型表中
  5079. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5080. $model = 'doubao-seed-2-0-mini-260215';
  5081. }
  5082. $is_multi = getProp($anime, 'is_multi');
  5083. $is_single = (int)$is_multi !== 1;
  5084. // 积分余额预检(仅单剧集模式收费)
  5085. if ($is_single) {
  5086. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5087. }
  5088. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5089. if ($prompt) {
  5090. $question .= "本次修改要求如下:\n{$prompt}";
  5091. }
  5092. // if (!$file && !$content && !$bid) {
  5093. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5094. // }
  5095. // 提取文件内容
  5096. if ($file) {
  5097. $content = $this->extractFileContent($file);
  5098. if (!$content) {
  5099. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5100. }
  5101. } elseif ($script_id) {
  5102. $content = $this->getContentByScriptId($script_id);
  5103. if (!$content) {
  5104. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5105. }
  5106. } elseif ($bid) {
  5107. $content = $this->getContentByBid($bid);
  5108. if (!$content) {
  5109. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5110. }
  5111. } elseif ($content) {
  5112. $content = filterContent($content);
  5113. } else {
  5114. $content = getProp($anime, 'content');
  5115. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5116. $need_generate_content = true;
  5117. }
  5118. }
  5119. // 美术风格
  5120. $input_art_style = getProp($data, 'art_style');
  5121. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5122. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5123. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5124. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5125. 中年女:邻居阿姨
  5126. 老年男:幽默大爷
  5127. 老年女:婆婆
  5128. 萌娃:奶气萌娃";
  5129. // 判断是否需要生成原文内容
  5130. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5131. // 如果需要生成原文内容,添加额外的要求
  5132. $content_generation_requirement = $need_generate_content
  5133. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5134. : "";
  5135. // 美术风格
  5136. if (!$mappedArtStyle) {
  5137. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5138. }else {
  5139. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5140. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5141. }else {
  5142. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5143. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5144. }
  5145. }
  5146. $systemPrompt = $is_single
  5147. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5148. 强制要求:
  5149. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5150. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5151. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5152. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5153. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5154. 普通要求:
  5155. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5156. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5157. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5158. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5159. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5160. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5161. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5162. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5163. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5164. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5165. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5166. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5167. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5168. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5169. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5170. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5171. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5172. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5173. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5174. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5175. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5176. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5177. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5178. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5179. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5180. 5.{$mappedArtStyle_prompt}\n\n
  5181. 示例如下:\n
  5182. ###剧本名:西昆仑
  5183. ###故事梗概
  5184. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5185. ###剧本亮点
  5186. 亮点1:绝境奇药,生死一线
  5187. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5188. 亮点2:结拜兄妹,化解尴尬
  5189. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5190. 亮点3:纤发夺命,情愫暗涌
  5191. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5192. ###人物关系
  5193. 阿雪与梁萧之间存在兄妹之情。
  5194. ###核心矛盾
  5195. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5196. ###主体列表
  5197. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5198. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5199. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5200. 姿态:站立。}{{甜心小美}}
  5201. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5202. 全景,正面拍摄,青年女性,亚洲人。
  5203. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5204. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5205. 姿态:站立。}{{阳光青年}}
  5206. ###美术风格
  5207. 基础画风风格词:厚涂古风
  5208. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5209. ###场景列表
  5210. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5211. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5212. 无人物。}
  5213. ###分镜剧本
  5214. ##第1幕:徐家老旧厨房 白天 室内
  5215. 分镜1
  5216. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5217. 场景:徐家老旧厨房
  5218. 构图设计:全景,低角度仰视
  5219. 运镜调度:手持拍摄
  5220. 配音角色:旁白
  5221. 出镜角色:许芸-校服装、徐母
  5222. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5223. 画面类型:普通画面
  5224. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5225. 分镜2
  5226. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5227. 场景:徐家老旧厨房
  5228. 构图设计:近景,徐母面部特写
  5229. 运镜调度:固定镜头
  5230. 配音角色:徐母
  5231. 出镜角色:徐母
  5232. 台词内容:问我夜不归宿死哪儿去了。
  5233. 画面类型:对口型
  5234. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5235. ##第2幕:徐家简陋客厅 黄昏 室内
  5236. 分镜3
  5237. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5238. 场景:徐家简陋客厅
  5239. 构图设计:全景,景深虚化
  5240. 运镜调度:固定镜头
  5241. 配音角色:旁白
  5242. 出镜角色:无
  5243. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5244. 画面类型:普通画面
  5245. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5246. 分镜4
  5247. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5248. 场景:徐家简陋客厅
  5249. 构图设计:特写,火车票
  5250. 运镜调度:固定镜头
  5251. 配音角色:旁白
  5252. 出镜角色:无
  5253. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5254. 画面类型:普通画面
  5255. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5256. "
  5257. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5258. 强制要求:\n
  5259. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5260. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5261. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5262. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5263. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5264. 普通要求:\n
  5265. 1.剧本名(必须生成)必须与文档内容高度相关
  5266. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5267. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5268. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5269. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5270. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5271. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5272. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5273. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5274. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5275. 4.{$mappedArtStyle_prompt}\n\n
  5276. 示例如下:\n
  5277. ###剧本名:西昆仑
  5278. ###故事梗概
  5279. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5280. ###剧本亮点
  5281. 亮点1:绝境奇药,生死一线
  5282. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5283. 亮点2:结拜兄妹,化解尴尬
  5284. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5285. 亮点3:纤发夺命,情愫暗涌
  5286. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5287. ###人物关系
  5288. 阿雪与梁萧之间存在兄妹之情。
  5289. ###核心矛盾
  5290. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5291. ###主体列表
  5292. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5293. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5294. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5295. 姿态:站立。}{{甜心小美}}
  5296. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5297. 全景,正面拍摄,青年女性,亚洲人。
  5298. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5299. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5300. 姿态:站立。}{{阳光青年}}
  5301. ###美术风格
  5302. 基础画风风格词:厚涂古风
  5303. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5304. ###场景列表
  5305. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5306. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5307. 无人物。}";
  5308. // 构建消息
  5309. $messages = [
  5310. [
  5311. 'role' => 'system',
  5312. 'content' => $systemPrompt
  5313. ],
  5314. [
  5315. 'role' => 'user',
  5316. 'content' => "以下是文档内容:
  5317. {$content}
  5318. 用户问题:
  5319. {$question}"
  5320. ]
  5321. ];
  5322. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5323. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5324. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5325. if ($model === 'deepseek-chat') {
  5326. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5327. $model = 'deepseek-v4-flash';
  5328. $thinkingMode = 'disabled';
  5329. } elseif ($model === 'deepseek-reasoner') {
  5330. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5331. $model = 'deepseek-v4-flash';
  5332. $thinkingMode = 'enabled';
  5333. }
  5334. $post_data = [
  5335. 'model' => $model,
  5336. 'messages' => $messages,
  5337. // 'max_tokens' => 8192,
  5338. 'temperature' => 0.7,
  5339. 'frequency_penalty' => 0,
  5340. 'presence_penalty' => 0,
  5341. 'response_format' => ['type' => 'text'],
  5342. 'thinking' => ['type'=>$thinkingMode],
  5343. 'stream' => true // 启用流式输出
  5344. ];
  5345. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5346. // 根据模型类型选择调用方法
  5347. $fullContent = '';
  5348. $fullReasoningContent = '';
  5349. $usage = [];
  5350. try {
  5351. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5352. // DeepSeek 官方模型使用 DeepSeek API
  5353. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5354. } else if (in_array($model, $this->gpt_text_models)) {
  5355. // GPT-5.4 模型使用 TokenRouter API
  5356. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5357. } else if (in_array($model, $this->gemini_text_models)) {
  5358. // Gemini 模型使用 Gemini API
  5359. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5360. } else {
  5361. // 其他模型使用火山引擎API
  5362. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5363. }
  5364. // 验证返回值类型
  5365. if (!is_iterable($streamGenerator)) {
  5366. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5367. dLog('deepseek')->error('addChat流式生成器无效', [
  5368. 'generator_type' => $errorType,
  5369. 'model' => $model,
  5370. 'anime_id' => $anime_id
  5371. ]);
  5372. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5373. 'type' => $errorType,
  5374. 'model' => $model
  5375. ]);
  5376. yield [
  5377. 'type' => 'error',
  5378. 'script' => [],
  5379. 'episode' => [],
  5380. 'answer' => '',
  5381. 'reasoning' => '',
  5382. 'usage' => [],
  5383. 'error' => '接口返回数据异常,请重新请求'
  5384. ];
  5385. return;
  5386. }
  5387. // 处理流式输出
  5388. foreach ($streamGenerator as $chunk) {
  5389. if (isset($chunk['type'])) {
  5390. if ($chunk['type'] === 'done') {
  5391. // 最终结果
  5392. $fullContent = $chunk['full_content'];
  5393. $fullReasoningContent = $chunk['full_reasoning'];
  5394. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5395. } else {
  5396. // 逐块yield数据
  5397. yield $chunk;
  5398. }
  5399. }
  5400. }
  5401. } catch (\Exception $e) {
  5402. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5403. 'model' => $model,
  5404. 'anime_id' => $anime_id,
  5405. 'trace' => $e->getTraceAsString()
  5406. ]);
  5407. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5408. 'error' => $e->getMessage(),
  5409. 'model' => $model
  5410. ]);
  5411. yield [
  5412. 'type' => 'error',
  5413. 'script' => [],
  5414. 'episode' => [],
  5415. 'answer' => '',
  5416. 'reasoning' => '',
  5417. 'usage' => [],
  5418. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5419. ];
  5420. return;
  5421. }
  5422. dLog('deepseek')->info('完整内容: '.$fullContent);
  5423. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5424. // 处理完整内容并返回最终结果
  5425. $script_arr = [];
  5426. if ($fullContent) {
  5427. $script_arr = handleScriptContent($fullContent);
  5428. dLog('deepseek')->info('解析内容', $script_arr);
  5429. logDB('deepseek', 'info', '解析内容', $script_arr);
  5430. }
  5431. if (empty($script_arr['roles'])) {
  5432. // 未生成剧本相关内容,保存对话记录并返回提示
  5433. dLog('deepseek')->info('未生成剧本相关的内容');
  5434. try {
  5435. DB::beginTransaction();
  5436. $now = date('Y-m-d H:i:s');
  5437. // 保存对话记录
  5438. $records = [
  5439. [
  5440. 'uid' => $uid,
  5441. 'anime_id' => $anime_id,
  5442. 'sequence' => 0,
  5443. 'role' => 'user',
  5444. 'content' => $prompt,
  5445. 'created_at' => $now,
  5446. 'updated_at' => $now
  5447. ],
  5448. [
  5449. 'uid' => $uid,
  5450. 'anime_id' => $anime_id,
  5451. 'sequence' => 0,
  5452. 'role' => 'assistant',
  5453. // 'content' => $fullContent,
  5454. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5455. 'created_at' => $now,
  5456. 'updated_at' => $now
  5457. ]
  5458. ];
  5459. DB::table('mp_anime_records')->insert($records);
  5460. DB::commit();
  5461. } catch (\Exception $e) {
  5462. DB::rollBack();
  5463. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5464. }
  5465. yield [
  5466. 'type' => 'done',
  5467. 'script' => [],
  5468. 'episode' => [],
  5469. 'answer' => $fullContent,
  5470. 'reasoning' => $fullReasoningContent,
  5471. 'usage' => $usage,
  5472. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5473. ];
  5474. return;
  5475. }
  5476. // 如果需要生成原文内容,从script_arr中提取
  5477. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5478. $content = $script_arr['content'];
  5479. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5480. if (!$content) {
  5481. yield [
  5482. 'type' => 'done',
  5483. 'script' => [],
  5484. 'episode' => [],
  5485. 'answer' => $fullContent,
  5486. 'reasoning' => $fullReasoningContent,
  5487. 'usage' => $usage,
  5488. 'error' => '未生成剧本内容,请调整提示词再试'
  5489. ];
  5490. return;
  5491. }
  5492. }
  5493. // 替换美术风格
  5494. if ($mappedArtStyle !== '') {
  5495. $script_arr['art_style'] = $mappedArtStyle;
  5496. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5497. }
  5498. // 新建动漫
  5499. if ($user_anime_name == '新剧本策划') {
  5500. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5501. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5502. // if (!$anime_name) {
  5503. // // 未识别到剧本名,保存对话记录并返回提示
  5504. // dLog('deepseek')->info('未能识别到剧本名称');
  5505. // try {
  5506. // DB::beginTransaction();
  5507. // $now = date('Y-m-d H:i:s');
  5508. // // 保存对话记录
  5509. // $records = [
  5510. // [
  5511. // 'uid' => $uid,
  5512. // 'anime_id' => $anime_id,
  5513. // 'sequence' => 0,
  5514. // 'role' => 'user',
  5515. // 'content' => $prompt,
  5516. // 'created_at' => $now,
  5517. // 'updated_at' => $now
  5518. // ],
  5519. // [
  5520. // 'uid' => $uid,
  5521. // 'anime_id' => $anime_id,
  5522. // 'sequence' => 0,
  5523. // 'role' => 'assistant',
  5524. // 'content' => '未能生成剧本名称,请重试',
  5525. // 'created_at' => $now,
  5526. // 'updated_at' => $now
  5527. // ]
  5528. // ];
  5529. // DB::table('mp_anime_records')->insert($records);
  5530. // DB::commit();
  5531. // } catch (\Exception $e) {
  5532. // DB::rollBack();
  5533. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5534. // }
  5535. // yield [
  5536. // 'type' => 'done',
  5537. // 'script' => [],
  5538. // 'episode' => [],
  5539. // 'answer' => $fullContent,
  5540. // 'reasoning' => $fullReasoningContent,
  5541. // 'usage' => $usage,
  5542. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5543. // ];
  5544. // return;
  5545. // }
  5546. // 确认对话名称唯一性
  5547. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5548. $anime_name = $anime_name . '_' . date('YmdHis');
  5549. }
  5550. }else {
  5551. $anime_name = $user_anime_name;
  5552. }
  5553. $table_data = [
  5554. 'user_id' => $uid,
  5555. 'anime_name' => $anime_name,
  5556. 'model' => $model,
  5557. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5558. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5559. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5560. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5561. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5562. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5563. 'art_style_type' => $input_art_style,
  5564. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5565. 'status' => '解析完成',
  5566. 'content' => $content,
  5567. 'is_multi' => $is_multi,
  5568. 'ace_mode' => $ace_mode,
  5569. 'generate_status' => '待执行',
  5570. 'updated_at' => date('Y-m-d H:i:s')
  5571. ];
  5572. if ($table_data['content']) {
  5573. $chapters = splitContent($table_data['content']);
  5574. $chapter_count = count($chapters);
  5575. if ($chapter_count > 0) {
  5576. $table_data['start_episode_sequence'] = 1;
  5577. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5578. }
  5579. }
  5580. // 如果有剧本ID则进行绑定
  5581. if ($script_id) {
  5582. $table_data['script_id'] = $script_id;
  5583. }
  5584. $single_episode = [];
  5585. try {
  5586. DB::beginTransaction();
  5587. $now = date('Y-m-d H:i:s');
  5588. // 更新动漫大纲
  5589. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5590. if (!$boolen) {
  5591. dLog('deepseek')->info('动漫保存失败', $table_data);
  5592. Utils::throwError('20003:动漫保存失败');
  5593. }
  5594. // 保存对话记录
  5595. $records = [
  5596. [
  5597. 'uid' => $uid,
  5598. 'anime_id' => $anime_id,
  5599. 'sequence' => 0,
  5600. 'role' => 'user',
  5601. 'content' => $prompt,
  5602. 'created_at' => date('Y-m-d H:i:s'),
  5603. 'updated_at' => date('Y-m-d H:i:s')
  5604. ],
  5605. [
  5606. 'uid' => $uid,
  5607. 'anime_id' => $anime_id,
  5608. 'sequence' => 0,
  5609. 'role' => 'assistant',
  5610. 'content' => $fullContent,
  5611. 'created_at' => date('Y-m-d H:i:s'),
  5612. 'updated_at' => date('Y-m-d H:i:s')
  5613. ]
  5614. ];
  5615. // 保存对话记录
  5616. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5617. if (!$boolen3) {
  5618. Utils::throwError('20003:对话记录保存失败');
  5619. }
  5620. if ($is_single) {
  5621. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5622. if (empty($episode_arr['acts'])) {
  5623. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5624. }
  5625. $saveResult = $this->saveEpisodeVersionData(
  5626. $anime_id,
  5627. 1,
  5628. $episode_arr,
  5629. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5630. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5631. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5632. null,
  5633. null,
  5634. false,
  5635. $content,
  5636. $now
  5637. );
  5638. $single_episode = $saveResult['episode'];
  5639. $episode_id = $saveResult['episode_id'];
  5640. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5641. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5642. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5643. 'props' => json_encode($saveResult['merged_props'], 256),
  5644. 'updated_at' => $now
  5645. ]);
  5646. if ($boolen5 === false) {
  5647. Utils::throwError('20003:单剧集主表资源同步失败');
  5648. }
  5649. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5650. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5651. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5652. $episode_record_content = '确认分镜大纲';
  5653. if ($content !== '') {
  5654. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5655. }
  5656. $episode_records = [
  5657. [
  5658. 'uid' => $uid,
  5659. 'anime_id' => $anime_id,
  5660. 'role' => 'user',
  5661. 'content' => $episode_record_content,
  5662. 'sequence' => 1,
  5663. 'episode_id' => $episode_id,
  5664. 'created_at' => $now,
  5665. 'updated_at' => $now
  5666. ],
  5667. [
  5668. 'uid' => $uid,
  5669. 'anime_id' => $anime_id,
  5670. 'role' => 'assistant',
  5671. 'content' => $fullContent,
  5672. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5673. 'sequence' => 1,
  5674. 'episode_id' => $episode_id,
  5675. 'created_at' => $now,
  5676. 'updated_at' => $now
  5677. ]
  5678. ];
  5679. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5680. if (!$boolen4) {
  5681. Utils::throwError('20003:单剧集分镜记录保存失败');
  5682. }
  5683. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5684. if ($is_single && !empty($single_episode)) {
  5685. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5686. 'anime_id' => $anime_id,
  5687. 'episode_id' => $episode_id ?? 0,
  5688. 'model' => $model,
  5689. 'source' => 'addChat',
  5690. ]);
  5691. }
  5692. }
  5693. }catch (\Exception $e) {
  5694. DB::rollBack();
  5695. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5696. yield [
  5697. 'type' => 'done',
  5698. 'answer' => $fullContent,
  5699. 'reasoning' => $fullReasoningContent,
  5700. 'usage' => $usage,
  5701. 'error' => $e->getMessage(),
  5702. ];
  5703. return;
  5704. }
  5705. DB::commit();
  5706. dLog('deepseek')->info('保存完毕');
  5707. if ($is_single && !empty($single_episode)) {
  5708. // $this->batchSetGlobalRoleImg([
  5709. // 'anime_id' => $anime_id,
  5710. // ]);
  5711. // $this->batchSetGlobalSceneImg([
  5712. // 'anime_id' => $anime_id,
  5713. // ]);
  5714. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5715. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5716. }
  5717. $table_data['anime_id'] = $anime_id;
  5718. $table_data['roles'] = json_decode($table_data['roles'], true);
  5719. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5720. // $table_data['episodes'] = $script_arr['episodes'];
  5721. unset($table_data['created_at']);
  5722. unset($table_data['updated_at']);
  5723. unset($table_data['status']);
  5724. dLog('deepseek')->info('开始返回');
  5725. yield [
  5726. 'type' => 'done',
  5727. 'script' => $table_data,
  5728. 'episode' => $single_episode,
  5729. 'answer' => $fullContent,
  5730. 'reasoning' => $fullReasoningContent,
  5731. 'usage' => $usage
  5732. ];
  5733. }
  5734. public function reGenerateAnime($data) {
  5735. $uid = Site::getUid();
  5736. $file = getProp($data, 'file');
  5737. $content = getProp($data, 'content', '');
  5738. $bid = getProp($data, 'bid', 0);
  5739. $script_id = getProp($data, 'script_id', 0);
  5740. $anime_id = getProp($data, 'anime_id');
  5741. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5742. if (!$anime) {
  5743. Utils::throwError('20003:该对话不存在');
  5744. }
  5745. $user_anime_name = getProp($anime, 'anime_name');
  5746. $prompt = getProp($data, 'prompt');
  5747. // 处理文本模型
  5748. $model = getProp($data, 'model');
  5749. if (!$model) {
  5750. // 用户没有输入,从anime表获取
  5751. $model = getProp($anime, 'model');
  5752. if (!$model) {
  5753. // anime表也没有,使用默认值
  5754. $model = 'doubao-seed-2-0-mini-260215';
  5755. }
  5756. }
  5757. // 验证模型是否在可用模型表中
  5758. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5759. $model = 'doubao-seed-2-0-mini-260215';
  5760. }
  5761. $is_multi = getProp($anime, 'is_multi', 1);
  5762. $is_single = (int)$is_multi !== 1;
  5763. // 积分余额预检(仅单剧集模式收费)
  5764. if ($is_single) {
  5765. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5766. }
  5767. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5768. if ($is_single) {
  5769. $episode_exists = DB::table('mp_anime_episodes')
  5770. ->where('anime_id', $anime_id)
  5771. ->where('sequence', 1)
  5772. ->exists();
  5773. if ($episode_exists) {
  5774. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5775. }
  5776. }
  5777. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5778. if ($prompt) {
  5779. $question .= "本次修改要求如下:\n{$prompt}";
  5780. }
  5781. // 提取文件内容
  5782. if ($file) {
  5783. $content = $this->extractFileContent($file);
  5784. if (!$content) {
  5785. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5786. }
  5787. } elseif ($script_id) {
  5788. $content = $this->getContentByScriptId($script_id);
  5789. if (!$content) {
  5790. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5791. }
  5792. } elseif ($bid) {
  5793. $content = $this->getContentByBid($bid);
  5794. if (!$content) {
  5795. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5796. }
  5797. } elseif ($content) {
  5798. $content = filterContent($content);
  5799. }else {
  5800. $content = filterContent(getProp($anime, 'content'));
  5801. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5802. $need_generate_content = true;
  5803. }
  5804. }
  5805. // 判断是否需要生成原文内容
  5806. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5807. // 如果需要生成原文内容,添加额外的要求
  5808. $content_generation_requirement = $need_generate_content
  5809. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5810. : "";
  5811. // 美术风格
  5812. $input_art_style = getProp($anime, 'art_style');
  5813. if (!$input_art_style) {
  5814. $input_art_style = getProp($data, 'art_style');
  5815. }
  5816. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5817. // 美术风格
  5818. if (!$mappedArtStyle) {
  5819. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5820. }else {
  5821. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5822. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5823. }else {
  5824. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5825. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5826. }
  5827. }
  5828. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5829. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5830. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5831. 中年女:邻居阿姨
  5832. 老年男:幽默大爷
  5833. 老年女:婆婆
  5834. 萌娃:奶气萌娃";
  5835. $system_message = ['role'=>'system', 'content'=>$is_single
  5836. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5837. 强制要求:
  5838. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5839. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5840. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5841. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5842. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5843. 普通要求:
  5844. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5845. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5846. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5847. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5848. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5849. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5850. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5851. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5852. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5853. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5854. 3.$mappedArtStyle_prompt\n\n
  5855. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5856. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5857. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5858. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5859. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5860. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5861. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5862. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5863. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5864. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5865. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5866. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5867. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5868. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5869. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5870. 示例如下:\n
  5871. ###剧本名:西昆仑
  5872. ###故事梗概
  5873. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5874. ###剧本亮点
  5875. 亮点1:绝境奇药,生死一线
  5876. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5877. 亮点2:结拜兄妹,化解尴尬
  5878. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5879. 亮点3:纤发夺命,情愫暗涌
  5880. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5881. ###人物关系
  5882. 阿雪与梁萧之间存在兄妹之情。
  5883. ###核心矛盾
  5884. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5885. ###主体列表
  5886. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5887. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5888. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5889. 姿态:站立。}{{甜心小美}}
  5890. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5891. 全景,正面拍摄,青年女性,亚洲人。
  5892. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5893. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5894. 姿态:站立。}{{阳光青年}}
  5895. ###美术风格
  5896. 基础画风风格词:厚涂古风
  5897. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5898. ###场景列表
  5899. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5900. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5901. 无人物。}
  5902. ###分镜剧本
  5903. ##第1幕:徐家老旧厨房 白天 室内
  5904. 分镜1
  5905. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5906. 场景:徐家老旧厨房
  5907. 构图设计:全景,低角度仰视
  5908. 运镜调度:手持拍摄
  5909. 配音角色:旁白
  5910. 出镜角色:许芸-校服装、徐母
  5911. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5912. 画面类型:普通画面
  5913. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5914. 分镜2
  5915. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5916. 场景:徐家老旧厨房
  5917. 构图设计:近景,徐母面部特写
  5918. 运镜调度:固定镜头
  5919. 配音角色:徐母
  5920. 出镜角色:徐母
  5921. 台词内容:问我夜不归宿死哪儿去了。
  5922. 画面类型:对口型
  5923. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5924. ##第2幕:徐家简陋客厅 黄昏 室内
  5925. 分镜3
  5926. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5927. 场景:徐家简陋客厅
  5928. 构图设计:全景,景深虚化
  5929. 运镜调度:固定镜头
  5930. 配音角色:旁白
  5931. 出镜角色:无
  5932. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5933. 画面类型:普通画面
  5934. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5935. 分镜4
  5936. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5937. 场景:徐家简陋客厅
  5938. 构图设计:特写,火车票
  5939. 运镜调度:固定镜头
  5940. 配音角色:旁白
  5941. 出镜角色:无
  5942. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5943. 画面类型:普通画面
  5944. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5945. "
  5946. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5947. 强制要求:\n
  5948. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5949. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5950. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5951. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5952. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5953. 普通要求:\n
  5954. 1.剧本名(必须生成)必须与文档内容高度相关
  5955. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5956. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5957. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5958. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5959. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5960. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5961. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5962. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5963. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5964. 4.$mappedArtStyle_prompt\n\n
  5965. 示例如下:\n
  5966. ###剧本名:西昆仑
  5967. ###故事梗概
  5968. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5969. ###剧本亮点
  5970. 亮点1:绝境奇药,生死一线
  5971. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5972. 亮点2:结拜兄妹,化解尴尬
  5973. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5974. 亮点3:纤发夺命,情愫暗涌
  5975. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5976. ###人物关系
  5977. 阿雪与梁萧之间存在兄妹之情。
  5978. ###核心矛盾
  5979. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5980. ###主体列表
  5981. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5982. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5983. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5984. 姿态:站立。}{{甜心小美}}
  5985. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5986. 全景,正面拍摄,青年女性,亚洲人。
  5987. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5988. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5989. 姿态:站立。}{{阳光青年}}
  5990. ###美术风格
  5991. 基础画风风格词:厚涂古风
  5992. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5993. ###场景列表
  5994. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5995. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5996. 无人物。}"];
  5997. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5998. $episode_count = $this->extractEpisodeNumber($prompt);
  5999. if ((int)getProp($anime, 'is_multi') !== 1) {
  6000. yield [
  6001. 'type' => 'done',
  6002. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6003. 'reasoning' => '',
  6004. 'usage' => []
  6005. ];
  6006. return;
  6007. }
  6008. if ($episode_count) {
  6009. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6010. $system_message = [
  6011. 'role' => 'system',
  6012. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6013. 强制要求:\n
  6014. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6015. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6016. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6017. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6018. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6019. 普通要求:\n
  6020. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6021. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6022. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6023. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6024. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6025. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6026. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6027. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6028. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6029. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6030. 示例如下:\n
  6031. ###剧本名:西昆仑
  6032. ###故事梗概
  6033. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6034. ###剧本亮点
  6035. 亮点1:绝境奇药,生死一线
  6036. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6037. 亮点2:结拜兄妹,化解尴尬
  6038. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6039. 亮点3:纤发夺命,情愫暗涌
  6040. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6041. ###人物关系
  6042. 阿雪与梁萧之间存在兄妹之情。
  6043. ###核心矛盾
  6044. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6045. ###主体列表
  6046. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6047. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6048. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6049. 姿态:站立。}{{甜心小美}}
  6050. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6051. 全景,正面拍摄,青年女性,亚洲人。
  6052. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6053. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6054. 姿态:站立。}{{阳光青年}}
  6055. ###美术风格
  6056. 基础画风风格词:厚涂古风
  6057. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6058. ###场景列表
  6059. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6060. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6061. 无人物。}
  6062. ###分集详细内容
  6063. ##第1章 重生
  6064. 我重生了。
  6065. 源于一个男人偏执的暗恋。
  6066. ##第2章 相救
  6067. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6068. 我眼睛扫向站在锅炉后的卞大伟。"
  6069. ];
  6070. // 构建消息
  6071. $messages = [
  6072. $system_message,
  6073. [
  6074. 'role' => 'user',
  6075. 'content' => "以下是文档内容:
  6076. {$content}
  6077. 用户问题:
  6078. {$question}"
  6079. ]
  6080. ];
  6081. }else {
  6082. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6083. // 构建消息
  6084. $messages = [
  6085. $system_message,
  6086. [
  6087. 'role' => 'user',
  6088. 'content' => "以下是文档内容:
  6089. {$content}
  6090. 用户问题:
  6091. {$question}"
  6092. ]
  6093. ];
  6094. }else {
  6095. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6096. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6097. return (array)$value;
  6098. })->toArray();
  6099. array_unshift($messages, $system_message);
  6100. $messages[] = [
  6101. 'role' => 'user',
  6102. 'content' => $prompt
  6103. ];
  6104. }
  6105. }
  6106. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6107. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6108. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6109. if ($model === 'deepseek-chat') {
  6110. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6111. $model = 'deepseek-v4-flash';
  6112. $thinkingMode = 'disabled';
  6113. } elseif ($model === 'deepseek-reasoner') {
  6114. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6115. $model = 'deepseek-v4-flash';
  6116. $thinkingMode = 'enabled';
  6117. }
  6118. $post_data = [
  6119. 'model' => $model,
  6120. 'messages' => $messages,
  6121. // 'max_tokens' => 8192,
  6122. 'temperature' => 0.7,
  6123. 'frequency_penalty' => 0,
  6124. 'presence_penalty' => 0,
  6125. 'response_format' => ['type' => 'text'],
  6126. 'thinking' => ['type' => $thinkingMode],
  6127. 'stream' => true // 启用流式输出
  6128. ];
  6129. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6130. // 根据模型类型选择调用方法
  6131. $fullContent = '';
  6132. $fullReasoningContent = '';
  6133. $usage = [];
  6134. // dd($post_data);
  6135. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6136. try {
  6137. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6138. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6139. } else if (in_array($model, $this->gpt_text_models)) {
  6140. // GPT-5.4 模型使用 TokenRouter API
  6141. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6142. } else if (in_array($model, $this->gemini_text_models)) {
  6143. // Gemini 模型使用 Gemini API
  6144. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6145. } else {
  6146. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6147. }
  6148. // 验证返回值类型
  6149. if (!is_iterable($streamGenerator)) {
  6150. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6151. dLog('deepseek')->error('方法名流式生成器无效', [
  6152. 'generator_type' => $errorType,
  6153. 'model' => $model,
  6154. // 添加其他上下文信息
  6155. ]);
  6156. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6157. 'type' => $errorType,
  6158. 'model' => $model
  6159. ]);
  6160. yield [
  6161. 'type' => 'error',
  6162. // 根据方法返回相应的空数据结构
  6163. 'answer' => '',
  6164. 'reasoning' => '',
  6165. 'usage' => [],
  6166. 'error' => '接口返回数据异常,请重新请求'
  6167. ];
  6168. return;
  6169. }
  6170. // 处理流式输出
  6171. foreach ($streamGenerator as $chunk) {
  6172. if (isset($chunk['type'])) {
  6173. if ($chunk['type'] === 'done') {
  6174. $fullContent = $chunk['full_content'];
  6175. $fullReasoningContent = $chunk['full_reasoning'];
  6176. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6177. } else {
  6178. yield $chunk;
  6179. }
  6180. }
  6181. }
  6182. } catch (\Exception $e) {
  6183. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6184. 'model' => $model,
  6185. 'trace' => $e->getTraceAsString()
  6186. ]);
  6187. logDB('deepseek', 'error', '方法名流式处理失败', [
  6188. 'error' => $e->getMessage(),
  6189. 'model' => $model
  6190. ]);
  6191. yield [
  6192. 'type' => 'error',
  6193. // 根据方法返回相应的空数据结构
  6194. 'answer' => '',
  6195. 'reasoning' => '',
  6196. 'usage' => [],
  6197. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6198. ];
  6199. return;
  6200. }
  6201. dLog('deepseek')->info('完整内容: '.$fullContent);
  6202. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6203. // 处理完整内容并返回最终结果
  6204. $script_arr = [];
  6205. if ($fullContent) {
  6206. $script_arr = handleScriptContent($fullContent);
  6207. dLog('deepseek')->info('解析内容', $script_arr);
  6208. logDB('deepseek', 'info', '解析内容', $script_arr);
  6209. }
  6210. if (empty($script_arr['roles'])) {
  6211. // 未生成剧本相关内容,保存对话记录并返回提示
  6212. dLog('deepseek')->info('未生成剧本相关的内容');
  6213. try {
  6214. $now = date('Y-m-d H:i:s');
  6215. // 保存对话记录
  6216. $records = [
  6217. [
  6218. 'uid' => $uid,
  6219. 'anime_id' => $anime_id,
  6220. 'sequence' => 0,
  6221. 'role' => 'user',
  6222. 'content' => $prompt,
  6223. 'created_at' => $now,
  6224. 'updated_at' => $now
  6225. ],
  6226. [
  6227. 'uid' => $uid,
  6228. 'anime_id' => $anime_id,
  6229. 'sequence' => 0,
  6230. 'role' => 'assistant',
  6231. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6232. 'created_at' => $now,
  6233. 'updated_at' => $now
  6234. ]
  6235. ];
  6236. DB::table('mp_anime_records')->insert($records);
  6237. } catch (\Exception $e) {
  6238. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6239. }
  6240. yield [
  6241. 'type' => 'done',
  6242. 'script' => [],
  6243. 'episode' => [],
  6244. 'answer' => $fullContent,
  6245. 'reasoning' => $fullReasoningContent,
  6246. 'usage' => $usage,
  6247. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6248. ];
  6249. return;
  6250. }
  6251. // 替换美术风格
  6252. if ($mappedArtStyle !== '') {
  6253. $script_arr['art_style'] = $mappedArtStyle;
  6254. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6255. }
  6256. if ($user_anime_name != '新剧本策划') {
  6257. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6258. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6259. // 确认对话名称唯一性
  6260. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6261. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6262. }
  6263. }else {
  6264. $anime_name = $user_anime_name;
  6265. }
  6266. $table_data = [
  6267. 'user_id' => $uid,
  6268. 'model' => $model,
  6269. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6270. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6271. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6272. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6273. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6274. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6275. 'art_style_type' => $input_art_style,
  6276. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6277. 'status' => '解析完成',
  6278. 'generate_status' => '待执行',
  6279. 'updated_at' => date('Y-m-d H:i:s')
  6280. ];
  6281. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6282. // 如果是修改集数,则将content内容更新(会改变原文)
  6283. if (isset($episode_count) && $episode_count > 0) {
  6284. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6285. $table_data['start_episode_sequence'] = 1;
  6286. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6287. }else {
  6288. // 如果需要生成原文内容,从script_arr中提取
  6289. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6290. $table_data['content'] = $script_arr['content'];
  6291. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6292. if (!$table_data['content']) {
  6293. yield [
  6294. 'type' => 'done',
  6295. 'script' => [],
  6296. 'episode' => [],
  6297. 'answer' => $fullContent,
  6298. 'reasoning' => $fullReasoningContent,
  6299. 'usage' => $usage,
  6300. 'error' => '未生成剧本内容,请调整提示词再试'
  6301. ];
  6302. return;
  6303. }
  6304. }
  6305. if (isset($table_data['content']) && $table_data['content']) {
  6306. $chapters = splitContent($table_data['content']);
  6307. $chapter_count = count($chapters);
  6308. if ($chapter_count > 0) {
  6309. $table_data['start_episode_sequence'] = 1;
  6310. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6311. }
  6312. }
  6313. }
  6314. $single_episode = [];
  6315. try {
  6316. DB::beginTransaction();
  6317. $now = date('Y-m-d H:i:s');
  6318. // 更新动漫大纲
  6319. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6320. if (!$boolen) {
  6321. dLog('deepseek')->info('对话修改失败', $table_data);
  6322. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6323. Utils::throwError('20003:对话修改失败');
  6324. }
  6325. // 保存对话记录
  6326. $records = [
  6327. [
  6328. 'uid' => $uid,
  6329. 'anime_id' => $anime_id,
  6330. 'sequence' => 0,
  6331. 'role' => 'user',
  6332. 'content' => $prompt,
  6333. 'created_at' => $now,
  6334. 'updated_at' => $now
  6335. ],
  6336. [
  6337. 'uid' => $uid,
  6338. 'anime_id' => $anime_id,
  6339. 'sequence' => 0,
  6340. 'role' => 'assistant',
  6341. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6342. 'content' => $fullContent,
  6343. 'created_at' => $now,
  6344. 'updated_at' => $now
  6345. ]
  6346. ];
  6347. // 保存对话记录
  6348. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6349. if (!$boolen3) {
  6350. Utils::throwError('20003:对话记录保存失败');
  6351. }
  6352. // 单剧集模式:生成并保存剧集信息
  6353. if ($is_single) {
  6354. $anime_name = getProp($anime, 'anime_name', '未命名');
  6355. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6356. if (empty($episode_arr['acts'])) {
  6357. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6358. }
  6359. $saveResult = $this->saveEpisodeVersionData(
  6360. $anime_id,
  6361. 1,
  6362. $episode_arr,
  6363. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6364. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6365. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6366. null,
  6367. null,
  6368. false,
  6369. $content,
  6370. $now
  6371. );
  6372. $single_episode = $saveResult['episode'];
  6373. $episode_id = $saveResult['episode_id'];
  6374. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6375. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6376. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6377. 'props' => json_encode($saveResult['merged_props'], 256),
  6378. 'updated_at' => $now
  6379. ]);
  6380. if ($boolen5 === false) {
  6381. Utils::throwError('20003:单剧集主表资源同步失败');
  6382. }
  6383. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6384. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6385. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6386. $episode_record_content = '确认分镜大纲';
  6387. if ($content !== '') {
  6388. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6389. }
  6390. $episode_records = [
  6391. [
  6392. 'uid' => $uid,
  6393. 'anime_id' => $anime_id,
  6394. 'role' => 'user',
  6395. 'content' => $episode_record_content,
  6396. 'sequence' => 1,
  6397. 'episode_id' => $episode_id,
  6398. 'created_at' => $now,
  6399. 'updated_at' => $now
  6400. ],
  6401. [
  6402. 'uid' => $uid,
  6403. 'anime_id' => $anime_id,
  6404. 'role' => 'assistant',
  6405. 'content' => $fullContent,
  6406. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6407. 'sequence' => 1,
  6408. 'episode_id' => $episode_id,
  6409. 'created_at' => $now,
  6410. 'updated_at' => $now
  6411. ]
  6412. ];
  6413. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6414. if (!$boolen4) {
  6415. Utils::throwError('20003:单剧集分镜记录保存失败');
  6416. }
  6417. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6418. if ($is_single && !empty($single_episode)) {
  6419. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6420. 'anime_id' => $anime_id,
  6421. 'episode_id' => $episode_id ?? 0,
  6422. 'model' => $model,
  6423. 'source' => 'reGenerateAnime',
  6424. ]);
  6425. }
  6426. }
  6427. }catch (\Exception $e) {
  6428. DB::rollBack();
  6429. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6430. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6431. yield [
  6432. 'type' => 'done',
  6433. 'answer' => $fullContent,
  6434. 'reasoning' => $fullReasoningContent,
  6435. 'usage' => $usage,
  6436. 'error' => $e->getMessage(),
  6437. ];
  6438. return;
  6439. }
  6440. DB::commit();
  6441. dLog('deepseek')->info('保存完毕');
  6442. if ($is_single && !empty($single_episode)) {
  6443. // $this->batchSetGlobalRoleImg([
  6444. // 'anime_id' => $anime_id,
  6445. // ]);
  6446. // $this->batchSetGlobalSceneImg([
  6447. // 'anime_id' => $anime_id,
  6448. // ]);
  6449. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6450. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6451. }
  6452. $table_data['anime_id'] = $anime_id;
  6453. $table_data['roles'] = json_decode($table_data['roles'], true);
  6454. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6455. unset($table_data['updated_at']);
  6456. unset($table_data['status']);
  6457. yield [
  6458. 'type' => 'done',
  6459. 'script' => $table_data,
  6460. 'episode' => $single_episode,
  6461. 'answer' => $fullContent,
  6462. 'reasoning' => $fullReasoningContent,
  6463. 'usage' => $usage
  6464. ];
  6465. }
  6466. public function chat($data) {
  6467. $uid = Site::getUid();
  6468. // 积分余额预检(不足直接报错)
  6469. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6470. $anime_id = getProp($data, 'anime_id');
  6471. $file = getProp($data, 'file');
  6472. $content = getProp($data, 'content', '');
  6473. $bid = getProp($data, 'bid', 0);
  6474. $script_id = getProp($data, 'script_id', 0);
  6475. $episode_number = getProp($data, 'episode_number', 1);
  6476. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6477. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6478. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6479. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6480. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6481. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6482. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6483. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6484. $roles = is_array($roles) ? $roles : [];
  6485. $scenes = is_array($scenes) ? $scenes : [];
  6486. // 获取最后一集序号
  6487. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6488. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6489. // 转换主体列表和场景列表的格式
  6490. // 获取参考主体或场景
  6491. if ((int)$episode_number === 1) {
  6492. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6493. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6494. }else {
  6495. $prev_episode_number = $episode_number - 1;
  6496. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6497. }
  6498. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6499. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6500. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6501. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6502. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6503. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6504. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6505. 中年女:邻居阿姨
  6506. 老年男:幽默大爷
  6507. 老年女:婆婆
  6508. 萌娃:奶气萌娃";
  6509. if ($roles_content) {
  6510. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6511. 主体范围:\n {$roles_content}\n
  6512. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6513. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6514. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6515. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6516. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6517. }else {
  6518. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6519. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6520. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6521. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6522. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6523. }
  6524. if ($scenes_content) {
  6525. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6526. 场景范围:\n {$scenes_content}\n
  6527. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6528. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6529. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6530. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6531. }else {
  6532. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6533. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6534. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6535. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6536. }
  6537. // 提取文件内容
  6538. if ($file) {
  6539. $uploaded_content = $this->extractFileContent($file);
  6540. if (!$uploaded_content) {
  6541. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6542. }
  6543. } elseif ($script_id) {
  6544. $uploaded_content = $this->getContentByScriptId($script_id);
  6545. if (!$uploaded_content) {
  6546. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6547. }
  6548. } elseif ($bid) {
  6549. $uploaded_content = $this->getContentByBid($bid);
  6550. if (!$uploaded_content) {
  6551. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6552. }
  6553. } elseif ($content) {
  6554. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6555. }
  6556. // elseif ($prompt) {
  6557. // $uploaded_content = filterContent($prompt);
  6558. // }
  6559. else {
  6560. $uploaded_content = '';
  6561. }
  6562. $input_art_style = getProp($anime, 'art_style');
  6563. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6564. // 美术风格
  6565. if (!$mappedArtStyle) {
  6566. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6567. }else {
  6568. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6569. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6570. }else {
  6571. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6572. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6573. }
  6574. }
  6575. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6576. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6577. // 强制要求:
  6578. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6579. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6580. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6581. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6582. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6583. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6584. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6585. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6586. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6587. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6588. // - 分镜要和场景列表、人物主体保持一致\n
  6589. // 普通要求:
  6590. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6591. // {$role_demo}
  6592. // {$scene_demo}
  6593. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6594. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6595. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6596. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6597. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6598. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6599. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6600. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6601. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6602. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6603. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6604. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6605. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6606. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6607. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6608. // 5.$mappedArtStyle_prompt\n\n
  6609. // 示例格式:\n
  6610. // 第1集:隐形的守护者
  6611. // ###故事梗概
  6612. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6613. // ###美术风格
  6614. // 基础画风风格词:韩漫二次元
  6615. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6616. // ###主体列表
  6617. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6618. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6619. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6620. // ###场景列表
  6621. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6622. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6623. // 无人物。}
  6624. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6625. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6626. // 无人物。}
  6627. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6628. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6629. // 无人物。}
  6630. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6631. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6632. // 无人物。}
  6633. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6634. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6635. // 无人物。}
  6636. // ###分镜剧本
  6637. // ##第1幕:徐家老旧厨房 白天 室内
  6638. // 分镜1
  6639. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6640. // 场景:徐家老旧厨房
  6641. // 构图设计:全景,低角度仰视
  6642. // 运镜调度:手持拍摄
  6643. // 配音角色:旁白
  6644. // 出镜角色:许芸-校服装、徐母
  6645. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6646. // 画面类型:普通画面
  6647. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6648. // 分镜2
  6649. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6650. // 场景:徐家老旧厨房
  6651. // 构图设计:近景,徐母面部特写
  6652. // 运镜调度:固定镜头
  6653. // 配音角色:徐母
  6654. // 出镜角色:徐母
  6655. // 台词内容:问我夜不归宿死哪儿去了。
  6656. // 画面类型:对口型
  6657. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6658. // ##第2幕:徐家简陋客厅 黄昏 室内
  6659. // 分镜3
  6660. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6661. // 场景:徐家简陋客厅
  6662. // 构图设计:全景,景深虚化
  6663. // 运镜调度:固定镜头
  6664. // 配音角色:旁白
  6665. // 出镜角色:无
  6666. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6667. // 画面类型:普通画面
  6668. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6669. // 分镜4
  6670. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6671. // 场景:徐家简陋客厅
  6672. // 构图设计:特写,火车票
  6673. // 运镜调度:固定镜头
  6674. // 配音角色:旁白
  6675. // 出镜角色:无
  6676. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6677. // 画面类型:普通画面
  6678. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6679. // \n\n";
  6680. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6681. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6682. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6683. 普通要求:
  6684. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6685. {$role_demo}
  6686. {$scene_demo}
  6687. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6688. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6689. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6690. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6691. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6692. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6693. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6694. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6695. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6696. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6697. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6698. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6699. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6700. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6701. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6702. 5.$mappedArtStyle_prompt
  6703. 6.《情绪-视听语言映射表》:
  6704. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6705. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6706. -----|---------|------------|----------------
  6707. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6708. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6709. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6710. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6711. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6712. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6713. -----|---------|------------|----------------
  6714. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6715. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6716. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6717. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6718. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6719. --------|---------|--------------|-------------
  6720. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6721. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6722. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6723. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6724. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6725. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6726. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6727. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6728. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6729. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6730. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6731. -----|---------|------------|------------
  6732. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6733. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6734. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6735. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6736. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6737. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6738. --------|---------|--------------|----------
  6739. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6740. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6741. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6742. 6.6 声音设计与潜意识影响 (Soundscape)
  6743. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6744. -----|---------|------------|------------------
  6745. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6746. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6747. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6748. 理论基石:
  6749. - The Five C's of Cinematography by Joseph V. Mascelli
  6750. - Film Art: An Introduction by David Bordwell
  6751. - Sight, Sound, Motion by Herbert Zettl
  6752. - Notes on the Cinematograph by Robert Bresson
  6753. \n\n
  6754. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6755. 示例格式:\n
  6756. 第1集:隐形的守护者
  6757. ###故事梗概
  6758. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6759. ###美术风格
  6760. 基础画风风格词:韩漫二次元
  6761. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6762. ###主体列表
  6763. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6764. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6765. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6766. ###场景列表
  6767. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6768. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6769. 无人物。}
  6770. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6771. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6772. 无人物。}
  6773. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6774. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6775. 无人物。}
  6776. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6777. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6778. 无人物。}
  6779. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6780. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6781. 无人物。}
  6782. ###分镜剧本
  6783. ##第1幕:徐家老旧厨房 白天 室内
  6784. 分镜1
  6785. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6786. 场景:徐家老旧厨房
  6787. 构图设计:全景,低角度仰视
  6788. 运镜调度:手持拍摄
  6789. 配音角色:旁白
  6790. 出镜角色:许芸-校服装、徐母
  6791. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6792. 画面类型:普通画面
  6793. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6794. 分镜2
  6795. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6796. 场景:徐家老旧厨房
  6797. 构图设计:近景,徐母面部特写
  6798. 运镜调度:固定镜头
  6799. 配音角色:徐母
  6800. 出镜角色:徐母
  6801. 台词内容:问我夜不归宿死哪儿去了。
  6802. 画面类型:对口型
  6803. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6804. ##第2幕:徐家简陋客厅 黄昏 室内
  6805. 分镜3
  6806. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6807. 场景:徐家简陋客厅
  6808. 构图设计:全景,景深虚化
  6809. 运镜调度:固定镜头
  6810. 配音角色:旁白
  6811. 出镜角色:无
  6812. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6813. 画面类型:普通画面
  6814. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6815. 分镜4
  6816. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6817. 场景:徐家简陋客厅
  6818. 构图设计:特写,火车票
  6819. 运镜调度:固定镜头
  6820. 配音角色:旁白
  6821. 出镜角色:无
  6822. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6823. 画面类型:普通画面
  6824. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6825. \n\n";
  6826. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6827. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  6828. $is_regenerate_version = true;
  6829. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6830. $prompt = $origin_prompt;
  6831. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6832. // 获取章节内容
  6833. $full_content = getProp($anime, 'content');
  6834. if ($uploaded_content) {
  6835. $full_content = $uploaded_content;
  6836. }
  6837. // 根据章节内容拆分章节
  6838. $chapters = splitContent($full_content);
  6839. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6840. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6841. $messages = [];
  6842. if ($prompt == '确认分镜大纲') {
  6843. // 暂时保留
  6844. $content = $chapter_content;
  6845. if ($is_single) $content = $full_content; // 单剧集使用全文
  6846. if (!$content) {
  6847. Utils::throwError('20003:章节内容无法获取,请确认');
  6848. }
  6849. $question = $is_single
  6850. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6851. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6852. // 构建消息
  6853. $messages[] =
  6854. [
  6855. 'role' => 'user',
  6856. 'content' => $question
  6857. ];
  6858. }else if ($prompt == '继续策划下一集') {
  6859. if ($is_single) {
  6860. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6861. }
  6862. $content = $chapter_content;
  6863. if (!$content) {
  6864. Utils::throwError('20003:章节内容无法获取,请确认');
  6865. }
  6866. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6867. // 获取上一集最后记录
  6868. $prev_sequence = $episode_number - 1;
  6869. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6870. // 构建消息
  6871. $messages[] =
  6872. [
  6873. 'role' => 'user',
  6874. 'content' => $question
  6875. ];
  6876. }else {
  6877. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6878. if (!$content) {
  6879. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6880. }
  6881. if (!$content) {
  6882. Utils::throwError('20003:章节内容无法获取,请确认');
  6883. }
  6884. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6885. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6886. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6887. if ($origin_prompt) {
  6888. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6889. }
  6890. $messages[] =
  6891. [
  6892. 'role' => 'user',
  6893. 'content' => $question
  6894. ];
  6895. }
  6896. // 处理文本模型
  6897. $model = getProp($data, 'model');
  6898. if (!$model) {
  6899. // 用户没有输入,从anime表获取
  6900. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6901. $model = getProp($anime, 'model');
  6902. if (!$model) {
  6903. // anime表也没有,使用默认值
  6904. $model = 'doubao-seed-2-0-mini-260215';
  6905. }
  6906. }
  6907. // 验证模型是否在可用模型表中
  6908. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6909. $model = 'doubao-seed-2-0-mini-260215';
  6910. }
  6911. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6912. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6913. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6914. if ($model === 'deepseek-chat') {
  6915. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6916. $model = 'deepseek-v4-flash';
  6917. $thinkingMode = 'disabled';
  6918. } elseif ($model === 'deepseek-reasoner') {
  6919. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6920. $model = 'deepseek-v4-flash';
  6921. $thinkingMode = 'enabled';
  6922. }
  6923. $post_data = [
  6924. 'model' => $model,
  6925. 'messages' => $messages,
  6926. // 'max_tokens' => 8192,
  6927. 'temperature' => 0.2,
  6928. 'frequency_penalty' => 0,
  6929. 'presence_penalty' => 0,
  6930. 'response_format' => ['type' => 'text'],
  6931. 'thinking' => ['type' => $thinkingMode],
  6932. 'stream' => true // 启用流式输出
  6933. ];
  6934. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6935. // 根据模型类型选择调用方法
  6936. $fullContent = '';
  6937. $fullReasoningContent = '';
  6938. $usage = [];
  6939. try {
  6940. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6941. // DeepSeek 官方模型使用 DeepSeek API
  6942. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6943. } else if (in_array($model, $this->gpt_text_models)) {
  6944. // GPT-5.4 模型使用 TokenRouter API
  6945. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6946. } else if (in_array($model, $this->gemini_text_models)) {
  6947. // Gemini 模型使用 Gemini API
  6948. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6949. } else {
  6950. // 其他模型使用火山引擎API
  6951. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6952. }
  6953. // 验证返回值类型
  6954. if (!is_iterable($streamGenerator)) {
  6955. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6956. dLog('deepseek')->error('chat流式生成器无效', [
  6957. 'generator_type' => $errorType,
  6958. 'model' => $model,
  6959. 'anime_id' => $anime_id,
  6960. 'episode_number' => $episode_number
  6961. ]);
  6962. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6963. 'type' => $errorType,
  6964. 'model' => $model
  6965. ]);
  6966. yield [
  6967. 'type' => 'error',
  6968. 'episode' => [],
  6969. 'answer' => '',
  6970. 'reasoning' => '',
  6971. 'usage' => [],
  6972. 'error' => '接口返回数据异常,请重新请求'
  6973. ];
  6974. return;
  6975. }
  6976. // 处理流式输出
  6977. foreach ($streamGenerator as $chunk) {
  6978. if (isset($chunk['type'])) {
  6979. if ($chunk['type'] === 'done') {
  6980. // 最终结果
  6981. $fullContent = $chunk['full_content'];
  6982. $fullReasoningContent = $chunk['full_reasoning'];
  6983. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6984. } else {
  6985. // 逐块yield数据
  6986. yield $chunk;
  6987. }
  6988. }
  6989. }
  6990. } catch (\Exception $e) {
  6991. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6992. 'model' => $model,
  6993. 'anime_id' => $anime_id,
  6994. 'episode_number' => $episode_number,
  6995. 'trace' => $e->getTraceAsString()
  6996. ]);
  6997. logDB('deepseek', 'error', 'chat流式处理失败', [
  6998. 'error' => $e->getMessage(),
  6999. 'model' => $model
  7000. ]);
  7001. yield [
  7002. 'type' => 'error',
  7003. 'episode' => [],
  7004. 'answer' => '',
  7005. 'reasoning' => '',
  7006. 'usage' => [],
  7007. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7008. ];
  7009. return;
  7010. }
  7011. dLog('deepseek')->info('完整内容: '.$fullContent);
  7012. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7013. // 处理完整内容并返回最终结果
  7014. $episode_arr = handleEpisodeContent($fullContent);
  7015. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7016. if (empty($episode_arr['acts'])) {
  7017. // 未生成剧本相关内容,保存对话记录并返回提示
  7018. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7019. try {
  7020. $now = date('Y-m-d H:i:s');
  7021. // 保存对话记录
  7022. $records = [
  7023. [
  7024. 'uid' => $uid,
  7025. 'anime_id' => $anime_id,
  7026. 'sequence' => $episode_number,
  7027. 'role' => 'user',
  7028. 'content' => $prompt,
  7029. 'created_at' => $now,
  7030. 'updated_at' => $now
  7031. ],
  7032. [
  7033. 'uid' => $uid,
  7034. 'anime_id' => $anime_id,
  7035. 'sequence' => $episode_number,
  7036. 'role' => 'assistant',
  7037. 'content' => $fullContent,
  7038. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7039. 'created_at' => $now,
  7040. 'updated_at' => $now
  7041. ]
  7042. ];
  7043. DB::table('mp_anime_records')->insert($records);
  7044. } catch (\Exception $e) {
  7045. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7046. }
  7047. yield [
  7048. 'type' => 'done',
  7049. 'episode' => [],
  7050. 'answer' => $fullContent,
  7051. 'reasoning' => $fullReasoningContent,
  7052. 'usage' => $usage,
  7053. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7054. ];
  7055. return;
  7056. }
  7057. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7058. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7059. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7060. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7061. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7062. $existing_props = is_array($existing_props) ? $existing_props : [];
  7063. $now = date('Y-m-d H:i:s');
  7064. try {
  7065. DB::beginTransaction();
  7066. $saveResult = $this->saveEpisodeVersionData(
  7067. $anime_id,
  7068. $episode_number,
  7069. $episode_arr,
  7070. $existing_roles,
  7071. $existing_scenes,
  7072. $existing_props,
  7073. $current_episode,
  7074. $base_episode,
  7075. $is_regenerate_version,
  7076. $content,
  7077. $now
  7078. );
  7079. $episode = $saveResult['episode'];
  7080. $episode_id = $saveResult['episode_id'];
  7081. $merged_roles = $saveResult['merged_roles'];
  7082. $merged_scenes = $saveResult['merged_scenes'];
  7083. $merged_props = $saveResult['merged_props'];
  7084. $record_content = $origin_prompt;
  7085. if ($uploaded_content !== '') {
  7086. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7087. }
  7088. $records = [
  7089. [
  7090. 'uid' => $uid,
  7091. 'anime_id' => $anime_id,
  7092. 'role' => 'user',
  7093. 'content' => $record_content,
  7094. 'sequence' => $episode_number,
  7095. 'episode_id' => $episode_id,
  7096. 'created_at' => $now,
  7097. 'updated_at' => $now
  7098. ],
  7099. [
  7100. 'uid' => $uid,
  7101. 'anime_id' => $anime_id,
  7102. 'role' => 'assistant',
  7103. 'content' => $fullContent,
  7104. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7105. 'sequence' => $episode_number,
  7106. 'episode_id' => $episode_id,
  7107. 'created_at' => $now,
  7108. 'updated_at' => $now
  7109. ]
  7110. ];
  7111. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7112. if (!$boolen4) {
  7113. Utils::throwError('20003:对话记录保存失败');
  7114. }
  7115. // 保存模型和内容到anime表
  7116. $update_anime_data = [
  7117. 'model' => $model,
  7118. 'updated_at' => $now
  7119. ];
  7120. if ($uploaded_content) {
  7121. $update_anime_data['content'] = $uploaded_content;
  7122. }
  7123. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7124. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7125. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7126. 'anime_id' => $anime_id,
  7127. 'episode_number' => $episode_number,
  7128. 'model' => $model,
  7129. 'source' => 'chat',
  7130. ]);
  7131. }catch (\Exception $e) {
  7132. DB::rollBack();
  7133. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7134. yield [
  7135. 'type' => 'done',
  7136. 'answer' => $fullContent,
  7137. 'reasoning' => $fullReasoningContent,
  7138. 'usage' => $usage,
  7139. 'error' => $e->getMessage(),
  7140. ];
  7141. return;
  7142. }
  7143. DB::commit();
  7144. if ($is_global_generate_pics) {
  7145. // // 批量生成全局角色图片
  7146. // $this->batchSetGlobalRoleImg([
  7147. // 'anime_id' => $anime_id,
  7148. // ], true);
  7149. // // 批量生成全局场景图片
  7150. // $this->batchSetGlobalSceneImg([
  7151. // 'anime_id' => $anime_id,
  7152. // ], true);
  7153. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7154. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7155. }
  7156. $episode['episode_id'] = $episode_id;
  7157. $episode['roles'] = $merged_roles;
  7158. $episode['scenes'] = $merged_scenes;
  7159. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7160. yield [
  7161. 'type' => 'done',
  7162. 'episode' => $episode,
  7163. 'answer' => $fullContent,
  7164. 'reasoning' => $fullReasoningContent,
  7165. 'usage' => $usage
  7166. ];
  7167. }
  7168. public function addChatForAce($data) {
  7169. $uid = Site::getUid();
  7170. $anime_id = getProp($data, 'anime_id');
  7171. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7172. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7173. if (!$anime) Utils::throwError('20003:对话不存在');
  7174. $file = getProp($data, 'file');
  7175. $content = getProp($data, 'content', '');
  7176. $bid = getProp($data, 'bid', 0);
  7177. $script_id = getProp($data, 'script_id', 0);
  7178. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7179. $prompt = getProp($data, 'prompt');
  7180. $is_multi = getProp($anime, 'is_multi');
  7181. $is_single = (int)$is_multi !== 1;
  7182. // 积分余额预检(仅单剧集模式收费)
  7183. if ($is_single) {
  7184. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7185. }
  7186. $extra_products = getProp($data, 'products', []);
  7187. if (!$extra_products) {
  7188. $extra_products = getProp($anime, 'extra_products');
  7189. if ($extra_products) {
  7190. $extra_products = json_decode($extra_products, true);
  7191. }else {
  7192. $extra_products = [];
  7193. }
  7194. }else {
  7195. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7196. }
  7197. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7198. $anime_script_id = getProp($anime, 'script_id');
  7199. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7200. $cpid = Site::getCpid();
  7201. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7202. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7203. ->where('mapping.script_id', $anime_script_id)
  7204. ->where('product.cpid', $cpid)
  7205. ->where('product.is_deleted', 0);
  7206. $mappings = $script_products_mappings->select(
  7207. 'mapping.product_id',
  7208. 'mapping.episode_number',
  7209. 'product.product_name',
  7210. 'product.type',
  7211. 'product.product',
  7212. 'product.pic_prompt',
  7213. 'product.url',
  7214. 'product.pic_task_id',
  7215. 'product.pic_task_status',
  7216. 'product.three_view_image_url'
  7217. )
  7218. ->get();
  7219. // 按 product_id 分组,合并 episode_number
  7220. $productMap = [];
  7221. foreach ($mappings as $item) {
  7222. $product_id = $item->product_id;
  7223. $product_name = $item->product_name;
  7224. // 处理product_name两边的符号
  7225. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7226. if (!isset($productMap[$product_id])) {
  7227. $productMap[$product_id] = [
  7228. 'product_id' => $product_id,
  7229. 'product_name' => $product_name,
  7230. 'type' => (int)$item->type,
  7231. 'product' => (int)$item->product,
  7232. 'pic_prompt' => $item->pic_prompt,
  7233. 'url' => $item->url,
  7234. 'pic_task_id' => $item->pic_task_id,
  7235. 'pic_task_status' => $item->pic_task_status,
  7236. 'episode_numbers' => [],
  7237. ];
  7238. }
  7239. // 添加 episode_number(去重)
  7240. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7241. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7242. }
  7243. }
  7244. // 将查询到的剧本资产合并到extra_products中
  7245. // 先构建extra_products的索引(以product_id为key,用于去重)
  7246. $extraProductsMap = [];
  7247. foreach ($extra_products as $item) {
  7248. $key = getProp($item, 'product_id');
  7249. if ($key) {
  7250. $extraProductsMap[$key] = $item;
  7251. }
  7252. }
  7253. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7254. foreach ($productMap as $product) {
  7255. $product_id = $product['product_id'];
  7256. // 如果不存在则添加(不带episode_number信息)
  7257. if (!isset($extraProductsMap[$product_id])) {
  7258. $extraProductsMap[$product_id] = [
  7259. 'product_id' => $product['product_id'],
  7260. 'product_name' => $product['product_name'],
  7261. 'type' => $product['type'],
  7262. 'product' => $product['product'],
  7263. 'pic_prompt' => $product['pic_prompt'],
  7264. 'url' => $product['url'],
  7265. 'pic_task_id' => $product['pic_task_id'],
  7266. 'pic_task_status' => $product['pic_task_status'],
  7267. ];
  7268. }
  7269. }
  7270. // 重新赋值给extra_products
  7271. $extra_products = array_values($extraProductsMap);
  7272. }
  7273. $user_anime_name = getProp($anime, 'anime_name');
  7274. // 处理提示词
  7275. if ($prompt && $extra_products) {
  7276. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7277. foreach($extra_products as $item) {
  7278. $product_name = getProp($item, 'product_name');
  7279. if ($product_name) {
  7280. // 替换 {product_name} 为 product_name
  7281. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7282. }
  7283. }
  7284. }
  7285. // 处理文本模型
  7286. $model = getProp($data, 'model');
  7287. if (!$model) {
  7288. // 用户没有输入,从anime表获取
  7289. $model = getProp($anime, 'model');
  7290. if (!$model) {
  7291. // anime表也没有,使用默认值
  7292. $model = 'deepseek-v4-pro';
  7293. }
  7294. }
  7295. // 验证模型是否在可用模型表中
  7296. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7297. $model = 'deepseek-v4-pro';
  7298. }
  7299. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7300. if ($prompt) {
  7301. $question .= "本次修改要求如下:\n{$prompt}";
  7302. }
  7303. // if (!$file && !$content && !$bid) {
  7304. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7305. // }
  7306. // 提取文件内容
  7307. if ($file) {
  7308. $content = $this->extractFileContent($file);
  7309. if (!$content) {
  7310. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7311. }
  7312. } elseif ($script_id) {
  7313. $content = $this->getContentByScriptId($script_id);
  7314. if (!$content) {
  7315. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7316. }
  7317. } elseif ($bid) {
  7318. $content = $this->getContentByBid($bid);
  7319. if (!$content) {
  7320. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7321. }
  7322. } elseif ($content) {
  7323. $content = filterContent($content);
  7324. } else {
  7325. $content = getProp($anime, 'content');
  7326. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7327. $need_generate_content = true;
  7328. }
  7329. }
  7330. // 美术风格
  7331. $input_art_style = getProp($data, 'art_style');
  7332. if (!$input_art_style) {
  7333. $mappedArtStyle = getProp($anime, 'art_style');
  7334. }else {
  7335. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7336. }
  7337. // 判断是否需要生成原文内容
  7338. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7339. // 如果需要生成原文内容,添加额外的要求
  7340. $content_generation_requirement = $need_generate_content
  7341. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7342. : "";
  7343. // 美术风格
  7344. if (!$mappedArtStyle) {
  7345. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7346. }else {
  7347. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7348. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7349. }else {
  7350. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7351. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7352. }
  7353. }
  7354. // 构建主体、场景和道具提示词
  7355. $extra_role_prompt = "\n";
  7356. $extra_scene_prompt = "\n";
  7357. $extra_prop_prompt = "\n";
  7358. $ref_products = []; // 参考资产
  7359. if ($extra_products) {
  7360. foreach($extra_products as $item) {
  7361. $product = getProp($item, 'product');
  7362. $product_name = getProp($item, 'product_name');
  7363. if ($product_name == '旁白') continue;
  7364. $ref_products[$product_name] = $item;
  7365. $pic_prompt = getProp($item, 'pic_prompt');
  7366. if ((int)$product === 1) {
  7367. // 拼接角色信息
  7368. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7369. } elseif ((int)$product === 2) {
  7370. // 拼接场景信息
  7371. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7372. } elseif ((int)$product === 3) {
  7373. // 拼接道具信息
  7374. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7375. }
  7376. }
  7377. // 优化提示词,融入剧本
  7378. if (!empty(trim($extra_role_prompt))) {
  7379. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7380. }
  7381. if (!empty(trim($extra_scene_prompt))) {
  7382. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7383. }
  7384. if (!empty(trim($extra_prop_prompt))) {
  7385. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7386. }
  7387. }
  7388. if ($anime_script_id && $is_single) {
  7389. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7390. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7391. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7392. }else {
  7393. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7394. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7395. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7396. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7397. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7398. {$extra_role_prompt}";
  7399. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7400. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7401. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7402. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7403. {$extra_scene_prompt}";
  7404. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7405. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7406. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7407. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7408. {$extra_prop_prompt}";
  7409. }
  7410. $systemPrompt = $is_single
  7411. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7412. 强制要求:
  7413. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7414. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7415. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7416. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7417. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7418. 普通要求:
  7419. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7420. $role_demo
  7421. $scene_demo
  7422. $prop_demo
  7423. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7424. 5.1片段分割逻辑(优先级从高到低):
  7425. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7426. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7427. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7428. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7429. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7430. - 片段数量格式为: 片段数量:8
  7431. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7432. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7433. 5.3分镜结构:每个分镜包含以下字段:
  7434. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7435. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7436. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7437. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7438. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7439. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7440. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7441. - 运镜:场景+画面描述+运镜
  7442. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7443. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7444. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7445. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7446. 6.{$mappedArtStyle_prompt}\n\n
  7447. 示例如下:\n
  7448. ###剧本名:西昆仑
  7449. ###故事梗概
  7450. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7451. ###剧本亮点
  7452. 亮点1:绝境奇药,生死一线
  7453. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7454. 亮点2:结拜兄妹,化解尴尬
  7455. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7456. 亮点3:纤发夺命,情愫暗涌
  7457. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7458. ###人物关系
  7459. 阿雪与梁萧之间存在兄妹之情。
  7460. ###核心矛盾
  7461. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7462. ###主体列表
  7463. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7464. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7465. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7466. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7467. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7468. 全景,正面拍摄,青年女性,亚洲人。
  7469. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7470. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7471. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7472. ###美术风格
  7473. 基础画风风格词:厚涂古风
  7474. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7475. ###场景列表
  7476. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7477. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7478. 无人物。}
  7479. ###分段剧本
  7480. 片段数量:8
  7481. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7482. ##片段1
  7483. 时长:12s
  7484. 分镜1
  7485. 出场角色:刀疤脸
  7486. 场景:边境小镇街道
  7487. 出场道具:酒杯-高脚杯
  7488. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7489. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7490. 配音台词:
  7491. 背景音效:
  7492. 分镜2
  7493. 出场角色:刀疤脸
  7494. 场景:悦来酒馆
  7495. 出场道具:酒杯-高脚杯
  7496. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7497. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7498. 配音台词:
  7499. 背景音效:
  7500. 分镜3
  7501. 出场角色:刀疤脸
  7502. 场景:悦来酒馆
  7503. 出场道具:酒杯-高脚杯
  7504. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7505. 运镜:从中景推向令牌特写。
  7506. 配音台词:
  7507. 背景音效:
  7508. 分镜4
  7509. 出场角色:刀疤脸
  7510. 场景:悦来酒馆
  7511. 出场道具:酒杯-高脚杯
  7512. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7513. 运镜:极速推向酒水溅起的瞬间。
  7514. 配音台词:
  7515. 背景音效:
  7516. 分镜5
  7517. 出场角色:刀疤脸
  7518. 场景:悦来酒馆
  7519. 出场道具:酒杯-高脚杯
  7520. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7521. 运镜:固定机位,利用倾斜构图制造压迫感。
  7522. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7523. 背景音效:
  7524. \n\n"
  7525. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7526. 强制要求:\n
  7527. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7528. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7529. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7530. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7531. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7532. 普通要求:\n
  7533. 1.剧本名(必须生成)必须与文档内容高度相关
  7534. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7535. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7536. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7537. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7538. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7539. {$extra_role_prompt}
  7540. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7541. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7542. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7543. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7544. {$extra_scene_prompt}
  7545. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7546. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7547. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7548. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7549. {$extra_prop_prompt}
  7550. 5.{$mappedArtStyle_prompt}\n\n
  7551. 示例如下:\n
  7552. ###剧本名:西昆仑
  7553. ###故事梗概
  7554. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7555. ###剧本亮点
  7556. 亮点1:绝境奇药,生死一线
  7557. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7558. 亮点2:结拜兄妹,化解尴尬
  7559. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7560. 亮点3:纤发夺命,情愫暗涌
  7561. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7562. ###人物关系
  7563. 阿雪与梁萧之间存在兄妹之情。
  7564. ###核心矛盾
  7565. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7566. ###主体列表
  7567. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7568. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7569. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7570. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7571. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7572. 全景,正面拍摄,青年女性,亚洲人。
  7573. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7574. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7575. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7576. ###美术风格
  7577. 基础画风风格词:厚涂古风
  7578. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7579. ###场景列表
  7580. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7581. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7582. 无人物。}
  7583. ###道具列表
  7584. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7585. // 构建消息
  7586. $messages = [
  7587. [
  7588. 'role' => 'system',
  7589. 'content' => $systemPrompt
  7590. ],
  7591. [
  7592. 'role' => 'user',
  7593. 'content' => "以下是文档内容:
  7594. {$content}
  7595. 用户问题:
  7596. {$question}"
  7597. ]
  7598. ];
  7599. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7600. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7601. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7602. if ($model === 'deepseek-chat') {
  7603. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7604. $model = 'deepseek-v4-flash';
  7605. $thinkingMode = 'disabled';
  7606. } elseif ($model === 'deepseek-reasoner') {
  7607. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7608. $model = 'deepseek-v4-flash';
  7609. $thinkingMode = 'enabled';
  7610. }
  7611. $post_data = [
  7612. 'model' => $model,
  7613. 'messages' => $messages,
  7614. // 'max_tokens' => 8192,
  7615. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7616. 'frequency_penalty' => 0,
  7617. 'presence_penalty' => 0,
  7618. 'response_format' => ['type' => 'text'],
  7619. 'thinking' => ['type'=>$thinkingMode],
  7620. 'stream' => true // 启用流式输出
  7621. ];
  7622. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7623. // 根据模型类型选择调用方法
  7624. $fullContent = '';
  7625. $fullReasoningContent = '';
  7626. $usage = [];
  7627. try {
  7628. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7629. // DeepSeek 官方模型使用 DeepSeek API
  7630. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7631. } else if (in_array($model, $this->gpt_text_models)) {
  7632. // GPT-5.4 模型使用 TokenRouter API
  7633. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7634. } else if (in_array($model, $this->gemini_text_models)) {
  7635. // Gemini 模型使用 Gemini API
  7636. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7637. } else {
  7638. // 其他模型使用火山引擎API
  7639. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7640. }
  7641. // 验证返回值类型
  7642. if (!is_iterable($streamGenerator)) {
  7643. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7644. dLog('deepseek')->error('addChat流式生成器无效', [
  7645. 'generator_type' => $errorType,
  7646. 'model' => $model,
  7647. 'anime_id' => $anime_id
  7648. ]);
  7649. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7650. 'type' => $errorType,
  7651. 'model' => $model
  7652. ]);
  7653. yield [
  7654. 'type' => 'error',
  7655. 'script' => [],
  7656. 'episode' => [],
  7657. 'answer' => '',
  7658. 'reasoning' => '',
  7659. 'usage' => [],
  7660. 'error' => '接口返回数据异常,请重新请求'
  7661. ];
  7662. return;
  7663. }
  7664. // 处理流式输出
  7665. foreach ($streamGenerator as $chunk) {
  7666. if (isset($chunk['type'])) {
  7667. if ($chunk['type'] === 'done') {
  7668. // 最终结果
  7669. $fullContent = $chunk['full_content'];
  7670. $fullReasoningContent = $chunk['full_reasoning'];
  7671. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7672. } else {
  7673. // 逐块yield数据
  7674. yield $chunk;
  7675. }
  7676. }
  7677. }
  7678. } catch (\Exception $e) {
  7679. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7680. 'model' => $model,
  7681. 'anime_id' => $anime_id,
  7682. 'trace' => $e->getTraceAsString()
  7683. ]);
  7684. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7685. 'error' => $e->getMessage(),
  7686. 'model' => $model
  7687. ]);
  7688. yield [
  7689. 'type' => 'error',
  7690. 'script' => [],
  7691. 'episode' => [],
  7692. 'answer' => '',
  7693. 'reasoning' => '',
  7694. 'usage' => [],
  7695. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7696. ];
  7697. return;
  7698. }
  7699. dLog('deepseek')->info('完整内容: '.$fullContent);
  7700. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7701. // 处理完整内容并返回最终结果
  7702. $script_arr = [];
  7703. if ($fullContent) {
  7704. $script_arr = handleScriptContentForAce($fullContent);
  7705. dLog('deepseek')->info('解析内容', $script_arr);
  7706. logDB('deepseek', 'info', '解析内容', $script_arr);
  7707. }
  7708. if (empty($script_arr['roles'])) {
  7709. // 未生成剧本相关内容,保存对话记录并返回提示
  7710. dLog('deepseek')->info('未生成剧本相关的内容');
  7711. try {
  7712. DB::beginTransaction();
  7713. $now = date('Y-m-d H:i:s');
  7714. // 保存对话记录
  7715. $records = [
  7716. [
  7717. 'uid' => $uid,
  7718. 'anime_id' => $anime_id,
  7719. 'sequence' => 0,
  7720. 'role' => 'user',
  7721. 'content' => $prompt,
  7722. 'created_at' => $now,
  7723. 'updated_at' => $now
  7724. ],
  7725. [
  7726. 'uid' => $uid,
  7727. 'anime_id' => $anime_id,
  7728. 'sequence' => 0,
  7729. 'role' => 'assistant',
  7730. // 'content' => $fullContent,
  7731. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7732. 'created_at' => $now,
  7733. 'updated_at' => $now
  7734. ]
  7735. ];
  7736. DB::table('mp_anime_records')->insert($records);
  7737. DB::commit();
  7738. } catch (\Exception $e) {
  7739. DB::rollBack();
  7740. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7741. }
  7742. yield [
  7743. 'type' => 'done',
  7744. 'script' => [],
  7745. 'episode' => [],
  7746. 'answer' => $fullContent,
  7747. 'reasoning' => $fullReasoningContent,
  7748. 'usage' => $usage,
  7749. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7750. ];
  7751. return;
  7752. }
  7753. // 如果需要生成原文内容,从script_arr中提取
  7754. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7755. $content = $script_arr['content'];
  7756. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7757. if (!$content) {
  7758. yield [
  7759. 'type' => 'done',
  7760. 'script' => [],
  7761. 'episode' => [],
  7762. 'answer' => $fullContent,
  7763. 'reasoning' => $fullReasoningContent,
  7764. 'usage' => $usage,
  7765. 'error' => '未生成剧本内容,请调整提示词再试'
  7766. ];
  7767. return;
  7768. }
  7769. }
  7770. // 替换美术风格
  7771. if ($mappedArtStyle !== '') {
  7772. $script_arr['art_style'] = $mappedArtStyle;
  7773. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7774. }
  7775. // 新建动漫
  7776. if ($user_anime_name == '新剧本策划') {
  7777. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7778. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7779. // if (!$anime_name) {
  7780. // // 未识别到剧本名,保存对话记录并返回提示
  7781. // dLog('deepseek')->info('未能识别到剧本名称');
  7782. // try {
  7783. // DB::beginTransaction();
  7784. // $now = date('Y-m-d H:i:s');
  7785. // // 保存对话记录
  7786. // $records = [
  7787. // [
  7788. // 'uid' => $uid,
  7789. // 'anime_id' => $anime_id,
  7790. // 'sequence' => 0,
  7791. // 'role' => 'user',
  7792. // 'content' => $prompt,
  7793. // 'created_at' => $now,
  7794. // 'updated_at' => $now
  7795. // ],
  7796. // [
  7797. // 'uid' => $uid,
  7798. // 'anime_id' => $anime_id,
  7799. // 'sequence' => 0,
  7800. // 'role' => 'assistant',
  7801. // 'content' => '未能生成剧本名称,请重试',
  7802. // 'created_at' => $now,
  7803. // 'updated_at' => $now
  7804. // ]
  7805. // ];
  7806. // DB::table('mp_anime_records')->insert($records);
  7807. // DB::commit();
  7808. // } catch (\Exception $e) {
  7809. // DB::rollBack();
  7810. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7811. // }
  7812. // yield [
  7813. // 'type' => 'done',
  7814. // 'script' => [],
  7815. // 'episode' => [],
  7816. // 'answer' => $fullContent,
  7817. // 'reasoning' => $fullReasoningContent,
  7818. // 'usage' => $usage,
  7819. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7820. // ];
  7821. // return;
  7822. // }
  7823. // 确认对话名称唯一性
  7824. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7825. $anime_name = $anime_name . '_' . date('YmdHis');
  7826. }
  7827. }else {
  7828. $anime_name = $user_anime_name;
  7829. }
  7830. $table_data = [
  7831. 'user_id' => $uid,
  7832. 'anime_name' => $anime_name,
  7833. 'model' => $model,
  7834. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7835. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7836. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7837. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7838. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7839. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7840. 'art_style_type' => $input_art_style,
  7841. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7842. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7843. 'status' => '解析完成',
  7844. 'content' => $content,
  7845. 'is_multi' => $is_multi,
  7846. 'ace_mode' => $ace_mode,
  7847. 'generate_status' => '待执行',
  7848. 'updated_at' => date('Y-m-d H:i:s')
  7849. ];
  7850. if ($table_data['content']) {
  7851. $chapters = splitContent($table_data['content']);
  7852. $chapter_count = count($chapters);
  7853. if ($chapter_count > 0) {
  7854. $table_data['start_episode_sequence'] = 1;
  7855. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7856. }
  7857. }
  7858. if ($extra_products) {
  7859. $table_data['extra_products'] = json_encode($extra_products, 256);
  7860. }
  7861. // 如果有剧本ID则进行绑定
  7862. if ($script_id) {
  7863. $table_data['script_id'] = $script_id;
  7864. }
  7865. $single_episode = [];
  7866. try {
  7867. DB::beginTransaction();
  7868. $now = date('Y-m-d H:i:s');
  7869. // 更新动漫大纲
  7870. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7871. if (!$boolen) {
  7872. dLog('deepseek')->info('动漫保存失败', $table_data);
  7873. Utils::throwError('20003:动漫保存失败');
  7874. }
  7875. // 保存对话记录
  7876. $records = [
  7877. [
  7878. 'uid' => $uid,
  7879. 'anime_id' => $anime_id,
  7880. 'sequence' => 0,
  7881. 'role' => 'user',
  7882. 'content' => $prompt,
  7883. 'created_at' => date('Y-m-d H:i:s'),
  7884. 'updated_at' => date('Y-m-d H:i:s')
  7885. ],
  7886. [
  7887. 'uid' => $uid,
  7888. 'anime_id' => $anime_id,
  7889. 'sequence' => 0,
  7890. 'role' => 'assistant',
  7891. 'content' => $fullContent,
  7892. 'created_at' => date('Y-m-d H:i:s'),
  7893. 'updated_at' => date('Y-m-d H:i:s')
  7894. ]
  7895. ];
  7896. // 保存对话记录
  7897. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7898. if (!$boolen3) {
  7899. Utils::throwError('20003:对话记录保存失败');
  7900. }
  7901. if ($is_single) {
  7902. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7903. if (empty($episode_arr['acts'])) {
  7904. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7905. }
  7906. $saveResult = $this->saveEpisodeVersionData(
  7907. $anime_id,
  7908. 1,
  7909. $episode_arr,
  7910. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7911. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7912. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7913. null,
  7914. null,
  7915. false,
  7916. $content,
  7917. $now,
  7918. $ref_products
  7919. );
  7920. $single_episode = $saveResult['episode'];
  7921. $episode_id = $saveResult['episode_id'];
  7922. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7923. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7924. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7925. 'props' => json_encode($saveResult['merged_props'], 256),
  7926. 'updated_at' => $now
  7927. ]);
  7928. if ($boolen5 === false) {
  7929. Utils::throwError('20003:单剧集主表资源同步失败');
  7930. }
  7931. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7932. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7933. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7934. $episode_record_content = '确认分镜大纲';
  7935. if ($content !== '') {
  7936. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7937. }
  7938. $episode_records = [
  7939. [
  7940. 'uid' => $uid,
  7941. 'anime_id' => $anime_id,
  7942. 'role' => 'user',
  7943. 'content' => $episode_record_content,
  7944. 'sequence' => 1,
  7945. 'episode_id' => $episode_id,
  7946. 'created_at' => $now,
  7947. 'updated_at' => $now
  7948. ],
  7949. [
  7950. 'uid' => $uid,
  7951. 'anime_id' => $anime_id,
  7952. 'role' => 'assistant',
  7953. 'content' => $fullContent,
  7954. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7955. 'sequence' => 1,
  7956. 'episode_id' => $episode_id,
  7957. 'created_at' => $now,
  7958. 'updated_at' => $now
  7959. ]
  7960. ];
  7961. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7962. if (!$boolen4) {
  7963. Utils::throwError('20003:单剧集分镜记录保存失败');
  7964. }
  7965. }
  7966. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7967. if ($is_single && !empty($single_episode)) {
  7968. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7969. 'anime_id' => $anime_id,
  7970. 'episode_id' => $episode_id ?? 0,
  7971. 'model' => $model,
  7972. 'source' => 'addChatForAce',
  7973. ]);
  7974. }
  7975. }catch (\Exception $e) {
  7976. DB::rollBack();
  7977. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7978. yield [
  7979. 'type' => 'done',
  7980. 'answer' => $fullContent,
  7981. 'reasoning' => $fullReasoningContent,
  7982. 'usage' => $usage,
  7983. 'error' => $e->getMessage(),
  7984. ];
  7985. return;
  7986. }
  7987. DB::commit();
  7988. dLog('deepseek')->info('保存完毕');
  7989. if ($is_single && !empty($single_episode)) {
  7990. // $this->batchSetGlobalRoleImg([
  7991. // 'anime_id' => $anime_id,
  7992. // ]);
  7993. // $this->batchSetGlobalSceneImg([
  7994. // 'anime_id' => $anime_id,
  7995. // ]);
  7996. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7997. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7998. }
  7999. $table_data['anime_id'] = $anime_id;
  8000. $table_data['roles'] = json_decode($table_data['roles'], true);
  8001. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8002. // $table_data['episodes'] = $script_arr['episodes'];
  8003. unset($table_data['created_at']);
  8004. unset($table_data['updated_at']);
  8005. unset($table_data['status']);
  8006. dLog('deepseek')->info('开始返回');
  8007. yield [
  8008. 'type' => 'done',
  8009. 'script' => $table_data,
  8010. 'episode' => $single_episode,
  8011. 'answer' => $fullContent,
  8012. 'reasoning' => $fullReasoningContent,
  8013. 'usage' => $usage
  8014. ];
  8015. }
  8016. public function reGenerateAnimeForAce($data) {
  8017. $uid = Site::getUid();
  8018. $file = getProp($data, 'file');
  8019. $content = getProp($data, 'content', '');
  8020. $bid = getProp($data, 'bid', 0);
  8021. $script_id = getProp($data, 'script_id', 0);
  8022. $anime_id = getProp($data, 'anime_id');
  8023. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8024. if (!$anime) {
  8025. Utils::throwError('20003:该对话不存在');
  8026. }
  8027. $is_multi = getProp($anime, 'is_multi', 1);
  8028. $is_single = (int)$is_multi !== 1;
  8029. // 积分余额预检(仅单剧集模式收费)
  8030. if ($is_single) {
  8031. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8032. }
  8033. $extra_products = getProp($data, 'products', []);
  8034. if (!$extra_products) {
  8035. $extra_products = getProp($anime, 'extra_products');
  8036. if ($extra_products) {
  8037. $extra_products = json_decode($extra_products, true);
  8038. }else {
  8039. $extra_products = [];
  8040. }
  8041. }else {
  8042. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8043. }
  8044. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8045. $anime_script_id = getProp($anime, 'script_id');
  8046. if ($anime_script_id && $is_single) {
  8047. $cpid = Site::getCpid();
  8048. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8049. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8050. ->where('mapping.script_id', $anime_script_id)
  8051. ->where('product.cpid', $cpid)
  8052. ->where('product.is_deleted', 0);
  8053. $mappings = $script_products_mappings->select(
  8054. 'mapping.product_id',
  8055. 'mapping.episode_number',
  8056. 'product.product_name',
  8057. 'product.type',
  8058. 'product.product',
  8059. 'product.pic_prompt',
  8060. 'product.url',
  8061. 'product.pic_task_id',
  8062. 'product.pic_task_status',
  8063. 'product.three_view_image_url'
  8064. )
  8065. ->get();
  8066. // 按 product_id 分组,合并 episode_number
  8067. $productMap = [];
  8068. foreach ($mappings as $item) {
  8069. $product_id = $item->product_id;
  8070. $product_name = $item->product_name;
  8071. // 处理product_name两边的符号
  8072. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8073. if (!isset($productMap[$product_id])) {
  8074. $productMap[$product_id] = [
  8075. 'product_id' => $product_id,
  8076. 'product_name' => $product_name,
  8077. 'type' => (int)$item->type,
  8078. 'product' => (int)$item->product,
  8079. 'pic_prompt' => $item->pic_prompt,
  8080. 'url' => $item->url,
  8081. 'pic_task_id' => $item->pic_task_id,
  8082. 'pic_task_status' => $item->pic_task_status,
  8083. 'episode_numbers' => [],
  8084. ];
  8085. }
  8086. // 添加 episode_number(去重)
  8087. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8088. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8089. }
  8090. }
  8091. // 将查询到的剧本资产合并到extra_products中
  8092. // 先构建extra_products的索引(以product_id为key,用于去重)
  8093. $extraProductsMap = [];
  8094. foreach ($extra_products as $item) {
  8095. $key = getProp($item, 'product_id');
  8096. if ($key) {
  8097. $extraProductsMap[$key] = $item;
  8098. }
  8099. }
  8100. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8101. foreach ($productMap as $product) {
  8102. $product_id = $product['product_id'];
  8103. // 如果不存在则添加(不带episode_number信息)
  8104. if (!isset($extraProductsMap[$product_id])) {
  8105. $extraProductsMap[$product_id] = [
  8106. 'product_id' => $product['product_id'],
  8107. 'product_name' => $product['product_name'],
  8108. 'type' => $product['type'],
  8109. 'product' => $product['product'],
  8110. 'pic_prompt' => $product['pic_prompt'],
  8111. 'url' => $product['url'],
  8112. 'pic_task_id' => $product['pic_task_id'],
  8113. 'pic_task_status' => $product['pic_task_status'],
  8114. ];
  8115. }
  8116. }
  8117. // 重新赋值给extra_products
  8118. $extra_products = array_values($extraProductsMap);
  8119. }
  8120. $user_anime_name = getProp($anime, 'anime_name');
  8121. $prompt = getProp($data, 'prompt');
  8122. // 处理提示词
  8123. if ($prompt && $extra_products) {
  8124. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8125. foreach($extra_products as $item) {
  8126. $product_name = getProp($item, 'product_name');
  8127. if ($product_name) {
  8128. // 替换 {product_name} 为 product_name
  8129. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8130. }
  8131. }
  8132. }
  8133. // 处理文本模型
  8134. $model = getProp($data, 'model');
  8135. if (!$model) {
  8136. // 用户没有输入,从anime表获取
  8137. $model = getProp($anime, 'model');
  8138. if (!$model) {
  8139. // anime表也没有,使用默认值
  8140. $model = 'deepseek-v4-pro';
  8141. }
  8142. }
  8143. // 验证模型是否在可用模型表中
  8144. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8145. $model = 'deepseek-v4-pro';
  8146. }
  8147. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8148. if ($is_single) {
  8149. $episode_exists = DB::table('mp_anime_episodes')
  8150. ->where('anime_id', $anime_id)
  8151. ->where('sequence', 1)
  8152. ->exists();
  8153. if ($episode_exists) {
  8154. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8155. }
  8156. }
  8157. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8158. if ($prompt) {
  8159. $question .= "本次修改要求如下:\n{$prompt}";
  8160. }
  8161. // 提取文件内容
  8162. if ($file) {
  8163. $content = $this->extractFileContent($file);
  8164. if (!$content) {
  8165. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8166. }
  8167. } elseif ($script_id) {
  8168. $content = $this->getContentByScriptId($script_id);
  8169. if (!$content) {
  8170. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8171. }
  8172. } elseif ($bid) {
  8173. $content = $this->getContentByBid($bid);
  8174. if (!$content) {
  8175. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8176. }
  8177. } elseif ($content) {
  8178. $content = filterContent($content);
  8179. }else {
  8180. $content = filterContent(getProp($anime, 'content'));
  8181. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  8182. $need_generate_content = true;
  8183. }
  8184. }
  8185. // 判断是否需要生成原文内容
  8186. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  8187. // 如果需要生成原文内容,添加额外的要求
  8188. $content_generation_requirement = $need_generate_content
  8189. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  8190. : "";
  8191. // 美术风格
  8192. $input_art_style = getProp($data, 'art_style');
  8193. if (!$input_art_style) {
  8194. $mappedArtStyle = getProp($anime, 'art_style');
  8195. }else {
  8196. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8197. }
  8198. if (!$mappedArtStyle) {
  8199. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8200. }else {
  8201. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8202. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8203. }else {
  8204. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8205. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8206. }
  8207. }
  8208. // 构建主体、场景和道具提示词
  8209. $extra_role_prompt = "\n";
  8210. $extra_scene_prompt = "\n";
  8211. $extra_prop_prompt = "\n";
  8212. $ref_products = []; // 参考资产
  8213. if ($extra_products) {
  8214. foreach($extra_products as $item) {
  8215. $product = getProp($item, 'product');
  8216. $product_name = getProp($item, 'product_name');
  8217. if ($product_name == '旁白') continue;
  8218. $ref_products[$product_name] = $item;
  8219. $pic_prompt = getProp($item, 'pic_prompt');
  8220. if ((int)$product === 1) {
  8221. // 拼接角色信息
  8222. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8223. } elseif ((int)$product === 2) {
  8224. // 拼接场景信息
  8225. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8226. } elseif ((int)$product === 3) {
  8227. // 拼接道具信息
  8228. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8229. }
  8230. }
  8231. // 优化提示词,融入剧本
  8232. if (!empty(trim($extra_role_prompt))) {
  8233. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8234. }
  8235. if (!empty(trim($extra_scene_prompt))) {
  8236. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8237. }
  8238. if (!empty(trim($extra_prop_prompt))) {
  8239. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8240. }
  8241. }
  8242. if ($anime_script_id && $is_single) {
  8243. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  8244. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  8245. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  8246. }else {
  8247. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8248. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8249. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8250. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8251. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8252. {$extra_role_prompt}";
  8253. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8254. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8255. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8256. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8257. {$extra_scene_prompt}";
  8258. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8259. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8260. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8261. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8262. {$extra_prop_prompt}";
  8263. }
  8264. $system_message = ['role'=>'system', 'content'=>$is_single
  8265. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  8266. 强制要求:
  8267. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8268. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8269. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8270. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8271. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8272. 普通要求:
  8273. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  8274. $role_demo
  8275. $scene_demo
  8276. $prop_demo
  8277. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8278. 5.1片段分割逻辑(优先级从高到低):
  8279. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8280. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8281. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8282. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8283. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8284. - 片段数量格式为: 片段数量:8
  8285. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8286. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8287. 5.3分镜结构:每个分镜包含以下字段:
  8288. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8289. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8290. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8291. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8292. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8293. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8294. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8295. - 运镜:场景+画面描述+运镜
  8296. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8297. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8298. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8299. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  8300. 6.{$mappedArtStyle_prompt}\n\n
  8301. 示例如下:\n
  8302. ###剧本名:西昆仑
  8303. ###故事梗概
  8304. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8305. ###剧本亮点
  8306. 亮点1:绝境奇药,生死一线
  8307. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8308. 亮点2:结拜兄妹,化解尴尬
  8309. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8310. 亮点3:纤发夺命,情愫暗涌
  8311. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8312. ###人物关系
  8313. 阿雪与梁萧之间存在兄妹之情。
  8314. ###核心矛盾
  8315. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8316. ###主体列表
  8317. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8318. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8319. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8320. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8321. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8322. 全景,正面拍摄,青年女性,亚洲人。
  8323. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8324. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8325. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8326. ###美术风格
  8327. 基础画风风格词:厚涂古风
  8328. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8329. ###场景列表
  8330. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8331. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8332. 无人物。}
  8333. ###分段剧本
  8334. 片段数量:8
  8335. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8336. ##片段1
  8337. 时长:12s
  8338. 分镜1
  8339. 出场角色:刀疤脸
  8340. 场景:边境小镇街道
  8341. 出场道具:酒杯-高脚杯
  8342. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8343. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8344. 配音台词:
  8345. 背景音效:
  8346. 分镜2
  8347. 出场角色:刀疤脸
  8348. 场景:悦来酒馆
  8349. 出场道具:酒杯-高脚杯
  8350. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8351. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8352. 配音台词:
  8353. 背景音效:
  8354. 分镜3
  8355. 出场角色:刀疤脸
  8356. 场景:悦来酒馆
  8357. 出场道具:酒杯-高脚杯
  8358. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8359. 运镜:从中景推向令牌特写。
  8360. 配音台词:
  8361. 背景音效:
  8362. 分镜4
  8363. 出场角色:刀疤脸
  8364. 场景:悦来酒馆
  8365. 出场道具:酒杯-高脚杯
  8366. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8367. 运镜:极速推向酒水溅起的瞬间。
  8368. 配音台词:
  8369. 背景音效:
  8370. 分镜5
  8371. 出场角色:刀疤脸
  8372. 场景:悦来酒馆
  8373. 出场道具:酒杯-高脚杯
  8374. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8375. 运镜:固定机位,利用倾斜构图制造压迫感。
  8376. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8377. 背景音效:
  8378. \n\n"
  8379. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8380. 强制要求:\n
  8381. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8382. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8383. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8384. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8385. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8386. 普通要求:\n
  8387. 1.剧本名(必须生成)必须与文档内容高度相关
  8388. $role_demo
  8389. $scene_demo
  8390. $prop_demo
  8391. 5.{$mappedArtStyle_prompt}\n\n
  8392. 示例如下:\n
  8393. ###剧本名:西昆仑
  8394. ###故事梗概
  8395. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8396. ###剧本亮点
  8397. 亮点1:绝境奇药,生死一线
  8398. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8399. 亮点2:结拜兄妹,化解尴尬
  8400. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8401. 亮点3:纤发夺命,情愫暗涌
  8402. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8403. ###人物关系
  8404. 阿雪与梁萧之间存在兄妹之情。
  8405. ###核心矛盾
  8406. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8407. ###主体列表
  8408. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8409. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8410. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8411. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8412. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8413. 全景,正面拍摄,青年女性,亚洲人。
  8414. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8415. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8416. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8417. ###美术风格
  8418. 基础画风风格词:厚涂古风
  8419. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8420. ###场景列表
  8421. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8422. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8423. 无人物。}
  8424. ###道具列表
  8425. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  8426. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  8427. $episode_count = $this->extractEpisodeNumber($prompt);
  8428. if ((int)getProp($anime, 'is_multi') !== 1) {
  8429. yield [
  8430. 'type' => 'done',
  8431. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  8432. 'reasoning' => '',
  8433. 'usage' => []
  8434. ];
  8435. return;
  8436. }
  8437. if ($episode_count) {
  8438. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  8439. $system_message = [
  8440. 'role' => 'system',
  8441. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8442. 强制要求:\n
  8443. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8444. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8445. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8446. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8447. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8448. 普通要求:\n
  8449. 1.<故事梗概>控制在200-300字左右
  8450. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8451. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8452. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8453. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8454. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8455. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8456. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8457. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8458. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8459. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8460. 示例如下:\n
  8461. ###剧本名:西昆仑
  8462. ###故事梗概
  8463. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8464. ###剧本亮点
  8465. 亮点1:绝境奇药,生死一线
  8466. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8467. 亮点2:结拜兄妹,化解尴尬
  8468. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8469. 亮点3:纤发夺命,情愫暗涌
  8470. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8471. ###人物关系
  8472. 阿雪与梁萧之间存在兄妹之情。
  8473. ###核心矛盾
  8474. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8475. ###主体列表
  8476. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8477. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8478. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8479. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8480. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8481. 全景,正面拍摄,青年女性,亚洲人。
  8482. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8483. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8484. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8485. ###美术风格
  8486. 基础画风风格词:厚涂古风
  8487. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8488. ###场景列表
  8489. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8490. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8491. 无人物。}
  8492. ###分集详细内容
  8493. ##第1章 重生
  8494. 我重生了。
  8495. 源于一个男人偏执的暗恋。
  8496. ##第2章 相救
  8497. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8498. 我眼睛扫向站在锅炉后的卞大伟。"
  8499. ];
  8500. // 构建消息
  8501. $messages = [
  8502. $system_message,
  8503. [
  8504. 'role' => 'user',
  8505. 'content' => "以下是文档内容:
  8506. {$content}
  8507. 用户问题:
  8508. {$question}"
  8509. ]
  8510. ];
  8511. }else {
  8512. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8513. // 构建消息
  8514. $messages = [
  8515. $system_message,
  8516. [
  8517. 'role' => 'user',
  8518. 'content' => "以下是文档内容:
  8519. {$content}
  8520. 用户问题:
  8521. {$question}"
  8522. ]
  8523. ];
  8524. }else {
  8525. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8526. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8527. return (array)$value;
  8528. })->toArray();
  8529. array_unshift($messages, $system_message);
  8530. $messages[] = [
  8531. 'role' => 'user',
  8532. 'content' => $prompt
  8533. ];
  8534. }
  8535. }
  8536. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8537. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8538. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8539. if ($model === 'deepseek-chat') {
  8540. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8541. $model = 'deepseek-v4-flash';
  8542. $thinkingMode = 'disabled';
  8543. } elseif ($model === 'deepseek-reasoner') {
  8544. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8545. $model = 'deepseek-v4-flash';
  8546. $thinkingMode = 'enabled';
  8547. }
  8548. $post_data = [
  8549. 'model' => $model,
  8550. 'messages' => $messages,
  8551. // 'max_tokens' => 8192,
  8552. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8553. 'frequency_penalty' => 0,
  8554. 'presence_penalty' => 0,
  8555. 'response_format' => ['type' => 'text'],
  8556. 'thinking' => ['type' => $thinkingMode],
  8557. 'stream' => true // 启用流式输出
  8558. ];
  8559. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8560. // 根据模型类型选择调用方法
  8561. $fullContent = '';
  8562. $fullReasoningContent = '';
  8563. $usage = [];
  8564. // dd($post_data);
  8565. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8566. try {
  8567. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8568. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8569. } else if (in_array($model, $this->gpt_text_models)) {
  8570. // GPT-5.4 模型使用 TokenRouter API
  8571. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8572. } else if (in_array($model, $this->gemini_text_models)) {
  8573. // Gemini 模型使用 Gemini API
  8574. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8575. } else {
  8576. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8577. }
  8578. // 验证返回值类型
  8579. if (!is_iterable($streamGenerator)) {
  8580. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8581. dLog('deepseek')->error('方法名流式生成器无效', [
  8582. 'generator_type' => $errorType,
  8583. 'model' => $model,
  8584. // 添加其他上下文信息
  8585. ]);
  8586. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8587. 'type' => $errorType,
  8588. 'model' => $model
  8589. ]);
  8590. yield [
  8591. 'type' => 'error',
  8592. // 根据方法返回相应的空数据结构
  8593. 'answer' => '',
  8594. 'reasoning' => '',
  8595. 'usage' => [],
  8596. 'error' => '接口返回数据异常,请重新请求'
  8597. ];
  8598. return;
  8599. }
  8600. // 处理流式输出
  8601. foreach ($streamGenerator as $chunk) {
  8602. if (isset($chunk['type'])) {
  8603. if ($chunk['type'] === 'done') {
  8604. $fullContent = $chunk['full_content'];
  8605. $fullReasoningContent = $chunk['full_reasoning'];
  8606. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8607. } else {
  8608. yield $chunk;
  8609. }
  8610. }
  8611. }
  8612. } catch (\Exception $e) {
  8613. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8614. 'model' => $model,
  8615. 'trace' => $e->getTraceAsString()
  8616. ]);
  8617. logDB('deepseek', 'error', '方法名流式处理失败', [
  8618. 'error' => $e->getMessage(),
  8619. 'model' => $model
  8620. ]);
  8621. yield [
  8622. 'type' => 'error',
  8623. // 根据方法返回相应的空数据结构
  8624. 'answer' => '',
  8625. 'reasoning' => '',
  8626. 'usage' => [],
  8627. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8628. ];
  8629. return;
  8630. }
  8631. dLog('deepseek')->info('完整内容: '.$fullContent);
  8632. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8633. // 处理完整内容并返回最终结果
  8634. $script_arr = [];
  8635. if ($fullContent) {
  8636. $script_arr = handleScriptContentForAce($fullContent);
  8637. dLog('deepseek')->info('解析内容', $script_arr);
  8638. logDB('deepseek', 'info', '解析内容', $script_arr);
  8639. }
  8640. if (empty($script_arr['roles'])) {
  8641. // 未生成剧本相关内容,保存对话记录并返回提示
  8642. dLog('deepseek')->info('未生成剧本相关的内容');
  8643. try {
  8644. $now = date('Y-m-d H:i:s');
  8645. // 保存对话记录
  8646. $records = [
  8647. [
  8648. 'uid' => $uid,
  8649. 'anime_id' => $anime_id,
  8650. 'sequence' => 0,
  8651. 'role' => 'user',
  8652. 'content' => $prompt,
  8653. 'created_at' => $now,
  8654. 'updated_at' => $now
  8655. ],
  8656. [
  8657. 'uid' => $uid,
  8658. 'anime_id' => $anime_id,
  8659. 'sequence' => 0,
  8660. 'role' => 'assistant',
  8661. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8662. 'created_at' => $now,
  8663. 'updated_at' => $now
  8664. ]
  8665. ];
  8666. DB::table('mp_anime_records')->insert($records);
  8667. } catch (\Exception $e) {
  8668. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8669. }
  8670. yield [
  8671. 'type' => 'done',
  8672. 'script' => [],
  8673. 'episode' => [],
  8674. 'answer' => $fullContent,
  8675. 'reasoning' => $fullReasoningContent,
  8676. 'usage' => $usage,
  8677. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8678. ];
  8679. return;
  8680. }
  8681. // 替换美术风格
  8682. if ($mappedArtStyle !== '') {
  8683. $script_arr['art_style'] = $mappedArtStyle;
  8684. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8685. }
  8686. if ($user_anime_name != '新剧本策划') {
  8687. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8688. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8689. // 确认对话名称唯一性
  8690. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8691. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8692. }
  8693. }else {
  8694. $anime_name = $user_anime_name;
  8695. }
  8696. $table_data = [
  8697. 'user_id' => $uid,
  8698. 'model' => $model,
  8699. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8700. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8701. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8702. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8703. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8704. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8705. 'art_style_type' => $input_art_style,
  8706. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8707. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8708. 'status' => '解析完成',
  8709. 'generate_status' => '待执行',
  8710. 'updated_at' => date('Y-m-d H:i:s')
  8711. ];
  8712. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8713. // 如果是修改集数,则将content内容更新(会改变原文)
  8714. if (isset($episode_count) && $episode_count > 0) {
  8715. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8716. $table_data['start_episode_sequence'] = 1;
  8717. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8718. }else {
  8719. // 如果需要生成原文内容,从script_arr中提取
  8720. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8721. $table_data['content'] = $script_arr['content'];
  8722. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8723. if (!$table_data['content']) {
  8724. yield [
  8725. 'type' => 'done',
  8726. 'script' => [],
  8727. 'episode' => [],
  8728. 'answer' => $fullContent,
  8729. 'reasoning' => $fullReasoningContent,
  8730. 'usage' => $usage,
  8731. 'error' => '未生成剧本内容,请调整提示词再试'
  8732. ];
  8733. return;
  8734. }
  8735. }
  8736. if (isset($table_data['content']) && $table_data['content']) {
  8737. $chapters = splitContent($table_data['content']);
  8738. $chapter_count = count($chapters);
  8739. if ($chapter_count > 0) {
  8740. $table_data['start_episode_sequence'] = 1;
  8741. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8742. }
  8743. }
  8744. }
  8745. if ($extra_products) {
  8746. $table_data['extra_products'] = json_encode($extra_products, 256);
  8747. }
  8748. $single_episode = [];
  8749. try {
  8750. DB::beginTransaction();
  8751. $now = date('Y-m-d H:i:s');
  8752. // 更新动漫大纲
  8753. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8754. if (!$boolen) {
  8755. dLog('deepseek')->info('对话修改失败', $table_data);
  8756. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8757. Utils::throwError('20003:对话修改失败');
  8758. }
  8759. // 保存对话记录
  8760. $records = [
  8761. [
  8762. 'uid' => $uid,
  8763. 'anime_id' => $anime_id,
  8764. 'sequence' => 0,
  8765. 'role' => 'user',
  8766. 'content' => $prompt,
  8767. 'created_at' => $now,
  8768. 'updated_at' => $now
  8769. ],
  8770. [
  8771. 'uid' => $uid,
  8772. 'anime_id' => $anime_id,
  8773. 'sequence' => 0,
  8774. 'role' => 'assistant',
  8775. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8776. 'content' => $fullContent,
  8777. 'created_at' => $now,
  8778. 'updated_at' => $now
  8779. ]
  8780. ];
  8781. // 保存对话记录
  8782. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8783. if (!$boolen3) {
  8784. Utils::throwError('20003:对话记录保存失败');
  8785. }
  8786. // 单剧集模式:生成并保存剧集信息
  8787. if ($is_single) {
  8788. $anime_name = getProp($anime, 'anime_name', '未命名');
  8789. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8790. if (empty($episode_arr['acts'])) {
  8791. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8792. }
  8793. $saveResult = $this->saveEpisodeVersionData(
  8794. $anime_id,
  8795. 1,
  8796. $episode_arr,
  8797. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8798. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8799. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8800. null,
  8801. null,
  8802. false,
  8803. $content,
  8804. $now,
  8805. $ref_products
  8806. );
  8807. $single_episode = $saveResult['episode'];
  8808. $episode_id = $saveResult['episode_id'];
  8809. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8810. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8811. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8812. 'props' => json_encode($saveResult['merged_props'], 256),
  8813. 'updated_at' => $now
  8814. ]);
  8815. if ($boolen5 === false) {
  8816. Utils::throwError('20003:单剧集主表资源同步失败');
  8817. }
  8818. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8819. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8820. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8821. $episode_record_content = '确认分镜大纲';
  8822. if ($content !== '') {
  8823. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8824. }
  8825. $episode_records = [
  8826. [
  8827. 'uid' => $uid,
  8828. 'anime_id' => $anime_id,
  8829. 'role' => 'user',
  8830. 'content' => $episode_record_content,
  8831. 'sequence' => 1,
  8832. 'episode_id' => $episode_id,
  8833. 'created_at' => $now,
  8834. 'updated_at' => $now
  8835. ],
  8836. [
  8837. 'uid' => $uid,
  8838. 'anime_id' => $anime_id,
  8839. 'role' => 'assistant',
  8840. 'content' => $fullContent,
  8841. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8842. 'sequence' => 1,
  8843. 'episode_id' => $episode_id,
  8844. 'created_at' => $now,
  8845. 'updated_at' => $now
  8846. ]
  8847. ];
  8848. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8849. if (!$boolen4) {
  8850. Utils::throwError('20003:单剧集分镜记录保存失败');
  8851. }
  8852. }
  8853. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8854. if ($is_single && !empty($single_episode)) {
  8855. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8856. 'anime_id' => $anime_id,
  8857. 'episode_id' => $episode_id ?? 0,
  8858. 'model' => $model,
  8859. 'source' => 'reGenerateAnimeForAce',
  8860. ]);
  8861. }
  8862. }catch (\Exception $e) {
  8863. DB::rollBack();
  8864. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8865. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8866. yield [
  8867. 'type' => 'done',
  8868. 'answer' => $fullContent,
  8869. 'reasoning' => $fullReasoningContent,
  8870. 'usage' => $usage,
  8871. 'error' => $e->getMessage(),
  8872. ];
  8873. return;
  8874. }
  8875. DB::commit();
  8876. dLog('deepseek')->info('保存完毕');
  8877. if ($is_single && !empty($single_episode)) {
  8878. // $this->batchSetGlobalRoleImg([
  8879. // 'anime_id' => $anime_id,
  8880. // ]);
  8881. // $this->batchSetGlobalSceneImg([
  8882. // 'anime_id' => $anime_id,
  8883. // ]);
  8884. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8885. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8886. }
  8887. $table_data['anime_id'] = $anime_id;
  8888. $table_data['roles'] = json_decode($table_data['roles'], true);
  8889. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8890. $table_data['props'] = json_decode($table_data['props'], true);
  8891. unset($table_data['updated_at']);
  8892. unset($table_data['status']);
  8893. yield [
  8894. 'type' => 'done',
  8895. 'script' => $table_data,
  8896. 'episode' => $single_episode,
  8897. 'answer' => $fullContent,
  8898. 'reasoning' => $fullReasoningContent,
  8899. 'usage' => $usage
  8900. ];
  8901. }
  8902. public function chatForAce($data) {
  8903. $uid = Site::getUid();
  8904. // 积分余额预检(不足直接报错)
  8905. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  8906. $anime_id = getProp($data, 'anime_id');
  8907. $file = getProp($data, 'file');
  8908. $content = getProp($data, 'content', '');
  8909. $bid = getProp($data, 'bid', 0);
  8910. $script_id = getProp($data, 'script_id', 0);
  8911. $episode_number = getProp($data, 'episode_number', 1);
  8912. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8913. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8914. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8915. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8916. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8917. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8918. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8919. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8920. $roles = is_array($roles) ? $roles : [];
  8921. $scenes = is_array($scenes) ? $scenes : [];
  8922. $extra_products = getProp($data, 'products', []);
  8923. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8924. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8925. $anime_script_id = getProp($anime, 'script_id');
  8926. if ($anime_script_id) {
  8927. $cpid = Site::getCpid();
  8928. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8929. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8930. ->where('mapping.script_id', $anime_script_id)
  8931. ->where('product.cpid', $cpid)
  8932. ->where('product.is_deleted', 0);
  8933. // 如果提供了 episode_number,则过滤指定集数
  8934. if ($episode_number !== null && $episode_number !== '') {
  8935. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8936. }
  8937. $mappings = $script_products_mappings->select(
  8938. 'mapping.product_id',
  8939. 'mapping.episode_number',
  8940. 'product.product_name',
  8941. 'product.type',
  8942. 'product.product',
  8943. 'product.pic_prompt',
  8944. 'product.url',
  8945. 'product.pic_task_id',
  8946. 'product.pic_task_status',
  8947. 'product.three_view_image_url'
  8948. )
  8949. ->get();
  8950. // 按 product_id 分组,合并 episode_number
  8951. $productMap = [];
  8952. foreach ($mappings as $item) {
  8953. $product_id = $item->product_id;
  8954. $product_name = $item->product_name;
  8955. // 处理product_name两边的符号
  8956. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8957. if (!isset($productMap[$product_id])) {
  8958. $productMap[$product_id] = [
  8959. 'product_id' => $product_id,
  8960. 'product_name' => $product_name,
  8961. 'type' => (int)$item->type,
  8962. 'product' => (int)$item->product,
  8963. 'pic_prompt' => $item->pic_prompt,
  8964. 'url' => $item->url,
  8965. 'pic_task_id' => $item->pic_task_id,
  8966. 'pic_task_status' => $item->pic_task_status,
  8967. 'episode_numbers' => [],
  8968. ];
  8969. }
  8970. // 添加 episode_number(去重)
  8971. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8972. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8973. }
  8974. }
  8975. // 将查询到的剧本资产合并到extra_products中
  8976. // 先构建extra_products的索引(以product_id+episode_number为key)
  8977. $extraProductsMap = [];
  8978. foreach ($extra_products as $item) {
  8979. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8980. $extraProductsMap[$key] = $item;
  8981. }
  8982. // 合并剧本资产(去重:product_id+episode_number)
  8983. foreach ($productMap as $product) {
  8984. foreach ($product['episode_numbers'] as $ep_num) {
  8985. $key = $product['product_id'] . '_' . $ep_num;
  8986. // 如果不存在则添加
  8987. if (!isset($extraProductsMap[$key])) {
  8988. $extraProductsMap[$key] = [
  8989. 'product_id' => $product['product_id'],
  8990. 'product_name' => $product['product_name'],
  8991. 'type' => $product['type'],
  8992. 'product' => $product['product'],
  8993. 'pic_prompt' => $product['pic_prompt'],
  8994. 'url' => $product['url'],
  8995. 'pic_task_id' => $product['pic_task_id'],
  8996. 'pic_task_status' => $product['pic_task_status'],
  8997. 'episode_number' => $ep_num,
  8998. ];
  8999. }
  9000. }
  9001. }
  9002. // 重新赋值给extra_products
  9003. $extra_products = array_values($extraProductsMap);
  9004. }
  9005. // 处理提示词
  9006. if ($prompt && $extra_products) {
  9007. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  9008. foreach($extra_products as $item) {
  9009. $product_name = getProp($item, 'product_name');
  9010. if ($product_name) {
  9011. // 替换 {product_name} 为 product_name
  9012. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  9013. }
  9014. }
  9015. }
  9016. // 获取最后一集序号
  9017. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  9018. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  9019. // 转换主体列表和场景列表的格式
  9020. // 获取参考主体或场景
  9021. if ((int)$episode_number === 1) {
  9022. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  9023. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  9024. }else {
  9025. $prev_episode_number = $episode_number - 1;
  9026. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  9027. }
  9028. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  9029. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  9030. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  9031. // 合并anime_products和extra_products(extra_products优先,去重)
  9032. $anime_products = getProp($anime, 'extra_products');
  9033. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  9034. $ref_products = [];
  9035. foreach($anime_products as $item) {
  9036. $product_name = getProp($item, 'product_name');
  9037. $ref_products[$product_name] = $item;
  9038. }
  9039. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  9040. $extra_roles = []; // 从extra_products中提取的角色
  9041. $extra_scenes = []; // 从extra_products中提取的场景
  9042. $extra_props = []; // 从extra_products中提取的道具
  9043. if ($extra_products && is_array($extra_products)) {
  9044. foreach($extra_products as $item) {
  9045. $product = (int)getProp($item, 'product');
  9046. $product_name = getProp($item, 'product_name');
  9047. if ($product_name == '旁白') continue;
  9048. $pic_prompt = getProp($item, 'pic_prompt');
  9049. $ref_products[$product_name] = $item;
  9050. if ($product === 1) {
  9051. // 角色
  9052. $extra_roles[$product_name] = [
  9053. 'role' => $product_name,
  9054. 'pic_prompt' => $pic_prompt,
  9055. 'url' => getProp($item, 'url', ''),
  9056. ];
  9057. } elseif ($product === 2) {
  9058. // 场景
  9059. $extra_scenes[$product_name] = [
  9060. 'scene' => $product_name,
  9061. 'pic_prompt' => $pic_prompt,
  9062. 'url' => getProp($item, 'url', ''),
  9063. ];
  9064. } elseif ($product === 3) {
  9065. // 道具
  9066. $extra_props[$product_name] = [
  9067. 'prop' => $product_name,
  9068. 'pic_prompt' => $pic_prompt,
  9069. 'url' => getProp($item, 'url', ''),
  9070. ];
  9071. }
  9072. }
  9073. }
  9074. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  9075. $merged_roles = [];
  9076. foreach($ref_roles as $role) {
  9077. $role_name = getProp($role, 'role');
  9078. if (!isset($extra_roles[$role_name])) {
  9079. $merged_roles[$role_name] = $role;
  9080. }
  9081. }
  9082. // 添加extra_roles
  9083. foreach($extra_roles as $role_name => $role) {
  9084. $merged_roles[$role_name] = $role;
  9085. }
  9086. $ref_roles = array_values($merged_roles);
  9087. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  9088. $merged_scenes = [];
  9089. foreach($ref_scenes as $scene) {
  9090. $scene_name = getProp($scene, 'scene');
  9091. if (!isset($extra_scenes[$scene_name])) {
  9092. $merged_scenes[$scene_name] = $scene;
  9093. }
  9094. }
  9095. // 添加extra_scenes
  9096. foreach($extra_scenes as $scene_name => $scene) {
  9097. $merged_scenes[$scene_name] = $scene;
  9098. }
  9099. $ref_scenes = array_values($merged_scenes);
  9100. // 合并ref_props和extra_props(extra_props优先,去重)
  9101. $merged_props = [];
  9102. foreach($ref_props as $prop) {
  9103. $prop_name = getProp($prop, 'prop');
  9104. if (!isset($extra_props[$prop_name])) {
  9105. $merged_props[$prop_name] = $prop;
  9106. }
  9107. }
  9108. // 添加extra_props
  9109. foreach($extra_props as $prop_name => $prop) {
  9110. $merged_props[$prop_name] = $prop;
  9111. }
  9112. $ref_props = array_values($merged_props);
  9113. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  9114. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  9115. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  9116. // 构建强制主体、场景和道具提示词
  9117. $forced_roles_prompt = "";
  9118. $forced_scenes_prompt = "";
  9119. $forced_props_prompt = "";
  9120. if (!empty($extra_roles)) {
  9121. $forced_roles_list = "";
  9122. foreach($extra_roles as $role_name => $role) {
  9123. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  9124. }
  9125. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9126. }
  9127. if (!empty($extra_scenes)) {
  9128. $forced_scenes_list = "";
  9129. foreach($extra_scenes as $scene_name => $scene) {
  9130. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  9131. }
  9132. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9133. }
  9134. if (!empty($extra_props)) {
  9135. $forced_props_list = "";
  9136. foreach($extra_props as $prop_name => $prop) {
  9137. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  9138. }
  9139. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9140. }
  9141. if ($anime_script_id) {
  9142. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  9143. }else if ($roles_content) {
  9144. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  9145. 主体范围:\n {$roles_content}\n
  9146. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  9147. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9148. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9149. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9150. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9151. }else {
  9152. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9153. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9154. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9155. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9156. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9157. }
  9158. if ($anime_script_id) {
  9159. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  9160. }else if ($scenes_content) {
  9161. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9162. 场景范围:\n {$scenes_content}\n
  9163. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  9164. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  9165. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9166. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9167. }else {
  9168. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9169. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9170. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9171. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9172. }
  9173. if ($anime_script_id) {
  9174. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  9175. }else if ($props_content) {
  9176. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9177. 道具范围:\n {$props_content}\n
  9178. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  9179. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  9180. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9181. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9182. }else {
  9183. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9184. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  9185. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9186. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9187. }
  9188. // 提取文件内容
  9189. if ($file) {
  9190. $uploaded_content = $this->extractFileContent($file);
  9191. if (!$uploaded_content) {
  9192. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9193. }
  9194. } elseif ($script_id) {
  9195. $uploaded_content = $this->getContentByScriptId($script_id);
  9196. if (!$uploaded_content) {
  9197. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9198. }
  9199. } elseif ($bid) {
  9200. $uploaded_content = $this->getContentByBid($bid);
  9201. if (!$uploaded_content) {
  9202. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9203. }
  9204. } elseif ($content) {
  9205. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  9206. }
  9207. // elseif ($prompt) {
  9208. // $uploaded_content = filterContent($prompt);
  9209. // }
  9210. else {
  9211. $uploaded_content = '';
  9212. }
  9213. // 美术风格
  9214. $input_art_style = getProp($data, 'art_style');
  9215. if (!$input_art_style) {
  9216. $mappedArtStyle = getProp($anime, 'art_style');
  9217. }else {
  9218. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9219. }
  9220. if (!$mappedArtStyle) {
  9221. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9222. }else {
  9223. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9224. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9225. }else {
  9226. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9227. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9228. }
  9229. }
  9230. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9231. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9232. // 强制要求:
  9233. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9234. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9235. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9236. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  9237. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  9238. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  9239. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  9240. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  9241. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  9242. // 10.分镜要和场景列表、人物主体保持一致\n
  9243. // 普通要求:
  9244. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9245. // {$role_demo}
  9246. // {$scene_demo}
  9247. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9248. // 4.1片段分割逻辑(优先级从高到低):
  9249. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9250. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9251. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9252. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9253. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9254. // - 片段数量格式为: 片段数量:8
  9255. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9256. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9257. // 4.3分镜结构:每个分镜包含以下字段:
  9258. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  9259. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  9260. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9261. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  9262. // - 运镜:场景+画面描述+运镜
  9263. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  9264. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9265. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9266. // 5.$mappedArtStyle_prompt\n\n
  9267. // 示例格式:\n
  9268. // 第1集:隐形的守护者
  9269. // ###故事梗概
  9270. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9271. // ###美术风格
  9272. // 基础画风风格词:胡金铨武侠
  9273. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9274. // ###主体列表
  9275. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9276. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9277. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9278. // ###场景列表
  9279. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9280. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9281. // ###分段剧本
  9282. // 片段数量:8
  9283. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9284. // ##片段1
  9285. // 时长:12s
  9286. // 分镜1
  9287. // 场景:边境小镇街道
  9288. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9289. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9290. // 配音台词:
  9291. // 背景音效:
  9292. // 分镜2
  9293. // 场景:悦来酒馆
  9294. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9295. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9296. // 配音台词:
  9297. // 背景音效:
  9298. // 分镜3
  9299. // 场景:悦来酒馆
  9300. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9301. // 运镜:从中景推向令牌特写。
  9302. // 配音台词:
  9303. // 背景音效:
  9304. // 分镜4
  9305. // 场景:悦来酒馆
  9306. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9307. // 运镜:极速推向酒水溅起的瞬间。
  9308. // 配音台词:
  9309. // 背景音效:
  9310. // 分镜5
  9311. // 镜头描述
  9312. // 场景:悦来酒馆
  9313. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9314. // 运镜:固定机位,利用倾斜构图制造压迫感。
  9315. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9316. // 背景音效:
  9317. // \n\n";
  9318. /*
  9319. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  9320. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  9321. // ===================================================================
  9322. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9323. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9324. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9325. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9326. 强制要求:
  9327. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9328. 普通要求:
  9329. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9330. {$role_demo}
  9331. {$scene_demo}
  9332. {$prop_demo}
  9333. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9334. 5.1片段分割逻辑(优先级从高到低):
  9335. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9336. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9337. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9338. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9339. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9340. - 片段数量格式为: 片段数量:8
  9341. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9342. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9343. 5.3分镜结构:每个分镜包含以下字段:
  9344. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9345. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9346. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9347. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9348. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9349. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9350. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9351. - 运镜:场景+画面描述+运镜
  9352. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9353. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9354. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9355. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9356. 6.《情绪-视听语言映射表》:
  9357. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9358. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9359. -----|---------|------------|----------------
  9360. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9361. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9362. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9363. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9364. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9365. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9366. -----|---------|------------|----------------
  9367. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9368. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9369. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9370. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9371. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9372. --------|---------|--------------|-------------
  9373. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9374. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9375. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9376. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9377. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9378. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9379. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9380. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9381. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9382. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9383. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9384. -----|---------|------------|------------
  9385. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9386. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9387. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9388. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9389. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9390. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9391. --------|---------|--------------|----------
  9392. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9393. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9394. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9395. 6.6 声音设计与潜意识影响 (Soundscape)
  9396. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9397. -----|---------|------------|------------------
  9398. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9399. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9400. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9401. 理论基石:
  9402. - The Five C's of Cinematography by Joseph V. Mascelli
  9403. - Film Art: An Introduction by David Bordwell
  9404. - Sight, Sound, Motion by Herbert Zettl
  9405. - Notes on the Cinematograph by Robert Bresson
  9406. \n\n
  9407. 7.{$mappedArtStyle_prompt}
  9408. 示例格式:\n
  9409. 第1集:隐形的守护者
  9410. ###故事梗概
  9411. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9412. ###美术风格
  9413. 基础画风风格词:胡金铨武侠
  9414. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9415. ###主体列表
  9416. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9417. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9418. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9419. ###场景列表
  9420. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9421. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9422. ###道具列表
  9423. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9424. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9425. ###分段剧本
  9426. 片段数量:8
  9427. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9428. ##片段1
  9429. 时长:12s
  9430. 分镜1
  9431. 出场角色:刀疤脸
  9432. 场景:边境小镇街道
  9433. 出场道具:酒杯-高脚杯
  9434. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9435. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9436. 配音台词:
  9437. 背景音效:
  9438. 分镜2
  9439. 出场角色:刀疤脸
  9440. 场景:悦来酒馆
  9441. 出场道具:酒杯-高脚杯
  9442. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9443. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9444. 配音台词:
  9445. 背景音效:
  9446. 分镜3
  9447. 出场角色:刀疤脸
  9448. 场景:悦来酒馆
  9449. 出场道具:酒杯-高脚杯
  9450. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9451. 运镜:从中景推向令牌特写。
  9452. 配音台词:
  9453. 背景音效:
  9454. 分镜4
  9455. 出场角色:刀疤脸
  9456. 场景:悦来酒馆
  9457. 出场道具:酒杯-高脚杯
  9458. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9459. 运镜:极速推向酒水溅起的瞬间。
  9460. 配音台词:
  9461. 背景音效:
  9462. 分镜5
  9463. 出场角色:刀疤脸
  9464. 场景:悦来酒馆
  9465. 出场道具:酒杯-高脚杯
  9466. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9467. 运镜:固定机位,利用倾斜构图制造压迫感。
  9468. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9469. 背景音效:
  9470. \n\n";
  9471. */
  9472. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9473. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9474. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9475. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9476. 强制要求:
  9477. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9478. 普通要求:
  9479. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  9480. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  9481. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  9482. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  9483. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9484. 5.1片段分割逻辑(优先级从高到低):
  9485. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9486. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9487. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9488. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9489. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9490. - 片段数量格式为: 片段数量:8
  9491. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9492. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9493. 5.3分镜结构:每个分镜包含以下字段:
  9494. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9495. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9496. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9497. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9498. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9499. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9500. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9501. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9502. - 运镜:场景+画面描述+运镜
  9503. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9504. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9505. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9506. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9507. 6.《情绪-视听语言映射表》:
  9508. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9509. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9510. -----|---------|------------|----------------
  9511. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9512. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9513. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9514. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9515. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9516. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9517. -----|---------|------------|----------------
  9518. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9519. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9520. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9521. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9522. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9523. --------|---------|--------------|-------------
  9524. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9525. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9526. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9527. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9528. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9529. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9530. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9531. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9532. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9533. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9534. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9535. -----|---------|------------|------------
  9536. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9537. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9538. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9539. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9540. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9541. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9542. --------|---------|--------------|----------
  9543. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9544. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9545. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9546. 6.6 声音设计与潜意识影响 (Soundscape)
  9547. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9548. -----|---------|------------|------------------
  9549. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9550. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9551. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9552. 理论基石:
  9553. - The Five C's of Cinematography by Joseph V. Mascelli
  9554. - Film Art: An Introduction by David Bordwell
  9555. - Sight, Sound, Motion by Herbert Zettl
  9556. - Notes on the Cinematograph by Robert Bresson
  9557. \n\n
  9558. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9559. 示例格式:\n
  9560. 第1集:隐形的守护者
  9561. ###故事梗概
  9562. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9563. ###美术风格
  9564. 基础画风风格词:胡金铨武侠
  9565. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9566. ###主体列表
  9567. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9568. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9569. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9570. ###场景列表
  9571. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9572. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9573. ###道具列表
  9574. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9575. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9576. ###分段剧本
  9577. 片段数量:8
  9578. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9579. ##片段1
  9580. 时长:12s
  9581. 分镜1
  9582. 出场角色:刀疤脸
  9583. 场景:边境小镇街道
  9584. 出场道具:酒杯-高脚杯
  9585. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9586. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9587. 配音台词:
  9588. 背景音效:
  9589. 分镜2
  9590. 出场角色:刀疤脸
  9591. 场景:悦来酒馆
  9592. 出场道具:酒杯-高脚杯
  9593. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9594. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9595. 配音台词:
  9596. 背景音效:
  9597. 分镜3
  9598. 出场角色:刀疤脸
  9599. 场景:悦来酒馆
  9600. 出场道具:酒杯-高脚杯
  9601. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9602. 运镜:从中景推向令牌特写。
  9603. 配音台词:
  9604. 背景音效:
  9605. 分镜4
  9606. 出场角色:刀疤脸
  9607. 场景:悦来酒馆
  9608. 出场道具:酒杯-高脚杯
  9609. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9610. 运镜:极速推向酒水溅起的瞬间。
  9611. 配音台词:
  9612. 背景音效:
  9613. 分镜5
  9614. 出场角色:刀疤脸
  9615. 场景:悦来酒馆
  9616. 出场道具:酒杯-高脚杯
  9617. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9618. 运镜:固定机位,利用倾斜构图制造压迫感。
  9619. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9620. 背景音效:
  9621. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9622. 【本次剧集信息】剧集序号是{$episode_number}。
  9623. 【本次生成数据-主体列表】{$role_demo}
  9624. 【本次生成数据-场景列表】{$scene_demo}
  9625. 【本次生成数据-道具列表】{$prop_demo}
  9626. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9627. \n\n";
  9628. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9629. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  9630. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9631. $is_regenerate_version = true;
  9632. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9633. $prompt = $origin_prompt;
  9634. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9635. // 获取章节内容
  9636. $full_content = getProp($anime, 'content');
  9637. if ($uploaded_content) {
  9638. $full_content = $uploaded_content;
  9639. }
  9640. // 根据章节内容拆分章节
  9641. $chapters = splitContent($full_content);
  9642. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9643. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9644. $messages = [];
  9645. if ($prompt == '确认分镜大纲') {
  9646. // 暂时保留
  9647. $content = $chapter_content;
  9648. if ($is_single) $content = $full_content; // 单剧集使用全文
  9649. if (!$content) {
  9650. Utils::throwError('20003:章节内容无法获取,请确认');
  9651. }
  9652. $question = $is_single
  9653. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9654. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9655. // 构建消息
  9656. $messages[] =
  9657. [
  9658. 'role' => 'user',
  9659. 'content' => $question
  9660. ];
  9661. }else if ($prompt == '继续策划下一集') {
  9662. if ($is_single) {
  9663. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9664. }
  9665. $content = $chapter_content;
  9666. if (!$content) {
  9667. Utils::throwError('20003:章节内容无法获取,请确认');
  9668. }
  9669. // 获取上一集最后记录
  9670. $prev_sequence = $episode_number - 1;
  9671. $messages = array_merge(
  9672. [
  9673. [
  9674. 'role' => 'system',
  9675. 'content' => $demo
  9676. ]
  9677. ],
  9678. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9679. );
  9680. // 构建消息
  9681. $messages[] =
  9682. [
  9683. 'role' => 'user',
  9684. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9685. ];
  9686. /*
  9687. // 旧版逻辑
  9688. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9689. // 构建消息
  9690. $messages[] =
  9691. [
  9692. 'role' => 'user',
  9693. 'content' => $question
  9694. ];
  9695. */
  9696. // dd($messages);
  9697. }else {
  9698. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9699. if (!$content) {
  9700. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9701. }
  9702. if (!$content) {
  9703. Utils::throwError('20003:章节内容无法获取,请确认');
  9704. }
  9705. $messages = array_merge(
  9706. [
  9707. [
  9708. 'role' => 'system',
  9709. 'content' => $demo
  9710. ]
  9711. ],
  9712. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9713. );
  9714. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9715. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9716. if ($origin_prompt) {
  9717. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9718. }
  9719. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9720. $messages[] = [
  9721. 'role' => 'user',
  9722. 'content' => "本集剧情内容:\n\n{$content}\n"
  9723. ];
  9724. $messages[] =
  9725. [
  9726. 'role' => 'user',
  9727. 'content' => $question
  9728. ];
  9729. }
  9730. // 处理文本模型
  9731. $model = getProp($data, 'model');
  9732. if (!$model) {
  9733. // 用户没有输入,从anime表获取
  9734. $model = getProp($anime, 'model');
  9735. if (!$model) {
  9736. // anime表也没有,使用默认值
  9737. $model = 'deepseek-v4-pro';
  9738. }
  9739. }
  9740. // 验证模型是否在可用模型表中
  9741. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9742. $model = 'deepseek-v4-pro';
  9743. }
  9744. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9745. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9746. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9747. if ($model === 'deepseek-chat') {
  9748. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9749. $model = 'deepseek-v4-flash';
  9750. $thinkingMode = 'disabled';
  9751. } elseif ($model === 'deepseek-reasoner') {
  9752. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9753. $model = 'deepseek-v4-flash';
  9754. $thinkingMode = 'enabled';
  9755. }
  9756. $post_data = [
  9757. 'model' => $model,
  9758. 'messages' => $messages,
  9759. // 'max_tokens' => 8192,
  9760. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9761. 'frequency_penalty' => 0,
  9762. 'presence_penalty' => 0,
  9763. 'response_format' => ['type' => 'text'],
  9764. 'thinking' => ['type' => $thinkingMode],
  9765. 'stream' => true // 启用流式输出
  9766. ];
  9767. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9768. // 根据模型类型选择调用方法
  9769. $fullContent = '';
  9770. $fullReasoningContent = '';
  9771. $usage = [];
  9772. try {
  9773. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9774. // DeepSeek 官方模型使用 DeepSeek API
  9775. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9776. } else if (in_array($model, $this->gpt_text_models)) {
  9777. // GPT-5.4 模型使用 TokenRouter API
  9778. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9779. } else if (in_array($model, $this->gemini_text_models)) {
  9780. // Gemini 模型使用 Gemini API
  9781. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9782. } else {
  9783. // 其他模型使用火山引擎API
  9784. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9785. }
  9786. // 验证返回值类型
  9787. if (!is_iterable($streamGenerator)) {
  9788. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9789. dLog('deepseek')->error('chat流式生成器无效', [
  9790. 'generator_type' => $errorType,
  9791. 'model' => $model,
  9792. 'anime_id' => $anime_id,
  9793. 'episode_number' => $episode_number
  9794. ]);
  9795. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9796. 'type' => $errorType,
  9797. 'model' => $model
  9798. ]);
  9799. yield [
  9800. 'type' => 'error',
  9801. 'episode' => [],
  9802. 'answer' => '',
  9803. 'reasoning' => '',
  9804. 'usage' => [],
  9805. 'error' => '接口返回数据异常,请重新请求'
  9806. ];
  9807. return;
  9808. }
  9809. // 处理流式输出
  9810. foreach ($streamGenerator as $chunk) {
  9811. if (isset($chunk['type'])) {
  9812. if ($chunk['type'] === 'done') {
  9813. // 最终结果
  9814. $fullContent = $chunk['full_content'];
  9815. $fullReasoningContent = $chunk['full_reasoning'];
  9816. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9817. } else {
  9818. // 逐块yield数据
  9819. yield $chunk;
  9820. }
  9821. }
  9822. }
  9823. } catch (\Exception $e) {
  9824. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9825. 'model' => $model,
  9826. 'anime_id' => $anime_id,
  9827. 'episode_number' => $episode_number,
  9828. 'trace' => $e->getTraceAsString()
  9829. ]);
  9830. logDB('deepseek', 'error', 'chat流式处理失败', [
  9831. 'error' => $e->getMessage(),
  9832. 'model' => $model
  9833. ]);
  9834. yield [
  9835. 'type' => 'error',
  9836. 'episode' => [],
  9837. 'answer' => '',
  9838. 'reasoning' => '',
  9839. 'usage' => [],
  9840. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9841. ];
  9842. return;
  9843. }
  9844. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9845. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9846. dLog('deepseek')->info('完整内容: '.$fullContent);
  9847. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9848. // 处理完整内容并返回最终结果
  9849. $episode_arr = handleEpisodeContentForAce($fullContent);
  9850. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9851. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9852. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9853. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9854. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9855. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9856. // }
  9857. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9858. $max_retries = 3;
  9859. $retry_count = 0;
  9860. $validation_failed = false;
  9861. $validation_error_msg = '';
  9862. // 验证生成的内容
  9863. if ($anime_script_id) {
  9864. // 检查是否有acts数据
  9865. if (empty($episode_arr['acts'])) {
  9866. $validation_failed = true;
  9867. $validation_error_msg = '未生成分镜剧本相关的内容';
  9868. } else {
  9869. // 校验主体列表:不能为空主体(旁白不算)
  9870. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9871. // 过滤掉"旁白"角色
  9872. $generated_roles = array_filter($generated_roles, function($role) {
  9873. return $role !== '旁白';
  9874. });
  9875. if (empty($generated_roles)) {
  9876. $validation_failed = true;
  9877. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9878. }
  9879. // 仅当存在强制主体设定时校验主体列表
  9880. if (!$validation_failed && !empty($extra_roles)) {
  9881. $expected_roles = array_keys($extra_roles);
  9882. // 找出生成的主体中不在预期列表中的主体
  9883. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9884. if (!empty($invalid_roles)) {
  9885. $validation_failed = true;
  9886. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9887. }
  9888. }
  9889. // 仅当存在强制场景设定时校验场景列表
  9890. if (!$validation_failed && !empty($extra_scenes)) {
  9891. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9892. $expected_scenes = array_keys($extra_scenes);
  9893. // 找出生成的场景中不在预期列表中的场景
  9894. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9895. if (!empty($invalid_scenes)) {
  9896. $validation_failed = true;
  9897. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9898. }
  9899. }
  9900. // 仅当存在强制道具设定时校验道具列表
  9901. if (!$validation_failed && !empty($extra_props)) {
  9902. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9903. $expected_props = array_keys($extra_props);
  9904. // 找出生成的道具中不在预期列表中的道具
  9905. $invalid_props = array_diff($generated_props, $expected_props);
  9906. if (!empty($invalid_props)) {
  9907. $validation_failed = true;
  9908. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9909. }
  9910. }
  9911. }
  9912. } else {
  9913. // 如果没有anime_script_id,只检查是否有acts数据
  9914. if (empty($episode_arr['acts'])) {
  9915. $validation_failed = true;
  9916. $validation_error_msg = '未生成分镜剧本相关的内容';
  9917. } else {
  9918. // 校验主体列表:不能为空主体(旁白不算)
  9919. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9920. // 过滤掉"旁白"角色
  9921. $generated_roles = array_filter($generated_roles, function($role) {
  9922. return $role !== '旁白';
  9923. });
  9924. if (empty($generated_roles)) {
  9925. $validation_failed = true;
  9926. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9927. }
  9928. }
  9929. }
  9930. // 重试逻辑
  9931. while ($validation_failed && $retry_count < $max_retries) {
  9932. $retry_count++;
  9933. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9934. 'reason' => $validation_error_msg,
  9935. 'anime_id' => $anime_id,
  9936. 'episode_number' => $episode_number
  9937. ]);
  9938. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9939. 'reason' => $validation_error_msg,
  9940. 'anime_id' => $anime_id
  9941. ]);
  9942. // 发送流式重试提示
  9943. yield [
  9944. 'type' => 'retry',
  9945. 'retry_count' => $retry_count,
  9946. 'reason' => $validation_error_msg
  9947. ];
  9948. // 构建重试提示词
  9949. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9950. if ($anime_script_id) {
  9951. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9952. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9953. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9954. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9955. } else {
  9956. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9957. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9958. }
  9959. // 添加重试消息到messages
  9960. $messages[] = [
  9961. 'role' => 'assistant',
  9962. 'content' => $fullContent
  9963. ];
  9964. $messages[] = [
  9965. 'role' => 'user',
  9966. 'content' => $retry_prompt
  9967. ];
  9968. // 更新post_data的messages
  9969. $post_data['messages'] = $messages;
  9970. // 重新调用API
  9971. try {
  9972. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9973. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9974. } else if (in_array($model, $this->gpt_text_models)) {
  9975. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9976. } else if (in_array($model, $this->gemini_text_models)) {
  9977. // Gemini 模型使用 Gemini API
  9978. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9979. } else {
  9980. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9981. }
  9982. // 处理流式输出
  9983. $fullContent = '';
  9984. $fullReasoningContent = '';
  9985. foreach ($streamGenerator as $chunk) {
  9986. if (isset($chunk['type'])) {
  9987. if ($chunk['type'] === 'done') {
  9988. $fullContent = $chunk['full_content'];
  9989. $fullReasoningContent = $chunk['full_reasoning'];
  9990. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9991. } else {
  9992. yield $chunk;
  9993. }
  9994. }
  9995. }
  9996. // 重新解析内容
  9997. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9998. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9999. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  10000. $episode_arr = handleEpisodeContentForAce($fullContent);
  10001. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  10002. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  10003. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  10004. // }
  10005. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  10006. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  10007. // 重新验证
  10008. $validation_failed = false;
  10009. $validation_error_msg = '';
  10010. if ($anime_script_id) {
  10011. if (empty($episode_arr['acts'])) {
  10012. $validation_failed = true;
  10013. $validation_error_msg = '未生成分镜剧本相关的内容';
  10014. } else {
  10015. // 校验主体列表:不能为空主体(旁白不算)
  10016. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10017. // 过滤掉"旁白"角色
  10018. $generated_roles = array_filter($generated_roles, function($role) {
  10019. return $role !== '旁白';
  10020. });
  10021. if (empty($generated_roles)) {
  10022. $validation_failed = true;
  10023. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10024. }
  10025. // 仅当存在强制主体设定时校验主体列表
  10026. if (!$validation_failed && !empty($extra_roles)) {
  10027. $expected_roles = array_keys($extra_roles);
  10028. $invalid_roles = array_diff($generated_roles, $expected_roles);
  10029. if (!empty($invalid_roles)) {
  10030. $validation_failed = true;
  10031. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  10032. }
  10033. }
  10034. // 仅当存在强制场景设定时校验场景列表
  10035. if (!$validation_failed && !empty($extra_scenes)) {
  10036. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  10037. $expected_scenes = array_keys($extra_scenes);
  10038. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  10039. if (!empty($invalid_scenes)) {
  10040. $validation_failed = true;
  10041. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  10042. }
  10043. }
  10044. // 仅当存在强制道具设定时校验道具列表
  10045. if (!$validation_failed && !empty($extra_props)) {
  10046. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  10047. $expected_props = array_keys($extra_props);
  10048. $invalid_props = array_diff($generated_props, $expected_props);
  10049. if (!empty($invalid_props)) {
  10050. $validation_failed = true;
  10051. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  10052. }
  10053. }
  10054. }
  10055. } else {
  10056. if (empty($episode_arr['acts'])) {
  10057. $validation_failed = true;
  10058. $validation_error_msg = '未生成分镜剧本相关的内容';
  10059. } else {
  10060. // 校验主体列表:不能为空主体(旁白不算)
  10061. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10062. // 过滤掉"旁白"角色
  10063. $generated_roles = array_filter($generated_roles, function($role) {
  10064. return $role !== '旁白';
  10065. });
  10066. if (empty($generated_roles)) {
  10067. $validation_failed = true;
  10068. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10069. }
  10070. }
  10071. }
  10072. } catch (\Exception $e) {
  10073. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  10074. 'trace' => $e->getTraceAsString()
  10075. ]);
  10076. break;
  10077. }
  10078. }
  10079. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  10080. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  10081. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  10082. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  10083. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  10084. if ($validation_failed && $retry_count >= $max_retries) {
  10085. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  10086. 'retry_count' => $retry_count,
  10087. 'last_error' => $validation_error_msg
  10088. ]);
  10089. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  10090. 'error' => $validation_error_msg,
  10091. 'anime_id' => $anime_id
  10092. ]);
  10093. $validation_failed = false;
  10094. $validation_error_msg = '';
  10095. }
  10096. // 如果重试后仍然失败
  10097. if ($validation_failed) {
  10098. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  10099. 'retry_count' => $retry_count,
  10100. 'last_error' => $validation_error_msg
  10101. ]);
  10102. try {
  10103. $now = date('Y-m-d H:i:s');
  10104. $records = [
  10105. [
  10106. 'uid' => $uid,
  10107. 'anime_id' => $anime_id,
  10108. 'sequence' => $episode_number,
  10109. 'role' => 'user',
  10110. 'content' => $prompt,
  10111. 'created_at' => $now,
  10112. 'updated_at' => $now
  10113. ],
  10114. [
  10115. 'uid' => $uid,
  10116. 'anime_id' => $anime_id,
  10117. 'sequence' => $episode_number,
  10118. 'role' => 'assistant',
  10119. 'content' => $fullContent,
  10120. 'created_at' => $now,
  10121. 'updated_at' => $now
  10122. ]
  10123. ];
  10124. DB::table('mp_anime_records')->insert($records);
  10125. } catch (\Exception $e) {
  10126. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  10127. }
  10128. yield [
  10129. 'type' => 'done',
  10130. 'episode' => [],
  10131. 'answer' => $fullContent,
  10132. 'reasoning' => $fullReasoningContent,
  10133. 'usage' => $usage,
  10134. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  10135. ];
  10136. return;
  10137. }
  10138. // 验证成功,记录日志
  10139. if ($retry_count > 0) {
  10140. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  10141. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  10142. }
  10143. // 老逻辑
  10144. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  10145. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  10146. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  10147. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  10148. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  10149. $existing_props = is_array($existing_props) ? $existing_props : [];
  10150. $now = date('Y-m-d H:i:s');
  10151. try {
  10152. DB::beginTransaction();
  10153. $saveResult = $this->saveEpisodeVersionData(
  10154. $anime_id,
  10155. $episode_number,
  10156. $episode_arr,
  10157. $existing_roles,
  10158. $existing_scenes,
  10159. $existing_props,
  10160. $current_episode,
  10161. $base_episode,
  10162. $is_regenerate_version,
  10163. $content,
  10164. $now,
  10165. $ref_products
  10166. );
  10167. $episode = $saveResult['episode'];
  10168. $episode_id = $saveResult['episode_id'];
  10169. $merged_roles = $saveResult['merged_roles'];
  10170. $merged_scenes = $saveResult['merged_scenes'];
  10171. $merged_props = $saveResult['merged_props'];
  10172. $record_content = $origin_prompt;
  10173. if ($uploaded_content !== '') {
  10174. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  10175. }
  10176. $records = [
  10177. [
  10178. 'uid' => $uid,
  10179. 'anime_id' => $anime_id,
  10180. 'role' => 'user',
  10181. 'content' => $record_content,
  10182. 'sequence' => $episode_number,
  10183. 'episode_id' => $episode_id,
  10184. 'created_at' => $now,
  10185. 'updated_at' => $now
  10186. ],
  10187. [
  10188. 'uid' => $uid,
  10189. 'anime_id' => $anime_id,
  10190. 'role' => 'assistant',
  10191. 'content' => $fullContent,
  10192. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10193. 'sequence' => $episode_number,
  10194. 'episode_id' => $episode_id,
  10195. 'created_at' => $now,
  10196. 'updated_at' => $now
  10197. ]
  10198. ];
  10199. $boolen4 = DB::table('mp_anime_records')->insert($records);
  10200. if (!$boolen4) {
  10201. Utils::throwError('20003:对话记录保存失败');
  10202. }
  10203. // 保存模型到anime表
  10204. $update_anime_data = [
  10205. 'model' => $model,
  10206. 'updated_at' => $now
  10207. ];
  10208. if ($uploaded_content) {
  10209. $update_anime_data['content'] = $uploaded_content;
  10210. }
  10211. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  10212. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10213. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10214. 'anime_id' => $anime_id,
  10215. 'episode_number' => $episode_number,
  10216. 'model' => $model,
  10217. 'source' => 'chatForAce',
  10218. ]);
  10219. }catch (\Exception $e) {
  10220. DB::rollBack();
  10221. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  10222. yield [
  10223. 'type' => 'done',
  10224. 'answer' => $fullContent,
  10225. 'reasoning' => $fullReasoningContent,
  10226. 'usage' => $usage,
  10227. 'error' => $e->getMessage(),
  10228. ];
  10229. return;
  10230. }
  10231. DB::commit();
  10232. if ($is_global_generate_pics) {
  10233. // // 批量生成全局角色图片
  10234. // $this->batchSetGlobalRoleImg([
  10235. // 'anime_id' => $anime_id,
  10236. // ], true);
  10237. // // 批量生成全局场景图片
  10238. // $this->batchSetGlobalSceneImg([
  10239. // 'anime_id' => $anime_id,
  10240. // ], true);
  10241. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10242. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10243. }
  10244. $episode['episode_id'] = $episode_id;
  10245. $episode['roles'] = $merged_roles;
  10246. $episode['scenes'] = $merged_scenes;
  10247. $episode['props'] = $merged_props;
  10248. $episode['end_episode_sequence'] = $end_episode_sequence;
  10249. // 获取mp_animes表中的视频参数
  10250. $episode['video_params'] = [
  10251. 'video_model' => getProp($anime, 'video_model'),
  10252. 'video_resolution' => getProp($anime, 'video_resolution'),
  10253. 'ratio' => getProp($anime, 'video_ratio'),
  10254. ];
  10255. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10256. yield [
  10257. 'type' => 'done',
  10258. 'episode' => $episode,
  10259. 'answer' => $fullContent,
  10260. 'reasoning' => $fullReasoningContent,
  10261. 'usage' => $usage
  10262. ];
  10263. }
  10264. /**
  10265. * chatForAce的非流式版本 - 用于定时任务
  10266. * 只获取最终 type=done 的数据,并验证必要字段
  10267. *
  10268. * @param array $data 请求数据
  10269. * @return array 生成结果
  10270. */
  10271. public function chatForAceNonStream($data) {
  10272. $finalResult = null;
  10273. // 调用流式方法,只保存 type=done 的数据
  10274. foreach ($this->chatForAce($data) as $chunk) {
  10275. // 只关注最终结果
  10276. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  10277. $finalResult = $chunk;
  10278. break; // 找到 done 就退出循环
  10279. }
  10280. }
  10281. // 验证最终结果
  10282. if (!$finalResult) {
  10283. return ['error' => '生成失败:未获取到最终结果'];
  10284. }
  10285. // 检查是否有错误
  10286. if (isset($finalResult['error']) && $finalResult['error']) {
  10287. return $finalResult;
  10288. }
  10289. // 验证必要字段
  10290. $episode = $finalResult['episode'] ?? [];
  10291. // 验证 roles(旁白不算主体,过滤后不能为空)
  10292. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  10293. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  10294. }
  10295. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  10296. return $role !== '旁白';
  10297. });
  10298. if (empty($nonNarratorRoles)) {
  10299. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  10300. }
  10301. // 验证 scenes
  10302. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  10303. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  10304. }
  10305. // 验证 props(道具可以为空,但必须存在且为数组)
  10306. if (!isset($episode['props']) || !is_array($episode['props'])) {
  10307. $episode['props'] = [];
  10308. }
  10309. // 验证 acts(分镜剧本)
  10310. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  10311. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  10312. }
  10313. // 更新验证后的 episode 数据
  10314. $finalResult['episode'] = $episode;
  10315. // 记录验证成功日志
  10316. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  10317. 'roles_count' => count($episode['roles']),
  10318. 'scenes_count' => count($episode['scenes']),
  10319. 'props_count' => count($episode['props']),
  10320. 'acts_count' => count($episode['acts'])
  10321. ]);
  10322. return $finalResult;
  10323. }
  10324. /**
  10325. * 批量生成多个分集
  10326. *
  10327. * @param array $data 请求数据
  10328. * @return array 任务信息
  10329. */
  10330. public function batchGenerateEpisodes($data) {
  10331. $uid = Site::getUid();
  10332. $cpid = Site::getCpid();
  10333. $anime_id = getProp($data, 'anime_id');
  10334. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  10335. $start_episode_number = getProp($data, 'start_episode_number');
  10336. $end_episode_number = getProp($data, 'end_episode_number');
  10337. if (!$anime_id) {
  10338. Utils::throwError('20003:anime_id参数缺失');
  10339. }
  10340. if ($generate_episode_number < 1) {
  10341. Utils::throwError('20003:生成集数必须大于0');
  10342. }
  10343. // 获取动漫信息
  10344. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10345. if (!$anime) {
  10346. Utils::throwError('20003:该剧集不存在');
  10347. }
  10348. // 检查是否是全能模式
  10349. if ((int)getProp($anime, 'ace_mode') !== 1) {
  10350. Utils::throwError('20003:只有全能模式才支持批量生成');
  10351. }
  10352. // 检查是否是多剧集模式
  10353. if ((int)getProp($anime, 'is_multi') !== 1) {
  10354. Utils::throwError('20003:单剧集不支持批量生成');
  10355. }
  10356. // 指定起始/结束剧集序号时的校验
  10357. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  10358. || ($end_episode_number !== null && $end_episode_number !== '');
  10359. if ($hasSpecifiedRange) {
  10360. if ($start_episode_number === null || $start_episode_number === ''
  10361. || $end_episode_number === null || $end_episode_number === '') {
  10362. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  10363. }
  10364. $start_episode_number = (int)$start_episode_number;
  10365. $end_episode_number = (int)$end_episode_number;
  10366. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  10367. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  10368. }
  10369. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  10370. $currentMaxEpisode = DB::table('mp_anime_episodes')
  10371. ->where('anime_id', $anime_id)
  10372. ->where('is_default', 1)
  10373. ->max('episode_number');
  10374. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  10375. $nextEpisodeNumber = $currentMaxEpisode + 1;
  10376. if ($start_episode_number !== $nextEpisodeNumber) {
  10377. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  10378. }
  10379. $startEpisodeNumber = $start_episode_number;
  10380. $endEpisodeNumber = $end_episode_number;
  10381. } else {
  10382. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  10383. $currentMaxEpisode = DB::table('mp_anime_episodes')
  10384. ->where('anime_id', $anime_id)
  10385. ->where('is_default', 1)
  10386. ->max('episode_number');
  10387. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  10388. // 确定起始集数
  10389. $startEpisodeNumber = $currentMaxEpisode + 1;
  10390. // 计算结束集数
  10391. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  10392. }
  10393. // 本次实际生成的集数
  10394. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  10395. // 检查是否超过总集数限制
  10396. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  10397. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  10398. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  10399. }
  10400. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  10401. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  10402. ->where('anime_id', $anime_id)
  10403. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10404. ->pluck('episode_number')
  10405. ->unique()
  10406. ->sort()
  10407. ->values()
  10408. ->toArray();
  10409. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  10410. ->where('anime_id', $anime_id)
  10411. ->where('is_default', 1)
  10412. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10413. ->pluck('episode_number')
  10414. ->unique()
  10415. ->sort()
  10416. ->values()
  10417. ->toArray();
  10418. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  10419. $duplicateMessages = [];
  10420. if (!empty($duplicatedBatchEpisodes)) {
  10421. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  10422. }
  10423. if (!empty($duplicatedAnimeEpisodes)) {
  10424. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  10425. }
  10426. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  10427. }
  10428. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  10429. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  10430. ->where('anime_id', $anime_id)
  10431. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10432. ->whereIn('status', ['pending', 'processing', 'completed'])
  10433. ->count();
  10434. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  10435. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  10436. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  10437. if ($needEpisodeCount > 0) {
  10438. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  10439. }
  10440. $now = date('Y-m-d H:i:s');
  10441. $createdTasks = [];
  10442. $skippedTasks = [];
  10443. // 为每一集创建详情记录
  10444. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  10445. // 检查是否已有该集的任务记录
  10446. $existingTask = DB::table('mp_batch_episode_generation_details')
  10447. ->where('anime_id', $anime_id)
  10448. ->where('episode_number', $episodeNumber)
  10449. ->first();
  10450. if ($existingTask) {
  10451. // 如果已存在且未完成,跳过
  10452. if (in_array($existingTask->status, ['pending', 'processing'])) {
  10453. $skippedTasks[] = $episodeNumber;
  10454. continue;
  10455. }
  10456. // 如果是失败状态,可以重新创建(删除旧记录)
  10457. if ($existingTask->status === 'failed') {
  10458. DB::table('mp_batch_episode_generation_details')
  10459. ->where('id', $existingTask->id)
  10460. ->delete();
  10461. }
  10462. // 如果是已完成状态,也跳过
  10463. if ($existingTask->status === 'completed') {
  10464. $skippedTasks[] = $episodeNumber;
  10465. continue;
  10466. }
  10467. }
  10468. // 准备任务数据
  10469. $taskData = [
  10470. 'anime_id' => $anime_id,
  10471. 'uid' => $uid,
  10472. 'cpid' => $cpid,
  10473. 'episode_number' => $episodeNumber,
  10474. 'status' => 'pending',
  10475. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  10476. 'retry_count' => 0,
  10477. 'created_at' => $now,
  10478. 'updated_at' => $now
  10479. ];
  10480. // 创建任务记录
  10481. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  10482. if ($taskId) {
  10483. $createdTasks[] = $episodeNumber;
  10484. }
  10485. }
  10486. if (empty($createdTasks)) {
  10487. if (!empty($skippedTasks)) {
  10488. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  10489. } else {
  10490. Utils::throwError('20003:创建批量生成任务失败');
  10491. }
  10492. }
  10493. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  10494. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  10495. $uid,
  10496. $cpid,
  10497. $anime_id,
  10498. $generate_episode_number,
  10499. $startEpisodeNumber,
  10500. $endEpisodeNumber
  10501. );
  10502. return [
  10503. 'anime_id' => $anime_id,
  10504. 'start_episode' => $startEpisodeNumber,
  10505. 'end_episode' => $endEpisodeNumber,
  10506. 'total_episodes' => $totalEpisodeCount,
  10507. 'created_episodes' => $createdTasks,
  10508. 'skipped_episodes' => $skippedTasks,
  10509. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  10510. "已创建: " . implode(',', $createdTasks) .
  10511. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  10512. 'task_center_id' => $taskCenterId
  10513. ];
  10514. }
  10515. /**
  10516. * 根据入参创建或复用批量生成分集的任务中心记录
  10517. *
  10518. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  10519. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  10520. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  10521. *
  10522. * @param int|string $uid
  10523. * @param int|string $cpid
  10524. * @param int|string $anime_id
  10525. * @param int $generate_episode_number
  10526. * @param int $startEpisodeNumber
  10527. * @param int $endEpisodeNumber
  10528. * @return int 任务中心ID
  10529. */
  10530. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  10531. $params = [
  10532. 'anime_id' => (int)$anime_id,
  10533. 'generate_episode_number' => (int)$generate_episode_number,
  10534. 'start_episode' => (int)$startEpisodeNumber,
  10535. 'end_episode' => (int)$endEpisodeNumber,
  10536. ];
  10537. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  10538. $paramsMd5 = md5(json_encode([
  10539. 'anime_id' => (int)$anime_id,
  10540. 'generate_episode_number' => (int)$generate_episode_number,
  10541. 'start_episode' => (int)$startEpisodeNumber,
  10542. 'end_episode' => (int)$endEpisodeNumber,
  10543. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  10544. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  10545. $existing = DB::table('mp_task_center')
  10546. ->where('uid', (int)$uid)
  10547. ->where('cpid', (int)$cpid)
  10548. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10549. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10550. ->where('params_md5', $paramsMd5)
  10551. ->orderBy('id', 'desc')
  10552. ->first();
  10553. if ($existing) {
  10554. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  10555. 'anime_id' => $anime_id,
  10556. 'task_center_id' => $existing->id,
  10557. 'params_md5' => $paramsMd5,
  10558. ]);
  10559. return (int)$existing->id;
  10560. }
  10561. $now = date('Y-m-d H:i:s');
  10562. DB::table('mp_task_center')->insertOrIgnore([
  10563. 'uid' => (int)$uid,
  10564. 'cpid' => (int)$cpid,
  10565. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  10566. 'title' => '批量生成分集',
  10567. 'ref_task_id' => 0,
  10568. 'status' => MpTaskCenter::STATUS_PROCESSING,
  10569. 'result' => null,
  10570. 'error_message' => null,
  10571. 'prompt' => null,
  10572. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  10573. 'params_md5' => $paramsMd5,
  10574. 'created_at' => $now,
  10575. 'updated_at' => $now,
  10576. ]);
  10577. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  10578. $taskId = (int)DB::table('mp_task_center')
  10579. ->where('uid', (int)$uid)
  10580. ->where('cpid', (int)$cpid)
  10581. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10582. ->where('params_md5', $paramsMd5)
  10583. ->orderBy('id', 'desc')
  10584. ->value('id');
  10585. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  10586. 'anime_id' => $anime_id,
  10587. 'task_center_id' => $taskId,
  10588. 'params_md5' => $paramsMd5,
  10589. ]);
  10590. return $taskId;
  10591. }
  10592. /**
  10593. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  10594. *
  10595. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  10596. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  10597. * 统一汇总更新,避免在每个更新点重复处理。
  10598. *
  10599. * @param int|string $animeId
  10600. * @return int 更新的任务中心记录数
  10601. */
  10602. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  10603. $animeId = (int)$animeId;
  10604. $updated = 0;
  10605. // 该 anime 是否还有未结束的详情任务
  10606. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  10607. ->where('anime_id', $animeId)
  10608. ->whereIn('status', ['pending', 'processing'])
  10609. ->exists();
  10610. // 扫描该 anime 相关的未完成任务中心记录
  10611. $tasks = DB::table('mp_task_center')
  10612. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10613. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10614. ->orderBy('id', 'desc')
  10615. ->limit(500)
  10616. ->get();
  10617. if ($hasUnfinished && !$tasks) {
  10618. return 0;
  10619. }
  10620. foreach ($tasks as $task) {
  10621. try {
  10622. $taskParams = json_decode((string)$task->params, true);
  10623. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  10624. continue;
  10625. }
  10626. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  10627. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  10628. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  10629. continue;
  10630. }
  10631. $details = DB::table('mp_batch_episode_generation_details')
  10632. ->where('anime_id', $animeId)
  10633. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  10634. ->get();
  10635. // 该批次范围内存在缺失记录,等待下一次检查
  10636. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  10637. continue;
  10638. }
  10639. $completedEpisodes = [];
  10640. $failedEpisodes = [];
  10641. $allFinished = true;
  10642. foreach ($details as $detail) {
  10643. if ($detail->status === 'completed') {
  10644. $completedEpisodes[] = $detail->episode_number;
  10645. } elseif ($detail->status === 'failed') {
  10646. $failedEpisodes[] = [
  10647. 'episode_number' => $detail->episode_number,
  10648. 'error_message' => $detail->error_message ?? '',
  10649. ];
  10650. } else {
  10651. // pending/processing(防御处理,正常不会走到)
  10652. $allFinished = false;
  10653. break;
  10654. }
  10655. }
  10656. if (!$allFinished) {
  10657. continue;
  10658. }
  10659. $result = json_encode([
  10660. 'anime_id' => $animeId,
  10661. 'start_episode' => $startEpisode,
  10662. 'end_episode' => $endEpisode,
  10663. 'total_episodes' => count($details),
  10664. 'completed_count' => count($completedEpisodes),
  10665. 'failed_count' => count($failedEpisodes),
  10666. 'completed_episodes' => $completedEpisodes,
  10667. 'failed_episodes' => $failedEpisodes,
  10668. ], JSON_UNESCAPED_UNICODE);
  10669. DB::table('mp_task_center')
  10670. ->where('id', $task->id)
  10671. ->update([
  10672. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  10673. 'result' => $result,
  10674. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  10675. 'updated_at' => date('Y-m-d H:i:s'),
  10676. ]);
  10677. $updated++;
  10678. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  10679. 'task_center_id' => $task->id,
  10680. 'anime_id' => $animeId,
  10681. 'start_episode' => $startEpisode,
  10682. 'end_episode' => $endEpisode,
  10683. ]);
  10684. } catch (\Exception $e) {
  10685. dLog('command')->error('更新批量生成分集任务中心异常', [
  10686. 'task_center_id' => $task->id,
  10687. 'anime_id' => $animeId,
  10688. 'error' => $e->getMessage(),
  10689. ]);
  10690. }
  10691. }
  10692. return $updated;
  10693. }
  10694. /**
  10695. * 获取批量生成任务状态
  10696. *
  10697. * @param array $data 请求数据
  10698. * @return array 任务状态信息
  10699. */
  10700. public function getBatchGenerationTaskStatus($data) {
  10701. $anime_id = getProp($data, 'anime_id');
  10702. if (!$anime_id) {
  10703. Utils::throwError('20003:anime_id参数缺失');
  10704. }
  10705. // 获取该anime的所有任务
  10706. $tasks = DB::table('mp_batch_episode_generation_details')
  10707. ->where('anime_id', $anime_id)
  10708. ->orderBy('episode_number')
  10709. ->get()
  10710. ->map(function($item) {
  10711. return [
  10712. 'id' => $item->id,
  10713. 'episode_number' => $item->episode_number,
  10714. 'status' => $item->status,
  10715. 'error_message' => $item->error_message,
  10716. 'retry_count' => $item->retry_count,
  10717. 'created_at' => $item->created_at,
  10718. 'updated_at' => $item->updated_at,
  10719. 'completed_at' => $item->completed_at
  10720. ];
  10721. })
  10722. ->toArray();
  10723. if (empty($tasks)) {
  10724. Utils::throwError('20003:该剧集没有批量生成任务');
  10725. }
  10726. // 统计各状态数量
  10727. $totalCount = count($tasks);
  10728. $pendingCount = 0;
  10729. $processingCount = 0;
  10730. $completedCount = 0;
  10731. $failedCount = 0;
  10732. $failed_episodes = [];
  10733. foreach ($tasks as $task) {
  10734. switch ($task['status']) {
  10735. case 'pending':
  10736. $pendingCount++;
  10737. break;
  10738. case 'processing':
  10739. $processingCount++;
  10740. break;
  10741. case 'completed':
  10742. $completedCount++;
  10743. break;
  10744. case 'failed':
  10745. $failedCount++;
  10746. // 组装失败分集对象(新对象):分集序号、错误原因
  10747. $failed_episodes[] = [
  10748. 'episode_number' => $task['episode_number'],
  10749. 'error_message' => $task['error_message'] ?? ''
  10750. ];
  10751. break;
  10752. }
  10753. }
  10754. // 计算进度百分比
  10755. $progress = 0;
  10756. if ($totalCount > 0) {
  10757. $progress = round(($completedCount / $totalCount) * 100, 2);
  10758. }
  10759. // 判断整体状态
  10760. $overallStatus = 'processing';
  10761. if ($completedCount === $totalCount) {
  10762. $overallStatus = 'completed';
  10763. } elseif ($pendingCount === $totalCount) {
  10764. $overallStatus = 'pending';
  10765. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  10766. $overallStatus = 'failed';
  10767. }
  10768. return [
  10769. 'anime_id' => $anime_id,
  10770. 'total_episodes' => $totalCount,
  10771. 'pending_count' => $pendingCount,
  10772. 'processing_count' => $processingCount,
  10773. 'completed_count' => $completedCount,
  10774. 'failed_count' => $failedCount,
  10775. 'progress' => $progress,
  10776. 'overall_status' => $overallStatus,
  10777. 'failed_episodes' => $failed_episodes,
  10778. 'tasks' => $tasks
  10779. ];
  10780. }
  10781. /**
  10782. * 将生成内容中不在强制列表中的资源合并进强制列表
  10783. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  10784. *
  10785. * @param array $generated 生成内容中的资源列表
  10786. * @param array $forced 强制资源列表(key为资源名称)
  10787. * @param string $type 资源类型:role、scene、prop
  10788. * @return array
  10789. */
  10790. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  10791. {
  10792. foreach ($generated as $item) {
  10793. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  10794. if ($name === null || $name === '') {
  10795. continue;
  10796. }
  10797. if ($name === '旁白') {
  10798. continue;
  10799. }
  10800. if (!isset($forced[$name])) {
  10801. $forced[$name] = $item;
  10802. }
  10803. }
  10804. return $forced;
  10805. }
  10806. /**
  10807. * 智能匹配并替换主体和场景名称
  10808. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10809. *
  10810. * @param array $episode_arr 解析后的剧集数据
  10811. * @param array $extra_roles 强制主体设定(key为主体名称)
  10812. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10813. * @return array 替换后的剧集数据
  10814. */
  10815. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10816. $replaced_count = 0;
  10817. // 1. 处理主体列表
  10818. if (!empty($episode_arr['roles'])) {
  10819. foreach ($episode_arr['roles'] as &$role) {
  10820. $generated_role_name = $role['role'] ?? '';
  10821. // 跳过旁白
  10822. if ($generated_role_name === '旁白') {
  10823. continue;
  10824. }
  10825. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10826. if (!isset($extra_roles[$generated_role_name])) {
  10827. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10828. if ($matched_role) {
  10829. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10830. $role['role'] = $matched_role;
  10831. $replaced_count++;
  10832. }
  10833. }
  10834. }
  10835. }
  10836. // 2. 处理场景列表
  10837. if (!empty($episode_arr['scenes'])) {
  10838. foreach ($episode_arr['scenes'] as &$scene) {
  10839. $generated_scene_name = $scene['scene'] ?? '';
  10840. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10841. if (!isset($extra_scenes[$generated_scene_name])) {
  10842. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10843. if ($matched_scene) {
  10844. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10845. $scene['scene'] = $matched_scene;
  10846. $replaced_count++;
  10847. }
  10848. }
  10849. }
  10850. }
  10851. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10852. if (!empty($episode_arr['acts'])) {
  10853. foreach ($episode_arr['acts'] as &$act) {
  10854. if (!empty($act['segments'])) {
  10855. foreach ($act['segments'] as &$segment) {
  10856. if (!empty($segment['segment_content'])) {
  10857. $original_content = $segment['segment_content'];
  10858. $replaced_content = $original_content;
  10859. // 替换场景名 - 在文本中查找并替换
  10860. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10861. // 尝试找到可能的短名称
  10862. $potential_short_names = [];
  10863. // 提取场景名的主要部分(冒号之前)
  10864. if (mb_strpos($full_scene_name, ':') !== false) {
  10865. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10866. $potential_short_names[] = $short_name;
  10867. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10868. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10869. $potential_short_names[] = $short_name;
  10870. }
  10871. // 替换场景字段中的短名称
  10872. foreach ($potential_short_names as $short_name) {
  10873. if ($short_name !== $full_scene_name) {
  10874. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10875. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10876. if ($new_content !== $replaced_content) {
  10877. $replaced_content = $new_content;
  10878. $replaced_count++;
  10879. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10880. }
  10881. }
  10882. }
  10883. }
  10884. // 替换配音角色名(跳过旁白)
  10885. foreach (array_keys($extra_roles) as $full_role_name) {
  10886. if ($full_role_name === '旁白') {
  10887. continue;
  10888. }
  10889. // 尝试找到可能的短名称
  10890. $potential_short_names = [];
  10891. // 提取角色名的主要部分(短横线之前)
  10892. if (mb_strpos($full_role_name, '-') !== false) {
  10893. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10894. $potential_short_names[] = $short_name;
  10895. }
  10896. // 替换配音台词中的短名称
  10897. foreach ($potential_short_names as $short_name) {
  10898. if ($short_name !== $full_role_name) {
  10899. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10900. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10901. if ($new_content !== $replaced_content) {
  10902. $replaced_content = $new_content;
  10903. $replaced_count++;
  10904. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10905. }
  10906. }
  10907. }
  10908. }
  10909. // 如果有替换,更新segment_content
  10910. if ($replaced_content !== $original_content) {
  10911. $segment['segment_content'] = $replaced_content;
  10912. }
  10913. }
  10914. }
  10915. }
  10916. }
  10917. }
  10918. if ($replaced_count > 0) {
  10919. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10920. 'replaced_count' => $replaced_count
  10921. ]);
  10922. }
  10923. return $episode_arr;
  10924. }
  10925. /**
  10926. * 查找匹配的名称
  10927. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10928. *
  10929. * @param string $generated_name 生成的名称
  10930. * @param array $expected_names 预期的名称列表
  10931. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10932. */
  10933. private function findMatchingName($generated_name, $expected_names) {
  10934. if (empty($generated_name)) {
  10935. return null;
  10936. }
  10937. // 尝试精确匹配
  10938. if (in_array($generated_name, $expected_names)) {
  10939. return $generated_name;
  10940. }
  10941. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10942. foreach ($expected_names as $expected_name) {
  10943. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10944. if (mb_strpos($expected_name, $generated_name) === 0) {
  10945. return $expected_name;
  10946. }
  10947. }
  10948. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10949. // 这样可以处理一些变体,但优先级较低
  10950. foreach ($expected_names as $expected_name) {
  10951. if (mb_strpos($expected_name, $generated_name) !== false) {
  10952. return $expected_name;
  10953. }
  10954. }
  10955. return null;
  10956. }
  10957. /**
  10958. * 重新生成分段剧本
  10959. * @param array $data 包含以下字段:
  10960. * - prompt: string|null 用户修改要求(可选)
  10961. * - template_id: int|null 提示词模板ID(可选)
  10962. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10963. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10964. * @return array 返回生成结果
  10965. */
  10966. public function regenerateSegmentScript($data) {
  10967. $uid = Site::getUid();
  10968. $prompt = trim((string)getProp($data, 'prompt', ''));
  10969. $template_id = getProp($data, 'template_id', 0);
  10970. $act_id = getProp($data, 'act_id', 0);
  10971. $episode_id = getProp($data, 'episode_id', 0);
  10972. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  10973. // 验证:prompt和template_id至少提供一个
  10974. if (empty($prompt) && empty($template_id)) {
  10975. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10976. }
  10977. // 验证:act_id和episode_id二选一
  10978. if (empty($act_id) && empty($episode_id)) {
  10979. Utils::throwError('20003:请提供片段ID或剧集ID');
  10980. }
  10981. if (!empty($act_id) && !empty($episode_id)) {
  10982. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10983. }
  10984. // 积分余额预检(仅剧集ID模式收费)
  10985. if (!empty($episode_id)) {
  10986. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  10987. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  10988. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10989. }
  10990. // 如果提供了template_id,获取模板提示词
  10991. $template_prompt = '';
  10992. if ($template_id > 0) {
  10993. $template = DB::table('mp_prompt_templates')
  10994. ->where('id', $template_id)
  10995. ->where('is_deleted', 0)
  10996. ->first();
  10997. if (!$template) {
  10998. Utils::throwError('20003:提示词模板不存在或已删除');
  10999. }
  11000. $template_prompt = $template->template_prompt ?? '';
  11001. }
  11002. // 合并用户提示词和模板提示词
  11003. $final_prompt = '';
  11004. if (!empty($template_prompt)) {
  11005. $final_prompt = $template_prompt;
  11006. if (!empty($prompt)) {
  11007. $final_prompt .= "\n\n补充要求:" . $prompt;
  11008. }
  11009. } else {
  11010. $final_prompt = $prompt;
  11011. }
  11012. // 获取需要重新生成的内容参考
  11013. $reference_content = '';
  11014. $target_episode_id = 0;
  11015. $target_anime_id = 0;
  11016. $target_episode_number = 0;
  11017. if ($act_id > 0) {
  11018. // 单个片段模式:获取该片段的内容
  11019. $segment = DB::table('mp_episode_segments')
  11020. ->where('id', $act_id)
  11021. ->first();
  11022. if (!$segment) {
  11023. Utils::throwError('20003:片段不存在');
  11024. }
  11025. $target_episode_id = $segment->episode_id;
  11026. $target_anime_id = $segment->anime_id;
  11027. $target_episode_number = $segment->episode_number;
  11028. $reference_content = $segment->act_content ?? '';
  11029. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  11030. } else {
  11031. // 整个剧集模式:获取所有片段的内容
  11032. $segments = DB::table('mp_episode_segments')
  11033. ->where('episode_id', $episode_id)
  11034. ->orderBy('act_number')
  11035. ->get();
  11036. if ($segments->isEmpty()) {
  11037. Utils::throwError('20003:该剧集没有片段数据');
  11038. }
  11039. $target_episode_id = $episode_id;
  11040. $target_anime_id = $segments[0]->anime_id;
  11041. $target_episode_number = $segments[0]->episode_number;
  11042. // 拼接所有片段内容,保留格式用于AI理解
  11043. $act_contents = [];
  11044. foreach ($segments as $seg) {
  11045. $act_number = $seg->act_number;
  11046. $act_content = $seg->act_content ?? '';
  11047. if (!empty($act_content)) {
  11048. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  11049. }
  11050. }
  11051. $reference_content = implode("\n\n", $act_contents);
  11052. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  11053. if ($episode_content) {
  11054. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  11055. }else {
  11056. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  11057. }
  11058. }
  11059. if (empty($reference_content)) {
  11060. Utils::throwError('20003:没有可参考的片段内容');
  11061. }
  11062. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  11063. $episode = DB::table('mp_anime_episodes')
  11064. ->where('id', $target_episode_id)
  11065. ->first();
  11066. if (!$episode) {
  11067. Utils::throwError('20003:剧集不存在');
  11068. }
  11069. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  11070. $anime_script_id = getProp($anime, 'script_id');
  11071. $intro = $episode->intro ?? '';
  11072. $art_style = $episode->art_style ?? '';
  11073. $roles = json_decode($episode->roles ?? '[]', true);
  11074. $scenes = json_decode($episode->scenes ?? '[]', true);
  11075. $props = json_decode($episode->props ?? '[]', true);
  11076. // 构建提示词中的主体列表和场景列表参考
  11077. $roles_ref = '';
  11078. if (!empty($roles) && is_array($roles)) {
  11079. $roles_list = [];
  11080. foreach ($roles as $role) {
  11081. $role_name = getProp($role, 'role', '');
  11082. $role_desc = getProp($role, 'description', '');
  11083. $pic_prompt = getProp($role, 'pic_prompt', '');
  11084. $voice_prompt = getProp($role, 'voice_prompt', '');
  11085. if (!empty($role_name)) {
  11086. $role_line = $role_name;
  11087. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  11088. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  11089. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  11090. $roles_list[] = $role_line;
  11091. }
  11092. }
  11093. if (!empty($roles_list)) {
  11094. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  11095. }
  11096. }
  11097. $scenes_ref = '';
  11098. if (!empty($scenes) && is_array($scenes)) {
  11099. $scenes_list = [];
  11100. foreach ($scenes as $scene) {
  11101. $scene_name = getProp($scene, 'scene', '');
  11102. $scene_desc = getProp($scene, 'description', '');
  11103. $pic_prompt = getProp($scene, 'pic_prompt', '');
  11104. if (!empty($scene_name)) {
  11105. $scene_line = $scene_name;
  11106. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  11107. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  11108. $scenes_list[] = $scene_line;
  11109. }
  11110. }
  11111. if (!empty($scenes_list)) {
  11112. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  11113. }
  11114. }
  11115. $props_ref = '';
  11116. if (!empty($props) && is_array($props)) {
  11117. $props_list = [];
  11118. foreach ($props as $prop) {
  11119. $prop_name = getProp($prop, 'prop', '');
  11120. $prop_desc = getProp($prop, 'description', '');
  11121. $pic_prompt = getProp($prop, 'pic_prompt', '');
  11122. if (!empty($prop_name)) {
  11123. $prop_line = $prop_name;
  11124. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  11125. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  11126. $props_list[] = $prop_line;
  11127. }
  11128. }
  11129. if (!empty($props_list)) {
  11130. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  11131. }
  11132. }
  11133. // 构建美术风格参考
  11134. $art_style_ref = '';
  11135. if (!empty($art_style)) {
  11136. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  11137. }
  11138. // 构建内容简介参考
  11139. $intro_ref = '';
  11140. if (!empty($intro)) {
  11141. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  11142. }
  11143. // 构建完整的AI提示词
  11144. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  11145. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  11146. $user_prompt .= $intro_ref;
  11147. $user_prompt .= $art_style_ref;
  11148. $user_prompt .= $reference_content;
  11149. // $user_prompt .= $roles_ref;
  11150. // $user_prompt .= $scenes_ref;
  11151. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  11152. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  11153. if ($act_id > 0) {
  11154. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  11155. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  11156. } else {
  11157. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  11158. }
  11159. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  11160. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  11161. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  11162. if ($act_id > 0) {
  11163. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  11164. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  11165. } else {
  11166. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  11167. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  11168. }
  11169. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  11170. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  11171. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  11172. $system_prompt .= "【强制要求】\n";
  11173. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  11174. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  11175. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  11176. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  11177. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  11178. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  11179. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  11180. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  11181. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  11182. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  11183. $segmentHeader = '';
  11184. if ($episode_id > 0) {
  11185. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  11186. }
  11187. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:\n" . $segmentHeader . "##片段1\n时长:12s\n分镜1\n出场角色:刀疤脸\n场景:边境小镇街道\n出场道具:酒杯-高脚杯\n画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。\n运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。\n配音台词:\n背景音效:\n\n分镜2\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。\n运镜:缓慢横移,掠过阴影中瑟缩的食客。\n配音台词:\n背景音效:\n\n分镜3\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。\n运镜:从中景推向令牌特写。\n配音台词:\n背景音效:\n\n分镜4\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。\n运镜:极速推向酒水溅起的瞬间。\n配音台词:\n背景音效:\n\n分镜5\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。\n运镜:固定机位,利用倾斜构图制造压迫感。\n配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?\n背景音效:";
  11188. // 获取模型配置
  11189. $model = getProp($data, 'model');
  11190. if (!$model) {
  11191. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  11192. }
  11193. // 验证模型是否在可用模型表中
  11194. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11195. $model = 'deepseek-v4-pro';
  11196. }
  11197. // 模型兼容性处理
  11198. $thinkingMode = 'disabled';
  11199. $reasoningEffort = 'high';
  11200. if ($model === 'deepseek-chat') {
  11201. $model = 'deepseek-v4-flash';
  11202. $thinkingMode = 'disabled';
  11203. } elseif ($model === 'deepseek-reasoner') {
  11204. $model = 'deepseek-v4-flash';
  11205. $thinkingMode = 'enabled';
  11206. }
  11207. // 构建消息
  11208. $messages = [
  11209. [
  11210. 'role' => 'system',
  11211. 'content' => $system_prompt
  11212. ],
  11213. [
  11214. 'role' => 'user',
  11215. 'content' => $user_prompt
  11216. ]
  11217. ];
  11218. // dd($messages);
  11219. // 构建请求参数
  11220. $post_data = [
  11221. 'model' => $model,
  11222. 'messages' => $messages,
  11223. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11224. 'frequency_penalty' => 0,
  11225. 'presence_penalty' => 0,
  11226. 'response_format' => ['type' => 'text'],
  11227. 'thinking' => ['type' => $thinkingMode],
  11228. 'stream' => false // 非流式输出
  11229. ];
  11230. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11231. // 调用AI生成新的分段剧本
  11232. try {
  11233. $fullContent = '';
  11234. $usage = [];
  11235. // 根据模型类型选择调用方法
  11236. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11237. // DeepSeek 官方模型使用 DeepSeek API
  11238. $chatResult = $this->chatOnly($post_data);
  11239. } else if (in_array($model, $this->gpt_text_models)) {
  11240. // GPT 模型使用 TokenRouter API
  11241. $chatResult = $this->gpt54ChatOnly($post_data);
  11242. } else {
  11243. // 其他模型使用火山引擎API
  11244. $chatResult = $this->volcEngineChatCompletion($post_data);
  11245. }
  11246. if (is_array($chatResult)) {
  11247. $fullContent = $chatResult['fullContent'] ?? '';
  11248. $usage = $chatResult['usage'] ?? [];
  11249. }
  11250. $generated_content = $fullContent;
  11251. if (empty($generated_content)) {
  11252. Utils::throwError('20003:AI生成内容为空,请重试');
  11253. }
  11254. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  11255. 'act_id' => $act_id,
  11256. 'episode_id' => $episode_id,
  11257. 'content_length' => mb_strlen($generated_content),
  11258. 'content_head' => mb_substr($generated_content, 0, 500),
  11259. 'content_tail' => mb_substr($generated_content, -200),
  11260. ]);
  11261. // 解析生成的内容 - 按片段分割
  11262. $parsed_segments = [];
  11263. // 先在开头添加换行符,确保第1片段也能被正确分割
  11264. $normalizedText = "\n" . $generated_content;
  11265. $parts = preg_split('/\n\s*##/', $normalizedText);
  11266. foreach ($parts as $part) {
  11267. $part = trim($part);
  11268. if (empty($part)) continue;
  11269. // 匹配"片段X"格式
  11270. if (!preg_match('/^片段\d+/', $part)) {
  11271. continue;
  11272. }
  11273. // 分离标题和内容
  11274. $lines = explode("\n", $part, 2);
  11275. $actTitle = trim($lines[0]);
  11276. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  11277. // 解析标题,提取序号
  11278. $actNumber = 0;
  11279. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  11280. $actNumber = intval($segmentTitleMatch[1]);
  11281. } else {
  11282. $actNumber = count($parsed_segments) + 1;
  11283. }
  11284. // 提取时长(仅保留数字)
  11285. $actDuration = 0;
  11286. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  11287. $actDurationStr = trim($actDurationMatch[1]);
  11288. // 提取数字部分(支持整数和小数)
  11289. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  11290. $actDuration = (float)$numMatch[1];
  11291. }
  11292. }
  11293. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  11294. if ($actDuration > 15) {
  11295. $actDuration = 15;
  11296. }
  11297. if ($actDuration < 4) {
  11298. $actDuration = 4;
  11299. }
  11300. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  11301. $cleaned_content = $this->cleanSegmentContent($actContent);
  11302. $parsed_segments[] = [
  11303. 'act_number' => $actNumber,
  11304. 'act_title' => $actTitle,
  11305. 'act_duration' => $actDuration,
  11306. 'act_content' => $cleaned_content,
  11307. ];
  11308. }
  11309. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  11310. if (empty($parsed_segments)) {
  11311. $fallbackContent = $this->cleanSegmentContent($generated_content);
  11312. if ($fallbackContent !== '') {
  11313. $fallbackDuration = 0;
  11314. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  11315. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  11316. $fallbackDuration = (float)$numMatch[1];
  11317. }
  11318. }
  11319. // 内容未带时长时,单片段模式沿用原片段的时长
  11320. if ($fallbackDuration <= 0 && $act_id > 0 && !empty($segment->act_duration)) {
  11321. $fallbackDuration = (float)$segment->act_duration;
  11322. }
  11323. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  11324. if ($fallbackDuration > 15) {
  11325. $fallbackDuration = 15;
  11326. }
  11327. if ($fallbackDuration < 4) {
  11328. $fallbackDuration = 4;
  11329. }
  11330. $parsed_segments[] = [
  11331. 'act_number' => 1,
  11332. 'act_title' => '片段1',
  11333. 'act_duration' => $fallbackDuration,
  11334. 'act_content' => $fallbackContent,
  11335. ];
  11336. }
  11337. }
  11338. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  11339. if ($act_id > 0 && count($parsed_segments) > 1) {
  11340. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  11341. 'act_id' => $act_id,
  11342. 'original_count' => count($parsed_segments),
  11343. ]);
  11344. $parsed_segments = array_slice($parsed_segments, 0, 1);
  11345. }
  11346. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  11347. 'act_id' => $act_id,
  11348. 'episode_id' => $episode_id,
  11349. 'segment_count' => count($parsed_segments),
  11350. 'segments' => array_map(function ($seg) {
  11351. return [
  11352. 'act_number' => $seg['act_number'],
  11353. 'act_duration' => $seg['act_duration'],
  11354. 'content_length' => mb_strlen($seg['act_content']),
  11355. ];
  11356. }, $parsed_segments),
  11357. ]);
  11358. if (empty($parsed_segments)) {
  11359. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  11360. 'act_id' => $act_id,
  11361. 'episode_id' => $episode_id,
  11362. 'content_length' => mb_strlen($generated_content),
  11363. 'content_head' => mb_substr($generated_content, 0, 1000),
  11364. 'content_tail' => mb_substr($generated_content, -300),
  11365. ]);
  11366. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  11367. }
  11368. // 收集所有资产名称(角色、场景、道具)
  11369. $product_names = [];
  11370. // 收集角色名称
  11371. if (!empty($roles) && is_array($roles)) {
  11372. foreach ($roles as $role) {
  11373. $role_name = getProp($role, 'role', '');
  11374. if (!empty($role_name)) {
  11375. $product_names[] = $role_name;
  11376. }
  11377. }
  11378. }
  11379. // 收集场景名称
  11380. if (!empty($scenes) && is_array($scenes)) {
  11381. foreach ($scenes as $scene) {
  11382. $scene_name = getProp($scene, 'scene', '');
  11383. if (!empty($scene_name)) {
  11384. $product_names[] = $scene_name;
  11385. }
  11386. }
  11387. }
  11388. // 收集道具名称
  11389. if (!empty($props) && is_array($props)) {
  11390. foreach ($props as $prop) {
  11391. $prop_name = getProp($prop, 'prop', '');
  11392. if (!empty($prop_name)) {
  11393. $product_names[] = $prop_name;
  11394. }
  11395. }
  11396. }
  11397. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  11398. $product_names = array_unique($product_names);
  11399. usort($product_names, function($a, $b) {
  11400. return mb_strlen($b) - mb_strlen($a);
  11401. });
  11402. // 处理每个片段的 act_show_content
  11403. foreach ($parsed_segments as &$segment) {
  11404. $act_content = getProp($segment, 'act_content', '');
  11405. if (empty($act_content)) {
  11406. $segment['act_show_content'] = '';
  11407. continue;
  11408. }
  11409. $processed_content = $act_content;
  11410. // 统一替换所有资产名称为 {资产名} 格式
  11411. // 使用占位符避免嵌套替换问题
  11412. $placeholder_map = [];
  11413. $placeholder_index = 0;
  11414. foreach ($product_names as $product_name) {
  11415. // 转义特殊字符
  11416. $escaped_product = preg_quote($product_name, '/');
  11417. // 检查是否匹配且未被 {} 包裹
  11418. $processed_content = preg_replace_callback(
  11419. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  11420. function($matches) use (&$placeholder_map, &$placeholder_index) {
  11421. // 使用唯一占位符
  11422. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  11423. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  11424. $placeholder_index++;
  11425. return $placeholder;
  11426. },
  11427. $processed_content
  11428. );
  11429. }
  11430. // 将所有占位符替换回实际内容
  11431. foreach ($placeholder_map as $placeholder => $replacement) {
  11432. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  11433. }
  11434. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  11435. $shot_counter = 0;
  11436. $processed_content = preg_replace_callback(
  11437. '/【(?:镜头|分镜)(\d+)】/u',
  11438. function($matches) use (&$shot_counter) {
  11439. $shot_counter++;
  11440. return '【镜头' . $shot_counter . '】';
  11441. },
  11442. $processed_content
  11443. );
  11444. $segment['act_show_content'] = $processed_content;
  11445. }
  11446. unset($segment); // 解除引用
  11447. // 保存到数据库
  11448. $now = date('Y-m-d H:i:s');
  11449. $saved_acts = []; // 用于记录保存后的片段信息
  11450. if ($act_id > 0) {
  11451. // 单个片段模式:更新单条记录
  11452. if (count($parsed_segments) > 0) {
  11453. $new_segment = $parsed_segments[0];
  11454. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  11455. if ($check_mode === 1) {
  11456. return [
  11457. 'check_mode' => 1,
  11458. 'act_id' => (int)$act_id,
  11459. 'act_title' => getProp($new_segment, 'act_title', ''),
  11460. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11461. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  11462. ];
  11463. }
  11464. $update_data = [
  11465. 'act_content' => getProp($new_segment, 'act_content', ''),
  11466. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  11467. 'act_title' => getProp($new_segment, 'act_title', ''),
  11468. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11469. 'updated_at' => $now,
  11470. ];
  11471. DB::table('mp_episode_segments')
  11472. ->where('id', $act_id)
  11473. ->update($update_data);
  11474. // 获取更新后的记录
  11475. $updated_act = DB::table('mp_episode_segments')
  11476. ->where('id', $act_id)
  11477. ->first();
  11478. if ($updated_act) {
  11479. $saved_acts[] = [
  11480. 'act_id' => $updated_act->id,
  11481. 'act_number' => $updated_act->act_number,
  11482. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  11483. 'act_content' => $updated_act->act_content,
  11484. 'act_show_content' => $updated_act->act_show_content,
  11485. 'video_url' => $updated_act->video_url ?? '',
  11486. 'video_duration' => $updated_act->video_duration ?? 0,
  11487. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  11488. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  11489. ];
  11490. }
  11491. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  11492. }
  11493. } else {
  11494. // 整个剧集模式:删除原有记录并批量保存新记录
  11495. DB::beginTransaction();
  11496. try {
  11497. // 删除原有的所有片段记录
  11498. DB::table('mp_episode_segments')
  11499. ->where('episode_id', $target_episode_id)
  11500. ->delete();
  11501. // 批量插入新的片段记录
  11502. $segments_to_insert = [];
  11503. foreach ($parsed_segments as $index => $segment) {
  11504. $act_number = $index + 1;
  11505. $segments_to_insert[] = [
  11506. 'anime_id' => $target_anime_id,
  11507. 'episode_id' => $target_episode_id,
  11508. 'episode_number' => $target_episode_number,
  11509. 'act_number' => $act_number,
  11510. 'act_title' => getProp($segment, 'act_title', ''),
  11511. 'act_duration' => getProp($segment, 'act_duration', 0),
  11512. 'act_content' => getProp($segment, 'act_content', ''),
  11513. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  11514. 'created_at' => $now,
  11515. 'updated_at' => $now,
  11516. ];
  11517. }
  11518. if (!empty($segments_to_insert)) {
  11519. DB::table('mp_episode_segments')->insert($segments_to_insert);
  11520. }
  11521. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11522. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11523. 'anime_id' => $target_anime_id,
  11524. 'episode_id' => $target_episode_id,
  11525. 'model' => $model,
  11526. 'source' => 'regenerateSegmentScript',
  11527. ]);
  11528. DB::commit();
  11529. // 查询保存后的所有片段记录
  11530. $saved_segments = DB::table('mp_episode_segments')
  11531. ->where('episode_id', $target_episode_id)
  11532. ->orderBy('act_number')
  11533. ->get();
  11534. foreach ($saved_segments as $saved_segment) {
  11535. $saved_acts[] = [
  11536. 'act_id' => $saved_segment->id,
  11537. 'act_number' => $saved_segment->act_number,
  11538. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  11539. 'act_content' => $saved_segment->act_content,
  11540. 'act_show_content' => $saved_segment->act_show_content,
  11541. 'video_url' => $saved_segment->video_url ?? '',
  11542. 'video_duration' => $saved_segment->video_duration ?? 0,
  11543. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  11544. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  11545. ];
  11546. }
  11547. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  11548. 'episode_id' => $target_episode_id,
  11549. 'segments_count' => count($segments_to_insert)
  11550. ]);
  11551. } catch (\Exception $e) {
  11552. DB::rollBack();
  11553. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  11554. Utils::throwError('20003:保存失败,请重试');
  11555. }
  11556. }
  11557. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  11558. return [
  11559. 'anime_id' => $target_anime_id,
  11560. 'episode_id' => $target_episode_id,
  11561. 'title' => getProp($episode, 'title', ''),
  11562. 'episode_number' => $target_episode_number,
  11563. 'is_generated' => getProp($episode, 'is_generated', 0),
  11564. 'acts' => $saved_acts,
  11565. ];
  11566. } catch (\Exception $e) {
  11567. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  11568. throw $e;
  11569. }
  11570. }
  11571. /**
  11572. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  11573. *
  11574. * @param string $actContent
  11575. * @return string
  11576. */
  11577. private function cleanSegmentContent(string $actContent): string
  11578. {
  11579. $cleaned_content = '';
  11580. $content_lines = explode("\n", $actContent);
  11581. $is_capturing = false; // 标记是否开始捕获分镜内容
  11582. $count = 0;
  11583. foreach ($content_lines as $line) {
  11584. $trimmed_line = trim($line);
  11585. // 跳过时长、旁白音色等非分镜行
  11586. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  11587. continue;
  11588. }
  11589. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X)
  11590. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  11591. $count++;
  11592. $is_capturing = true;
  11593. if (!preg_match('/^【/u', $trimmed_line)) {
  11594. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  11595. }
  11596. if ($count > 1) {
  11597. $trimmed_line = "\n" . $trimmed_line;
  11598. }
  11599. }
  11600. if ($is_capturing && !empty($trimmed_line)) {
  11601. $cleaned_content .= $trimmed_line . "\n";
  11602. }
  11603. }
  11604. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  11605. return $cleaned_content;
  11606. }
  11607. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  11608. {
  11609. $episode_arr = [
  11610. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  11611. 'intro' => getProp($script_arr, 'intro'),
  11612. 'art_style' => getProp($script_arr, 'art_style'),
  11613. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  11614. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  11615. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  11616. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  11617. ];
  11618. if (empty($episode_arr['acts'])) {
  11619. $fallback_episode_arr = handleEpisodeContent($fullContent);
  11620. if (!empty($fallback_episode_arr['acts'])) {
  11621. $episode_arr = array_merge($fallback_episode_arr, [
  11622. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  11623. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  11624. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  11625. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  11626. ]);
  11627. }
  11628. }
  11629. // if (!getProp($episode_arr, 'episode_title')) {
  11630. // $episode_title = '';
  11631. // $episodes = getProp($script_arr, 'episodes', []);
  11632. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  11633. // $episode_title = '第1集:' . $episodes[0]['title'];
  11634. // }
  11635. // if (!$episode_title) {
  11636. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  11637. // }
  11638. // $episode_arr['episode_title'] = $episode_title;
  11639. // }
  11640. return $episode_arr;
  11641. }
  11642. private function saveEpisodeVersionData(
  11643. int $anime_id,
  11644. int $episode_number,
  11645. array $episode_arr,
  11646. array $existing_roles,
  11647. array $existing_scenes,
  11648. array $existing_props,
  11649. $current_episode,
  11650. $base_episode,
  11651. bool $is_regenerate_version,
  11652. string $content,
  11653. string $now,
  11654. array $ref_products = []
  11655. ): array {
  11656. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  11657. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  11658. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  11659. // 过滤掉关键字段为空的条目
  11660. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  11661. return !empty($item['role'] ?? null);
  11662. }));
  11663. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  11664. return !empty($item['scene'] ?? null);
  11665. }));
  11666. $merged_props = array_values(array_filter($generated_props, function ($item) {
  11667. return !empty($item['prop'] ?? null);
  11668. }));
  11669. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  11670. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  11671. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  11672. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11673. $ace_mode = getProp($anime, 'ace_mode');
  11674. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  11675. $global_roles = json_decode(getProp($anime, 'roles'), true);
  11676. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  11677. $global_roles = is_array($global_roles) ? $global_roles : [];
  11678. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  11679. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  11680. $art_style_type = getProp($anime, 'art_style_type');
  11681. // 检查并创建 roles 的图片生成任务
  11682. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  11683. // 检查并创建 scenes 的图片生成任务
  11684. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  11685. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  11686. if ($arr && is_array($arr)) {
  11687. $merged_roles = $arr['roles'];
  11688. $merged_scenes = $arr['scenes'];
  11689. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  11690. }
  11691. // 确保数据是数组类型
  11692. if (!is_array($merged_roles)) {
  11693. dLog('deepseek')->error('merged_roles不是数组类型', [
  11694. 'type' => gettype($merged_roles),
  11695. 'value' => $merged_roles
  11696. ]);
  11697. $merged_roles = [];
  11698. }
  11699. if (!is_array($merged_scenes)) {
  11700. dLog('deepseek')->error('merged_scenes不是数组类型', [
  11701. 'type' => gettype($merged_scenes),
  11702. 'value' => $merged_scenes
  11703. ]);
  11704. $merged_scenes = [];
  11705. }
  11706. if (!is_array($merged_props)) {
  11707. dLog('deepseek')->error('merged_props不是数组类型', [
  11708. 'type' => gettype($merged_props),
  11709. 'value' => $merged_props
  11710. ]);
  11711. $merged_props = [];
  11712. }
  11713. // 同步新出现的主体和场景到全局
  11714. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  11715. $role_arr = [];
  11716. foreach ($merged_roles as $item) {
  11717. $role_arr[$item['role']] = $item;
  11718. }
  11719. $version_count = DB::table('mp_anime_episodes')
  11720. ->where('anime_id', $anime_id)
  11721. ->where('episode_number', $episode_number)
  11722. ->count('id');
  11723. $episode = [
  11724. 'anime_id' => $anime_id,
  11725. 'episode_number' => $episode_number,
  11726. 'title' => getProp($episode_arr, 'episode_title'),
  11727. 'content' => $content,
  11728. 'intro' => getProp($episode_arr, 'intro'),
  11729. 'art_style' => getProp($episode_arr, 'art_style'),
  11730. 'roles' => json_encode($merged_roles, 256),
  11731. 'scenes' => json_encode($merged_scenes, 256),
  11732. 'props' => json_encode($merged_props, 256),
  11733. 'generate_status' => '待执行',
  11734. 'generate_at' => $now,
  11735. 'is_default' => 1,
  11736. 'updated_at' => $now,
  11737. ];
  11738. $del_flag = false;
  11739. if ($is_regenerate_version) {
  11740. DB::table('mp_anime_episodes')
  11741. ->where('anime_id', $anime_id)
  11742. ->where('episode_number', $episode_number)
  11743. ->update(['is_default' => 0, 'updated_at' => $now]);
  11744. $episode['sequence'] = $version_count + 1;
  11745. $episode['created_at'] = $now;
  11746. $episode['cpid'] = Site::getCpid();
  11747. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11748. if (!$episode_id) {
  11749. Utils::throwError('20003:创建剧集版本失败');
  11750. }
  11751. } else {
  11752. $target_episode = $current_episode ?: $base_episode;
  11753. if ($target_episode) {
  11754. $episode_id = getProp($target_episode, 'id');
  11755. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  11756. DB::table('mp_anime_episodes')
  11757. ->where('anime_id', $anime_id)
  11758. ->where('episode_number', $episode_number)
  11759. ->where('id', '<>', $episode_id)
  11760. ->update(['is_default' => 0, 'updated_at' => $now]);
  11761. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  11762. if ($boolen === false) {
  11763. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11764. Utils::throwError('20003:分集内容保存失败');
  11765. }
  11766. $del_flag = true;
  11767. } else {
  11768. DB::table('mp_anime_episodes')
  11769. ->where('anime_id', $anime_id)
  11770. ->where('episode_number', $episode_number)
  11771. ->update(['is_default' => 0, 'updated_at' => $now]);
  11772. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  11773. $episode['created_at'] = $now;
  11774. $episode['cpid'] = Site::getCpid();
  11775. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11776. if (!$episode_id) {
  11777. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  11778. Utils::throwError('20003:分集内容保存失败');
  11779. }
  11780. }
  11781. }
  11782. $segments = [];
  11783. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11784. // 如果是第2集及以后,获取上一集的主体音色数据
  11785. $previous_roles_voice = [];
  11786. if ($episode_number >= 2) {
  11787. $previous_episode = DB::table('mp_anime_episodes')
  11788. ->where('anime_id', $anime_id)
  11789. ->where('episode_number', $episode_number - 1)
  11790. ->where('is_default', 1)
  11791. ->first();
  11792. if ($previous_episode) {
  11793. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  11794. if (is_array($previous_roles)) {
  11795. foreach ($previous_roles as $prev_role) {
  11796. $role_name = getProp($prev_role, 'role');
  11797. if ($role_name) {
  11798. $previous_roles_voice[$role_name] = [
  11799. 'voice_name' => getProp($prev_role, 'voice_name'),
  11800. 'voice_type' => getProp($prev_role, 'voice_type'),
  11801. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  11802. ];
  11803. $voice_prompt = getProp($prev_role, 'voice_prompt');
  11804. if ($voice_prompt) {
  11805. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  11806. }
  11807. }
  11808. }
  11809. }
  11810. }
  11811. }
  11812. // 将继承的音色数据同步到当前集的主体列表
  11813. if (!empty($previous_roles_voice)) {
  11814. foreach ($merged_roles as &$role) {
  11815. $role_name = getProp($role, 'role');
  11816. if ($role_name && isset($previous_roles_voice[$role_name])) {
  11817. // 强制继承上一集的音色数据
  11818. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  11819. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  11820. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  11821. // 如果上一集有 voice_prompt 则继承,否则跳过
  11822. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  11823. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  11824. }
  11825. }
  11826. }
  11827. unset($role); // 解除引用
  11828. // 更新 role_arr 以便后续使用
  11829. $role_arr = [];
  11830. foreach ($merged_roles as $item) {
  11831. $role_arr[$item['role']] = $item;
  11832. }
  11833. }
  11834. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  11835. $emotion_list = array_flip($emotion_list);
  11836. foreach ($acts as $act) {
  11837. $act_segments = getProp($act, 'segments', []);
  11838. if (!is_array($act_segments)) {
  11839. continue;
  11840. }
  11841. if ((int)$ace_mode === 1) {
  11842. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  11843. $merged_parts = [];
  11844. foreach ($act_segments as $seg) {
  11845. $seg_num = getProp($seg, 'segment_number');
  11846. $seg_content = getProp($seg, 'segment_content');
  11847. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  11848. }
  11849. $act_content = implode("\n", $merged_parts);
  11850. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11851. $segments[] = [
  11852. 'anime_id' => $anime_id,
  11853. 'episode_id' => $episode_id,
  11854. 'episode_number' => $episode_number,
  11855. 'act_number' => getProp($act, 'act_number'),
  11856. 'act_title' => getProp($act, 'act_title'),
  11857. 'act_duration' => getProp($act, 'act_duration'),
  11858. 'act_content' => $act_content,
  11859. 'created_at' => $now,
  11860. 'updated_at' => $now
  11861. ];
  11862. } else {
  11863. foreach ($act_segments as $segment) {
  11864. $voice_actor = getProp($segment, 'voice_actor');
  11865. // 优先从上一集继承音色数据
  11866. $timbre_info = [];
  11867. if (isset($previous_roles_voice[$voice_actor])) {
  11868. // 从上一集继承音色数据
  11869. $timbre_info = $previous_roles_voice[$voice_actor];
  11870. } elseif (isset($role_arr[$voice_actor])) {
  11871. // 使用当前集的主体音色数据
  11872. $timbre_info = $role_arr[$voice_actor];
  11873. }
  11874. $voice_type = getProp($timbre_info, 'voice_type');
  11875. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  11876. if ($timbre_emotion) {
  11877. $timbre_emotion = explode(',', $timbre_emotion);
  11878. } else {
  11879. $timbre_emotion = [];
  11880. }
  11881. $emotion = getProp($segment, 'emotion', '中性');
  11882. if (!in_array($emotion, $timbre_emotion)) {
  11883. $emotion = '中性';
  11884. }
  11885. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11886. $segments[] = [
  11887. 'anime_id' => $anime_id,
  11888. 'episode_id' => $episode_id,
  11889. 'episode_number' => $episode_number,
  11890. 'act_number' => getProp($act, 'act_number'),
  11891. 'act_title' => getProp($act, 'act_title'),
  11892. 'act_duration' => getProp($act, 'act_duration'),
  11893. 'segment_id' => getProp($segment, 'segment_id'),
  11894. 'segment_number' => getProp($segment, 'segment_number'),
  11895. 'segment_content' => getProp($segment, 'segment_content'),
  11896. 'description' => getProp($segment, 'description'),
  11897. 'composition' => getProp($segment, 'composition'),
  11898. 'camera_movement' => getProp($segment, 'camera_movement'),
  11899. 'voice_actor' => $voice_actor,
  11900. 'dialogue' => getProp($segment, 'dialogue'),
  11901. 'frame_type' => getProp($segment, 'frame_type'),
  11902. 'scene' => getProp($segment, 'scene'),
  11903. 'characters' => getProp($segment, 'characters'),
  11904. 'tail_frame' => getProp($segment, 'tail_frame'),
  11905. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11906. 'voice_type' => $voice_type,
  11907. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11908. 'emotion' => $emotion,
  11909. 'emotion_type' => $emotion_type,
  11910. 'gender' => getProp($segment, 'gender', '0'),
  11911. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11912. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11913. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11914. 'pitch' => getProp($segment, 'pitch', 0),
  11915. 'created_at' => $now,
  11916. 'updated_at' => $now
  11917. ];
  11918. }
  11919. }
  11920. }
  11921. if ($segments) {
  11922. if ($del_flag) {
  11923. DB::table('mp_episode_segments')
  11924. ->where('anime_id', $anime_id)
  11925. ->where('episode_id', $episode_id)
  11926. ->delete();
  11927. }
  11928. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11929. if (!$boolen) {
  11930. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11931. Utils::throwError('20003:分镜内容保存失败');
  11932. }
  11933. }
  11934. dLog('deepseek')->info('segments', $segments);
  11935. // ace_mode=1: acts 返回值按合并格式调整
  11936. if ((int)$ace_mode === 1) {
  11937. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11938. $act_map = [];
  11939. foreach ($table_act_data as $item) {
  11940. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11941. }
  11942. $restructured_acts = [];
  11943. foreach ($acts as $act) {
  11944. $act_segments = getProp($act, 'segments', []);
  11945. if (!is_array($act_segments)) {
  11946. continue;
  11947. }
  11948. $merged_parts = [];
  11949. foreach ($act_segments as $seg) {
  11950. $seg_num = getProp($seg, 'segment_number');
  11951. $seg_content = getProp($seg, 'segment_content');
  11952. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11953. }
  11954. $act_content = implode("\n", $merged_parts);
  11955. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11956. $restructured_acts[] = [
  11957. 'anime_id' => $anime_id,
  11958. 'episode_id' => $episode_id,
  11959. 'episode_number' => $episode_number,
  11960. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11961. 'act_number' => getProp($act, 'act_number'),
  11962. 'act_title' => getProp($act, 'act_title'),
  11963. 'act_duration' => getProp($act, 'act_duration'),
  11964. 'act_content' => $act_content,
  11965. 'created_at' => $now,
  11966. 'updated_at' => $now,
  11967. ];
  11968. }
  11969. $acts = $restructured_acts;
  11970. }
  11971. $episode['episode_id'] = $episode_id;
  11972. $episode['roles'] = $merged_roles;
  11973. $episode['scenes'] = $merged_scenes;
  11974. $episode['props'] = $merged_props;
  11975. $episode['acts'] = $acts;
  11976. return [
  11977. 'episode' => $episode,
  11978. 'episode_id' => $episode_id,
  11979. 'merged_roles' => $merged_roles,
  11980. 'merged_scenes' => $merged_scenes,
  11981. 'merged_props' => $merged_props,
  11982. ];
  11983. }
  11984. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11985. {
  11986. $content = '';
  11987. foreach ($items as $item) {
  11988. $name = trim((string)getProp($item, $nameKey));
  11989. if ($name === '' || $name === '旁白') {
  11990. continue;
  11991. }
  11992. $description = trim((string)getProp($item, 'description'));
  11993. $content .= $name . ': ' . $description;
  11994. if ($nameKey == 'role') {
  11995. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11996. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11997. $voice_name = trim(getProp($item, 'voice_name'));
  11998. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11999. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  12000. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  12001. }else {
  12002. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  12003. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  12004. }
  12005. $content .= "\n";
  12006. }
  12007. return trim($content);
  12008. }
  12009. private function getEpisodeChatContent($animeId, $sequence, $content) {
  12010. if ((int)$sequence <= 0) {
  12011. return [];
  12012. }
  12013. $origin_content = '';
  12014. if ($content) {
  12015. $origin_content = '本集剧情内容:'.$content;
  12016. }else {
  12017. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  12018. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  12019. }
  12020. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  12021. // 获取分集信息
  12022. $episode = DB::table('mp_anime_episodes')
  12023. ->where('anime_id', $animeId)
  12024. ->where('episode_number', $sequence)
  12025. ->where('is_default', 1)
  12026. ->first();
  12027. if (!$episode) {
  12028. return [];
  12029. }
  12030. $episode_id = getProp($episode, 'id');
  12031. $episode_number = getProp($episode, 'episode_number');
  12032. $title = getProp($episode, 'title');
  12033. $intro = getProp($episode, 'intro');
  12034. $art_style = getProp($episode, 'art_style');
  12035. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12036. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12037. // 组装纯文本内容
  12038. $content = '';
  12039. // 添加分集标题和梗概
  12040. $content .= "###第{$episode_number}集:{$title}\n\n";
  12041. $content .= "###故事梗概\n";
  12042. $content .= trim($intro) . "\n\n";
  12043. // 添加美术风格
  12044. $content .= "###美术风格\n";
  12045. $content .= trim($art_style) . "\n\n";
  12046. // 添加主体列表
  12047. $content .= "###主体列表\n";
  12048. $pangbai_voice_prompt = "";
  12049. foreach ($roles as $role) {
  12050. $name = getProp($role, 'role');
  12051. $description = getProp($role, 'description');
  12052. $pic_prompt = getProp($role, 'pic_prompt');
  12053. $voice_prompt = getProp($role, 'voice_prompt');
  12054. $voice_name = getProp($role, 'voice_name');
  12055. $content .= "{$name}: {$description}";
  12056. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  12057. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  12058. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  12059. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  12060. $content .= "\n";
  12061. }
  12062. $content .= "\n";
  12063. // 添加场景列表
  12064. $content .= "###场景列表\n";
  12065. foreach ($scenes as $scene) {
  12066. $name = getProp($scene, 'scene');
  12067. $description = getProp($scene, 'description');
  12068. $pic_prompt = getProp($scene, 'pic_prompt');
  12069. $content .= "{$name}: {$description}";
  12070. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  12071. $content .= "\n";
  12072. }
  12073. $content .= "\n";
  12074. // 获取分镜信息
  12075. $segments = DB::table('mp_episode_segments')
  12076. ->where('anime_id', $animeId)
  12077. ->where('episode_id', $episode_id)
  12078. ->orderBy('segment_number')
  12079. ->get();
  12080. if ($segments && count($segments) > 0) {
  12081. if ((int)$ace_mode === 1) {
  12082. $content .= "###分段剧本\n";
  12083. // 获取片段数量
  12084. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  12085. $content .= "片段数量:{$act_count}\n";
  12086. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  12087. $content .= "\n";
  12088. }else {
  12089. $content .= "###分镜剧本\n";
  12090. }
  12091. // 按幕分组
  12092. $currentAct = null;
  12093. foreach ($segments as $segment) {
  12094. $act_number = getProp($segment, 'act_number');
  12095. $act_title = getProp($segment, 'act_title');
  12096. $act_duration = getProp($segment, 'act_duration');
  12097. $segment_number = getProp($segment, 'segment_number');
  12098. $segment_content = getProp($segment, 'segment_content');
  12099. $scene_description = getProp($segment, 'scene_description');
  12100. $scene_name = getProp($segment, 'scene_name');
  12101. $composition = getProp($segment, 'composition');
  12102. $camera_movement = getProp($segment, 'camera_movement');
  12103. $voice_type = getProp($segment, 'voice_type');
  12104. $characters = getProp($segment, 'characters');
  12105. $dialogue = getProp($segment, 'dialogue');
  12106. $frame_type = getProp($segment, 'frame_type');
  12107. $tail_frame_description = getProp($segment, 'tail_frame_description');
  12108. // 判断是否是全能模式
  12109. if ((int)$ace_mode === 1) { // 全能模式
  12110. // 如果是新的分段,添加分段标题
  12111. if ($act_number !== $currentAct) {
  12112. $currentAct = $act_number;
  12113. $content .= "##{$act_title}\n";
  12114. $content .= "时长:{$act_duration}s\n";
  12115. }
  12116. }else {
  12117. // 如果是新的幕,添加幕标题
  12118. if ($act_number !== $currentAct) {
  12119. $currentAct = $act_number;
  12120. $content .= "##第{$act_number}幕:{$scene_name}\n";
  12121. }
  12122. }
  12123. // 添加分镜信息
  12124. $content .= "分镜{$segment_number}\n";
  12125. $content .= "分镜内容:\n{$segment_content}\n";
  12126. // $content .= "画面描述:{$scene_description}\n";
  12127. // $content .= "场景:{$scene_name}\n";
  12128. // $content .= "构图设计:{$composition}\n";
  12129. // $content .= "运镜调度:{$camera_movement}\n";
  12130. // if (!empty($voice_type)) {
  12131. // $content .= "配音角色:{$voice_type}\n";
  12132. // }
  12133. // if (!empty($characters)) {
  12134. // $content .= "出镜角色:{$characters}\n";
  12135. // }
  12136. // if (!empty($dialogue)) {
  12137. // $content .= "台词内容:\"{$dialogue}\"\n";
  12138. // }
  12139. // $content .= "画面类型:{$frame_type}\n";
  12140. // $content .= "尾帧描述:{$tail_frame_description}\n";
  12141. $content .= "\n";
  12142. }
  12143. }
  12144. $content = trim($content);
  12145. if($content) $content = "上集剧本内容:\n{$content}";
  12146. return [
  12147. [
  12148. 'role' => 'user',
  12149. 'content' => $origin_content
  12150. ],
  12151. [
  12152. 'role' => 'assistant',
  12153. 'content' => $content
  12154. ]
  12155. ];
  12156. }
  12157. private function getEpisodeChatMessages($animeId, $sequence): array
  12158. {
  12159. if ((int)$sequence <= 0) {
  12160. return [];
  12161. }
  12162. return DB::table('mp_anime_records')
  12163. ->where('anime_id', $animeId)
  12164. ->where('sequence', $sequence)
  12165. ->where('episode_id', '>', 0)
  12166. ->select('role', 'content')
  12167. ->orderBy('created_at')
  12168. ->orderBy('id')
  12169. ->get()
  12170. ->map(function ($value) {
  12171. return (array)$value;
  12172. })
  12173. ->toArray();
  12174. }
  12175. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  12176. {
  12177. $existingMap = [];
  12178. foreach ($existingItems as $item) {
  12179. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12180. if ($itemKey === '') {
  12181. continue;
  12182. }
  12183. $existingMap[$itemKey] = $item;
  12184. }
  12185. if (!$generatedItems) {
  12186. return array_values($existingItems);
  12187. }
  12188. $merged = [];
  12189. foreach ($generatedItems as $item) {
  12190. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12191. if ($itemKey === '') {
  12192. continue;
  12193. }
  12194. if (isset($existingMap[$itemKey])) {
  12195. if (trim((string)getProp($item, 'description')) === '') {
  12196. $merged[] = $existingMap[$itemKey];
  12197. continue;
  12198. }
  12199. // 检查内容是否发生变化
  12200. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  12201. if (!$isChanged) {
  12202. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  12203. $mergedItem = [
  12204. $nameKey => trim((string)getProp($item, $nameKey)),
  12205. 'description' => trim((string)getProp($item, 'description')),
  12206. ];
  12207. // 如果有 pic_prompt,添加到合并项中
  12208. $picPrompt = getProp($item, 'pic_prompt');
  12209. if (!empty($picPrompt)) {
  12210. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12211. }
  12212. // 继承现有项的 URL
  12213. $existingUrl = getProp($existingMap[$itemKey], 'url');
  12214. if (!empty($existingUrl)) {
  12215. $mergedItem['url'] = $existingUrl;
  12216. }
  12217. // 继承现有项的 task_id
  12218. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  12219. if (!empty($existingTaskId)) {
  12220. $mergedItem['task_id'] = $existingTaskId;
  12221. }
  12222. // 继承现有项的 task_status
  12223. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  12224. if (!empty($existingTaskStatus)) {
  12225. $mergedItem['task_status'] = $existingTaskStatus;
  12226. }
  12227. // 保留生成项的音色字段
  12228. $voiceName = getProp($item, 'voice_name');
  12229. if (!empty($voiceName)) {
  12230. $mergedItem['voice_name'] = $voiceName;
  12231. }
  12232. $voiceType = getProp($item, 'voice_type');
  12233. if (!empty($voiceType)) {
  12234. $mergedItem['voice_type'] = $voiceType;
  12235. }
  12236. $audioUrl = getProp($item, 'voice_audio_url');
  12237. if (!empty($audioUrl)) {
  12238. $mergedItem['voice_audio_url'] = $audioUrl;
  12239. }
  12240. $merged[] = $mergedItem;
  12241. } else {
  12242. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  12243. $mergedItem = [
  12244. $nameKey => trim((string)getProp($item, $nameKey)),
  12245. 'description' => trim((string)getProp($item, 'description')),
  12246. ];
  12247. // 如果有 pic_prompt,添加到合并项中
  12248. $picPrompt = getProp($item, 'pic_prompt');
  12249. if (!empty($picPrompt)) {
  12250. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12251. }
  12252. // 保留生成项的音色字段
  12253. $voiceName = getProp($item, 'voice_name');
  12254. if (!empty($voiceName)) {
  12255. $mergedItem['voice_name'] = $voiceName;
  12256. }
  12257. $voiceType = getProp($item, 'voice_type');
  12258. if (!empty($voiceType)) {
  12259. $mergedItem['voice_type'] = $voiceType;
  12260. }
  12261. $audioUrl = getProp($item, 'voice_audio_url');
  12262. if (!empty($audioUrl)) {
  12263. $mergedItem['voice_audio_url'] = $audioUrl;
  12264. }
  12265. // 不继承 URL、task_id 和 task_status(重置状态)
  12266. $merged[] = $mergedItem;
  12267. }
  12268. } else {
  12269. // 新增项,保留生成项的所有字段
  12270. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  12271. }
  12272. }
  12273. return $merged ?: array_values($existingItems);
  12274. }
  12275. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  12276. {
  12277. $resetItem = [
  12278. $nameKey => trim((string)getProp($item, $nameKey)),
  12279. 'description' => trim((string)getProp($item, 'description')),
  12280. ];
  12281. // 保留指定的字段
  12282. foreach ($preserveFields as $field) {
  12283. $value = getProp($item, $field);
  12284. if (!empty($value)) {
  12285. $resetItem[$field] = $value;
  12286. }
  12287. }
  12288. return $resetItem;
  12289. }
  12290. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  12291. {
  12292. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  12293. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  12294. if ($existingKey !== $generatedKey) {
  12295. return true;
  12296. }
  12297. // 比较 description 是否变化
  12298. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  12299. return true;
  12300. }
  12301. // 比较 pic_prompt 是否变化
  12302. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  12303. }
  12304. private function normalizeEpisodeResourceKey($value): string
  12305. {
  12306. $value = trim((string)$value);
  12307. if ($value === '') {
  12308. return '';
  12309. }
  12310. return strtolower((string)preg_replace('/\s+/u', '', $value));
  12311. }
  12312. // 生成全局角色图片
  12313. private function batchSetGlobalRoleImg($data, $is_force=false) {
  12314. $anime_id = getProp($data, 'anime_id');
  12315. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12316. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12317. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12318. $art_style = getProp($anime, 'art_style');
  12319. $update_flag = false;
  12320. foreach ($roles as &$role) {
  12321. $role_name = getProp($role, 'role');
  12322. if ($role_name == '旁白') continue;
  12323. // 优先使用 pic_prompt,如果没有则使用 description
  12324. $pic_prompt = getProp($role, 'pic_prompt');
  12325. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12326. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12327. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12328. // 参考图地址
  12329. $ref_img_url = getProp($role, 'url');
  12330. if (!$is_force && $ref_img_url) continue;
  12331. $update_flag = true;
  12332. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12333. try {
  12334. $params = [
  12335. 'prompt' => $description,
  12336. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  12337. 'ref_img_urls' => []
  12338. ];
  12339. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12340. $task_id = $task->id;
  12341. if (!$task_id) {
  12342. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  12343. }
  12344. $role['task_id'] = $task_id;
  12345. $role['task_status'] = 'processing';
  12346. } catch (\Exception $e) {
  12347. Utils::throwError("20003:" . $e->getMessage());
  12348. }
  12349. }
  12350. if (!$update_flag) return true;
  12351. // 保存角色信息
  12352. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12353. 'roles' => json_encode($roles, 256),
  12354. 'generate_status' => '执行中',
  12355. 'generate_at' => date('Y-m-d H:i:s'),
  12356. 'updated_at' => date('Y-m-d H:i:s')
  12357. ]);
  12358. if (!$boolen) {
  12359. Utils::throwError('20003:保存角色信息失败');
  12360. }
  12361. return $boolen;
  12362. }
  12363. // 生成全局场景图片
  12364. private function batchSetGlobalSceneImg($data, $is_force=false) {
  12365. $anime_id = getProp($data, 'anime_id');
  12366. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12367. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12368. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12369. $art_style = getProp($anime, 'art_style');
  12370. $update_flag = false;
  12371. foreach ($scenes as &$scene) {
  12372. $scene_name = getProp($scene, 'scene');
  12373. // 优先使用 pic_prompt,如果没有则使用 description
  12374. $pic_prompt = getProp($scene, 'pic_prompt');
  12375. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12376. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  12377. // 参考图地址
  12378. $ref_img_url = getProp($scene, 'url');
  12379. if (!$is_force && $ref_img_url) continue;
  12380. $update_flag = true;
  12381. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12382. try {
  12383. $params = [
  12384. 'prompt' => $description,
  12385. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  12386. 'ref_img_urls' => []
  12387. ];
  12388. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12389. $task_id = $task->id;
  12390. if (!$task_id) {
  12391. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  12392. }
  12393. $scene['task_id'] = $task_id;
  12394. $scene['task_status'] = 'processing';
  12395. } catch (\Exception $e) {
  12396. Utils::throwError("20003:" . $e->getMessage());
  12397. }
  12398. }
  12399. if (!$update_flag) return true;
  12400. // 保存角色信息
  12401. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12402. 'scenes' => json_encode($scenes, 256),
  12403. 'generate_status' => '执行中',
  12404. 'generate_at' => date('Y-m-d H:i:s'),
  12405. 'updated_at' => date('Y-m-d H:i:s')
  12406. ]);
  12407. if (!$boolen) {
  12408. Utils::throwError('20003:保存角色信息失败');
  12409. }
  12410. return $boolen;
  12411. }
  12412. // 生成分镜主体、场景和道具图片
  12413. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  12414. $character_prefix = '';
  12415. $scene_prefix = '';
  12416. $prop_prefix = '';
  12417. if ($art_style_type) {
  12418. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  12419. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  12420. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  12421. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  12422. }
  12423. $update_flag = false;
  12424. // 获取上一集的roles、scenes和props数据
  12425. $prev_roles = [];
  12426. $prev_scenes = [];
  12427. $prev_props = [];
  12428. if ($episode_number > 1) {
  12429. $prev_episode = DB::table('mp_anime_episodes')
  12430. ->where('anime_id', $anime_id)
  12431. ->where('episode_number', $episode_number - 1)
  12432. ->where('is_default', 1)
  12433. ->first();
  12434. if ($prev_episode) {
  12435. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  12436. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  12437. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  12438. dLog('deepseek')->info("获取上一集数据成功", [
  12439. 'anime_id' => $anime_id,
  12440. 'prev_episode_number' => $episode_number - 1,
  12441. 'prev_roles_count' => count($prev_roles),
  12442. 'prev_scenes_count' => count($prev_scenes),
  12443. 'prev_props_count' => count($prev_props)
  12444. ]);
  12445. }
  12446. }
  12447. // 处理角色图片生成
  12448. foreach ($roles as &$role) {
  12449. $role_name = getProp($role, 'role');
  12450. if ($role_name == '旁白') continue;
  12451. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  12452. if (isset($ref_products[$role_name])) {
  12453. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  12454. if ($role['url']) continue;
  12455. }
  12456. $role_description = getProp($role, 'description');
  12457. $role_pic_prompt = getProp($role, 'pic_prompt');
  12458. $role_url = getProp($role, 'url');
  12459. // 检查是否可以从上一集继承
  12460. $inherited = false;
  12461. if (!$is_force && !empty($prev_roles)) {
  12462. foreach ($prev_roles as $prev_role) {
  12463. $prev_role_name = getProp($prev_role, 'role');
  12464. $prev_description = getProp($prev_role, 'description');
  12465. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  12466. $prev_url = getProp($prev_role, 'url');
  12467. $prev_task_id = getProp($prev_role, 'task_id');
  12468. $prev_task_status = getProp($prev_role, 'task_status');
  12469. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  12470. if ($role_name == $prev_role_name
  12471. && $role_description == $prev_description
  12472. && $role_pic_prompt == $prev_pic_prompt
  12473. && !empty($prev_url)) {
  12474. $role['task_id'] = $prev_task_id;
  12475. $role['task_status'] = $prev_task_status;
  12476. $role['url'] = $prev_url;
  12477. $inherited = true;
  12478. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  12479. 'anime_id' => $anime_id,
  12480. 'episode_number' => $episode_number,
  12481. 'task_id' => $prev_task_id,
  12482. 'url' => $prev_url
  12483. ]);
  12484. break;
  12485. }
  12486. }
  12487. }
  12488. // 如果已继承或已有url,跳过生成
  12489. if ($inherited || (!$is_force && $role_url)) {
  12490. continue;
  12491. }
  12492. // 优先使用 pic_prompt,如果没有则使用 description
  12493. $pic_prompt = getProp($role, 'pic_prompt');
  12494. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12495. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12496. $update_flag = true;
  12497. // 调用AIImageGenerationService的生成图片任务接口
  12498. try {
  12499. $params = [
  12500. 'prompt' => $description,
  12501. 'ref_img_urls' => []
  12502. ];
  12503. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12504. $task_id = $task->id;
  12505. if (!$task_id) {
  12506. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  12507. continue; // 不中断,继续处理其他角色
  12508. }
  12509. $role['task_id'] = $task_id;
  12510. $role['task_status'] = 'processing';
  12511. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  12512. 'anime_id' => $anime_id,
  12513. 'episode_number' => $episode_number,
  12514. 'task_id' => $task_id
  12515. ]);
  12516. } catch (\Exception $e) {
  12517. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  12518. // 不抛出异常,继续处理其他角色
  12519. }
  12520. }
  12521. // 处理场景图片生成
  12522. foreach ($scenes as &$scene) {
  12523. $scene_name = getProp($scene, 'scene');
  12524. $scene_description = getProp($scene, 'description');
  12525. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  12526. $scene_url = getProp($scene, 'url');
  12527. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  12528. if (isset($ref_products[$scene_name])) {
  12529. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  12530. if ($scene['url']) continue;
  12531. }
  12532. // 检查是否可以从上一集继承
  12533. $inherited = false;
  12534. if (!$is_force && !empty($prev_scenes)) {
  12535. foreach ($prev_scenes as $prev_scene) {
  12536. $prev_scene_name = getProp($prev_scene, 'scene');
  12537. $prev_description = getProp($prev_scene, 'description');
  12538. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  12539. $prev_url = getProp($prev_scene, 'url');
  12540. $prev_task_id = getProp($prev_scene, 'task_id');
  12541. $prev_task_status = getProp($prev_scene, 'task_status');
  12542. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  12543. if ($scene_name == $prev_scene_name
  12544. && $scene_description == $prev_description
  12545. && $scene_pic_prompt == $prev_pic_prompt
  12546. && !empty($prev_url)) {
  12547. $scene['task_id'] = $prev_task_id;
  12548. $scene['task_status'] = $prev_task_status;
  12549. $scene['url'] = $prev_url;
  12550. $inherited = true;
  12551. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  12552. 'anime_id' => $anime_id,
  12553. 'episode_number' => $episode_number,
  12554. 'task_id' => $prev_task_id,
  12555. 'url' => $prev_url
  12556. ]);
  12557. break;
  12558. }
  12559. }
  12560. }
  12561. // 如果已继承或已有url,跳过生成
  12562. if ($inherited || (!$is_force && $scene_url)) {
  12563. continue;
  12564. }
  12565. // 优先使用 pic_prompt,如果没有则使用 description
  12566. $pic_prompt = getProp($scene, 'pic_prompt');
  12567. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12568. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12569. $update_flag = true;
  12570. // 调用AIImageGenerationService的生成图片任务接口
  12571. try {
  12572. $params = [
  12573. 'prompt' => $description,
  12574. 'ref_img_urls' => []
  12575. ];
  12576. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12577. $task_id = $task->id;
  12578. if (!$task_id) {
  12579. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  12580. continue; // 不中断,继续处理其他场景
  12581. }
  12582. $scene['task_id'] = $task_id;
  12583. $scene['task_status'] = 'processing';
  12584. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  12585. 'anime_id' => $anime_id,
  12586. 'episode_number' => $episode_number,
  12587. 'task_id' => $task_id
  12588. ]);
  12589. } catch (\Exception $e) {
  12590. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  12591. // 不抛出异常,继续处理其他场景
  12592. }
  12593. }
  12594. // 处理道具图片生成(逻辑与场景一致)
  12595. foreach ($props as &$prop) {
  12596. $prop_name = getProp($prop, 'prop');
  12597. $prop_description = getProp($prop, 'description');
  12598. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  12599. $prop_url = getProp($prop, 'url');
  12600. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  12601. if (isset($ref_products[$prop_name])) {
  12602. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  12603. if ($prop['url']) continue;
  12604. }
  12605. // 检查是否可以从上一集继承
  12606. $inherited = false;
  12607. if (!$is_force && !empty($prev_props)) {
  12608. foreach ($prev_props as $prev_prop) {
  12609. $prev_prop_name = getProp($prev_prop, 'prop');
  12610. $prev_description = getProp($prev_prop, 'description');
  12611. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  12612. $prev_url = getProp($prev_prop, 'url');
  12613. $prev_task_id = getProp($prev_prop, 'task_id');
  12614. $prev_task_status = getProp($prev_prop, 'task_status');
  12615. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  12616. if ($prop_name == $prev_prop_name
  12617. && $prop_description == $prev_description
  12618. && $prop_pic_prompt == $prev_pic_prompt
  12619. && !empty($prev_url)) {
  12620. $prop['task_id'] = $prev_task_id;
  12621. $prop['task_status'] = $prev_task_status;
  12622. $prop['url'] = $prev_url;
  12623. $inherited = true;
  12624. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  12625. 'anime_id' => $anime_id,
  12626. 'episode_number' => $episode_number,
  12627. 'task_id' => $prev_task_id,
  12628. 'url' => $prev_url
  12629. ]);
  12630. break;
  12631. }
  12632. }
  12633. }
  12634. // 如果已继承或已有url,跳过生成
  12635. if ($inherited || (!$is_force && $prop_url)) {
  12636. continue;
  12637. }
  12638. // 优先使用 pic_prompt,如果没有则使用 description
  12639. $pic_prompt = getProp($prop, 'pic_prompt');
  12640. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  12641. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12642. $update_flag = true;
  12643. // 调用AIImageGenerationService的生成图片任务接口
  12644. try {
  12645. $params = [
  12646. 'prompt' => $description,
  12647. 'ref_img_urls' => []
  12648. ];
  12649. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12650. $task_id = $task->id;
  12651. if (!$task_id) {
  12652. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  12653. continue; // 不中断,继续处理其他道具
  12654. }
  12655. $prop['task_id'] = $task_id;
  12656. $prop['task_status'] = 'processing';
  12657. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  12658. 'anime_id' => $anime_id,
  12659. 'episode_number' => $episode_number,
  12660. 'task_id' => $task_id
  12661. ]);
  12662. } catch (\Exception $e) {
  12663. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  12664. // 不抛出异常,继续处理其他道具
  12665. }
  12666. }
  12667. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12668. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  12669. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  12670. // // 保存剧集的角色和场景信息
  12671. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  12672. // 'roles' => json_encode($roles, 256),
  12673. // 'scenes' => json_encode($scenes, 256),
  12674. // 'generate_status' => '执行中',
  12675. // 'generate_at' => date('Y-m-d H:i:s'),
  12676. // 'updated_at' => date('Y-m-d H:i:s')
  12677. // ]);
  12678. // if (!$boolen) {
  12679. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  12680. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  12681. // }
  12682. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  12683. // 'episode_id' => $episode_id,
  12684. 'roles_count' => count($roles),
  12685. 'scenes_count' => count($scenes),
  12686. 'props_count' => count($props)
  12687. ]);
  12688. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12689. }
  12690. /**
  12691. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  12692. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  12693. *
  12694. * @param int $anime_id 动漫对话ID
  12695. * @param array $episode_roles 剧集角色数据
  12696. * @param array $episode_scenes 剧集场景数据
  12697. * @param array $episode_props 剧集道具数据
  12698. * @return bool
  12699. */
  12700. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  12701. // 获取全局数据
  12702. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12703. if (!$anime) {
  12704. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12705. return false;
  12706. }
  12707. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12708. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12709. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  12710. $roles_added = false;
  12711. $roles_updated = false;
  12712. $scenes_added = false;
  12713. $props_added = false;
  12714. // 处理角色同步
  12715. foreach ($episode_roles as $episode_role) {
  12716. $episode_role_name = getProp($episode_role, 'role');
  12717. $episode_description = getProp($episode_role, 'description');
  12718. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12719. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  12720. // 跳过旁白
  12721. if ($episode_role_name == '旁白') {
  12722. continue;
  12723. }
  12724. // 检查全局中是否已存在相同的角色
  12725. $exists = false;
  12726. $global_role_index = -1;
  12727. foreach ($global_roles as $index => $global_role) {
  12728. $global_role_name = getProp($global_role, 'role');
  12729. $global_description = getProp($global_role, 'description');
  12730. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12731. // 如果role、description、pic_prompt三项都一致,则认为已存在
  12732. if ($episode_role_name == $global_role_name
  12733. && $episode_description == $global_description
  12734. && $episode_pic_prompt == $global_pic_prompt) {
  12735. $exists = true;
  12736. $global_role_index = $index;
  12737. break;
  12738. }
  12739. }
  12740. // 如果不存在,则添加到全局
  12741. if (!$exists) {
  12742. $global_roles[] = $episode_role;
  12743. $roles_added = true;
  12744. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  12745. 'anime_id' => $anime_id,
  12746. 'role' => $episode_role_name
  12747. ]);
  12748. } else {
  12749. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  12750. if (!empty($episode_voice_prompt)) {
  12751. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  12752. // 如果全局没有voice_prompt或与剧集不一致,则更新
  12753. if ($global_voice_prompt !== $episode_voice_prompt) {
  12754. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  12755. $roles_updated = true;
  12756. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  12757. 'anime_id' => $anime_id,
  12758. 'role' => $episode_role_name,
  12759. 'voice_prompt' => $episode_voice_prompt
  12760. ]);
  12761. }
  12762. }
  12763. }
  12764. }
  12765. // 处理场景同步
  12766. foreach ($episode_scenes as $episode_scene) {
  12767. $episode_scene_name = getProp($episode_scene, 'scene');
  12768. $episode_description = getProp($episode_scene, 'description');
  12769. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12770. // 检查全局中是否已存在相同的场景
  12771. $exists = false;
  12772. foreach ($global_scenes as $global_scene) {
  12773. $global_scene_name = getProp($global_scene, 'scene');
  12774. $global_description = getProp($global_scene, 'description');
  12775. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12776. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  12777. if ($episode_scene_name == $global_scene_name
  12778. && $episode_description == $global_description
  12779. && $episode_pic_prompt == $global_pic_prompt) {
  12780. $exists = true;
  12781. break;
  12782. }
  12783. }
  12784. // 如果不存在,则添加到全局
  12785. if (!$exists) {
  12786. $global_scenes[] = $episode_scene;
  12787. $scenes_added = true;
  12788. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  12789. 'anime_id' => $anime_id,
  12790. 'scene' => $episode_scene_name
  12791. ]);
  12792. }
  12793. }
  12794. // 处理道具同步(逻辑与场景一致)
  12795. foreach ($episode_props as $episode_prop) {
  12796. $episode_prop_name = getProp($episode_prop, 'prop');
  12797. $episode_description = getProp($episode_prop, 'description');
  12798. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  12799. // 检查全局中是否已存在相同的道具
  12800. $exists = false;
  12801. foreach ($global_props as $global_prop) {
  12802. $global_prop_name = getProp($global_prop, 'prop');
  12803. $global_description = getProp($global_prop, 'description');
  12804. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  12805. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  12806. if ($episode_prop_name == $global_prop_name
  12807. && $episode_description == $global_description
  12808. && $episode_pic_prompt == $global_pic_prompt) {
  12809. $exists = true;
  12810. break;
  12811. }
  12812. }
  12813. // 如果不存在,则添加到全局
  12814. if (!$exists) {
  12815. $global_props[] = $episode_prop;
  12816. $props_added = true;
  12817. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  12818. 'anime_id' => $anime_id,
  12819. 'prop' => $episode_prop_name
  12820. ]);
  12821. }
  12822. }
  12823. // 如果有新增或更新,则更新全局数据
  12824. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  12825. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12826. if ($roles_added || $roles_updated) {
  12827. $update_data['roles'] = json_encode($global_roles, 256);
  12828. }
  12829. if ($scenes_added) {
  12830. $update_data['scenes'] = json_encode($global_scenes, 256);
  12831. }
  12832. if ($props_added) {
  12833. $update_data['props'] = json_encode($global_props, 256);
  12834. }
  12835. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12836. dLog('deepseek')->info('剧集数据同步到全局完成', [
  12837. 'anime_id' => $anime_id,
  12838. 'roles_added' => $roles_added,
  12839. 'roles_updated' => $roles_updated,
  12840. 'scenes_added' => $scenes_added,
  12841. 'props_added' => $props_added,
  12842. 'global_roles_count' => count($global_roles),
  12843. 'global_scenes_count' => count($global_scenes),
  12844. 'global_props_count' => count($global_props)
  12845. ]);
  12846. }
  12847. return true;
  12848. }
  12849. /**
  12850. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  12851. *
  12852. * @param int $anime_id 动漫对话ID
  12853. * @param int $episode_id 分集ID
  12854. * @return bool
  12855. */
  12856. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  12857. // 获取全局角色和场景数据
  12858. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12859. if (!$anime) {
  12860. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12861. return false;
  12862. }
  12863. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12864. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12865. // 获取指定的分集
  12866. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  12867. if (!$episode) {
  12868. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12869. return false;
  12870. }
  12871. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12872. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12873. $roles_updated = false;
  12874. $scenes_updated = false;
  12875. // 继承角色的task_id、task_status和url
  12876. foreach ($episode_roles as &$episode_role) {
  12877. $episode_role_name = getProp($episode_role, 'role');
  12878. $episode_description = getProp($episode_role, 'description');
  12879. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12880. $episode_url = getProp($episode_role, 'url');
  12881. // 跳过旁白角色
  12882. if ($episode_role_name == '旁白') {
  12883. continue;
  12884. }
  12885. // 如果剧集中已有URL,跳过
  12886. if (!empty($episode_url)) {
  12887. continue;
  12888. }
  12889. // 遍历全局角色数据,查找匹配的角色
  12890. foreach ($global_roles as $global_role) {
  12891. $global_role_name = getProp($global_role, 'role');
  12892. $global_description = getProp($global_role, 'description');
  12893. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12894. $global_url = getProp($global_role, 'url');
  12895. $global_task_id = getProp($global_role, 'task_id');
  12896. $global_task_status = getProp($global_role, 'task_status');
  12897. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12898. if ($episode_role_name == $global_role_name
  12899. && $episode_description == $global_description
  12900. && $episode_pic_prompt == $global_pic_prompt) {
  12901. // 继承 task_id、task_status 和 url
  12902. if (!empty($global_task_id)) {
  12903. $episode_role['task_id'] = $global_task_id;
  12904. $episode_role['task_status'] = $global_task_status;
  12905. $roles_updated = true;
  12906. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12907. 'episode_id' => $episode_id,
  12908. 'role' => $episode_role_name,
  12909. 'task_id' => $global_task_id,
  12910. 'task_status' => $global_task_status
  12911. ]);
  12912. }
  12913. if (!empty($global_url)) {
  12914. $episode_role['url'] = $global_url;
  12915. $roles_updated = true;
  12916. dLog('deepseek')->info('剧集角色继承全局url', [
  12917. 'episode_id' => $episode_id,
  12918. 'role' => $episode_role_name,
  12919. 'url' => $global_url
  12920. ]);
  12921. }
  12922. break;
  12923. }
  12924. }
  12925. }
  12926. // 继承场景的task_id、task_status和url
  12927. foreach ($episode_scenes as &$episode_scene) {
  12928. $episode_scene_name = getProp($episode_scene, 'scene');
  12929. $episode_description = getProp($episode_scene, 'description');
  12930. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12931. $episode_url = getProp($episode_scene, 'url');
  12932. // 如果剧集中已有URL,跳过
  12933. if (!empty($episode_url)) {
  12934. continue;
  12935. }
  12936. // 遍历全局场景数据,查找匹配的场景
  12937. foreach ($global_scenes as $global_scene) {
  12938. $global_scene_name = getProp($global_scene, 'scene');
  12939. $global_description = getProp($global_scene, 'description');
  12940. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12941. $global_url = getProp($global_scene, 'url');
  12942. $global_task_id = getProp($global_scene, 'task_id');
  12943. $global_task_status = getProp($global_scene, 'task_status');
  12944. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12945. if ($episode_scene_name == $global_scene_name
  12946. && $episode_description == $global_description
  12947. && $episode_pic_prompt == $global_pic_prompt) {
  12948. // 继承 task_id、task_status 和 url
  12949. if (!empty($global_task_id)) {
  12950. $episode_scene['task_id'] = $global_task_id;
  12951. $episode_scene['task_status'] = $global_task_status;
  12952. $scenes_updated = true;
  12953. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12954. 'episode_id' => $episode_id,
  12955. 'scene' => $episode_scene_name,
  12956. 'task_id' => $global_task_id,
  12957. 'task_status' => $global_task_status
  12958. ]);
  12959. }
  12960. if (!empty($global_url)) {
  12961. $episode_scene['url'] = $global_url;
  12962. $scenes_updated = true;
  12963. dLog('deepseek')->info('剧集场景继承全局url', [
  12964. 'episode_id' => $episode_id,
  12965. 'scene' => $episode_scene_name,
  12966. 'url' => $global_url
  12967. ]);
  12968. }
  12969. break;
  12970. }
  12971. }
  12972. }
  12973. // 如果有更新,则保存到数据库
  12974. if ($roles_updated || $scenes_updated) {
  12975. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12976. if ($roles_updated) {
  12977. $update_data['roles'] = json_encode($episode_roles, 256);
  12978. }
  12979. if ($scenes_updated) {
  12980. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12981. }
  12982. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12983. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12984. 'episode_id' => $episode_id,
  12985. 'roles_updated' => $roles_updated,
  12986. 'scenes_updated' => $scenes_updated
  12987. ]);
  12988. }
  12989. return true;
  12990. }
  12991. public function chatChangeImg($data) {
  12992. $segment = getProp($data, 'segment');
  12993. $segment_content = getProp($segment, 'segment_content');
  12994. $prompt = getProp($data, 'prompt');
  12995. $ref_img = getProp($data, 'ref_img');
  12996. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12997. // 处理文本模型
  12998. $model = getProp($data, 'model');
  12999. if (!$model) {
  13000. // 用户没有输入,从anime表获取
  13001. $segment_id = getProp($segment, 'segment_id');
  13002. if ($segment_id) {
  13003. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  13004. if ($episode_id) {
  13005. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  13006. if ($anime_id) {
  13007. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  13008. }
  13009. }
  13010. }
  13011. if (!$model) {
  13012. // anime表也没有,使用默认值
  13013. $model = 'doubao-seed-2-0-mini-260215';
  13014. }
  13015. }
  13016. // 验证模型是否在可用模型表中
  13017. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  13018. $model = 'doubao-seed-2-0-mini-260215';
  13019. }
  13020. $messages[] =
  13021. [
  13022. 'role' => 'user',
  13023. 'content' => $question
  13024. ];
  13025. $post_data = [
  13026. 'model' => $model,
  13027. 'messages' => $messages,
  13028. // 'max_tokens' => 8192,
  13029. 'temperature' => 0.7,
  13030. 'frequency_penalty' => 0,
  13031. 'presence_penalty' => 0,
  13032. 'response_format' => ['type' => 'text'],
  13033. 'stream' => false // 是否启用流式输出
  13034. ];
  13035. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  13036. // DeepSeek 官方模型使用 DeepSeek API
  13037. $chatResult = $this->chatOnly($post_data);
  13038. } else if (in_array($model, $this->gpt_text_models)) {
  13039. // GPT-5.4 模型使用 TokenRouter API
  13040. $chatResult = $this->gpt54ChatOnly($post_data);
  13041. } else {
  13042. // 其他模型使用火山引擎API
  13043. $chatResult = $this->volcEngineChatCompletion($post_data);
  13044. }
  13045. if (is_array($chatResult)) {
  13046. extract($chatResult);
  13047. }else {
  13048. Utils::throwError('20003: 接口调用失败!');
  13049. }
  13050. // 仅记录 token 使用明细(不扣积分)
  13051. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  13052. 'model' => $model,
  13053. 'source' => 'chatChangeImg',
  13054. ], $model);
  13055. return [
  13056. 'type' => 'done',
  13057. // 'episode' => $episode,
  13058. 'answer' => $fullContent,
  13059. 'reasoning' => $fullReasoningContent,
  13060. 'usage' => $usage
  13061. ];
  13062. }
  13063. /**
  13064. * 仅调用 deepseek 对话接口(非流式)
  13065. *
  13066. * @param array $post_data
  13067. * @param int $timeout
  13068. * @return array
  13069. */
  13070. private function chatOnly($post_data, $timeout = 1800) {
  13071. $post_data['max_tokens'] = 300000;
  13072. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  13073. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  13074. $response = $result->getBody()->getContents();
  13075. $response_arr = json_decode($response, true);
  13076. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  13077. $fullContent = '';
  13078. $fullReasoningContent = [];
  13079. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  13080. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  13081. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  13082. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  13083. }
  13084. return [
  13085. 'fullContent' => $fullContent,
  13086. 'fullReasoningContent' => $fullReasoningContent,
  13087. 'usage' => $usage
  13088. ];
  13089. }
  13090. /**
  13091. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  13092. *
  13093. * @param string $errorMessage
  13094. * @return string|null
  13095. */
  13096. public function analyzeErrorMessage($errorMessage)
  13097. {
  13098. try {
  13099. $post_data = [
  13100. 'model' => 'deepseek-v4-flash',
  13101. 'messages' => [
  13102. [
  13103. 'role' => 'system',
  13104. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  13105. ],
  13106. [
  13107. 'role' => 'user',
  13108. 'content' => (string)$errorMessage,
  13109. ],
  13110. ],
  13111. 'temperature' => 0.3,
  13112. 'frequency_penalty' => 0,
  13113. 'presence_penalty' => 0,
  13114. 'response_format' => ['type' => 'text'],
  13115. 'stream' => false,
  13116. ];
  13117. $result = $this->chatOnly($post_data, 8);
  13118. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  13119. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  13120. 'model' => 'deepseek-v4-flash',
  13121. 'source' => 'analyzeErrorMessage',
  13122. ], 'deepseek-v4-flash');
  13123. $content = trim((string)($result['fullContent'] ?? ''));
  13124. if ($content === '') {
  13125. return null;
  13126. }
  13127. return mb_substr($content, 0, 50);
  13128. } catch (\Exception $e) {
  13129. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  13130. 'error_message' => $errorMessage
  13131. ]);
  13132. return null;
  13133. }
  13134. }
  13135. // 仅调用 GPT-5.4 对话接口(非流式)
  13136. private function gpt54ChatOnly($post_data) {
  13137. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  13138. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  13139. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  13140. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  13141. $usedLunaFallback = false;
  13142. if (empty($apiKey)) {
  13143. Utils::throwError('20003:GPT-5.4 API Key未配置');
  13144. }
  13145. // 先探活,服务不可用时自动重试
  13146. $this->ensureGptServiceAvailable($apiKey);
  13147. $client = new Client(['timeout' => 1800, 'verify' => false]);
  13148. // 移除 thinking 参数,GPT-5.4 不支持
  13149. if (isset($post_data['thinking'])) {
  13150. unset($post_data['thinking']);
  13151. }
  13152. if (isset($post_data['reasoning_effort'])) {
  13153. unset($post_data['reasoning_effort']);
  13154. }
  13155. $post_data['max_completion_tokens'] = 100000;
  13156. // 确保 stream 为 false
  13157. $post_data['stream'] = false;
  13158. $maxRetries = $this->gptRetryTimes();
  13159. $interval = $this->gptRetryInterval();
  13160. $attempt = 0;
  13161. while (true) {
  13162. try {
  13163. $headers = [
  13164. 'Authorization' => 'Bearer ' . $apiKey,
  13165. 'Content-Type' => 'application/json'
  13166. ];
  13167. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  13168. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  13169. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  13170. 'json' => $post_data,
  13171. 'headers' => $headers
  13172. ]);
  13173. $response = $result->getBody()->getContents();
  13174. $response_arr = json_decode($response, true);
  13175. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  13176. $fullContent = '';
  13177. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  13178. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  13179. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  13180. }
  13181. return [
  13182. 'fullContent' => $fullContent,
  13183. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  13184. 'usage' => $usage
  13185. ];
  13186. } catch (\Exception $e) {
  13187. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  13188. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  13189. $usedLunaFallback = true;
  13190. $apiKey = $lunaApiKey;
  13191. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  13192. continue;
  13193. }
  13194. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  13195. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  13196. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  13197. throw $e;
  13198. }
  13199. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  13200. 'retry' => $attempt + 1,
  13201. 'max_retries' => $maxRetries,
  13202. 'error' => $e->getMessage()
  13203. ]);
  13204. sleep($interval);
  13205. $attempt++;
  13206. }
  13207. }
  13208. }
  13209. public function getContentByBid($bid) {
  13210. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  13211. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  13212. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  13213. $content = '';
  13214. foreach ($chapters as $chapter) {
  13215. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  13216. }
  13217. return $content;
  13218. }
  13219. public function getContentByScriptId($script_id) {
  13220. $content = '';
  13221. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  13222. if ($contents) {
  13223. $content = implode(PHP_EOL, $contents);
  13224. }else {
  13225. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  13226. }
  13227. return $content;
  13228. }
  13229. /**
  13230. * 根据文件类型提取文本内容
  13231. *
  13232. * @param mixed $file 文件对象或文件路径
  13233. * @return string
  13234. */
  13235. public function extractFileContent($file) {
  13236. // 获取文件路径和扩展名
  13237. if (is_string($file)) {
  13238. $filePath = $file;
  13239. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  13240. } else {
  13241. // Laravel UploadedFile 对象
  13242. $filePath = $file->getRealPath();
  13243. $extension = strtolower($file->getClientOriginalExtension());
  13244. }
  13245. $content = '';
  13246. switch ($extension) {
  13247. case 'txt':
  13248. $content = $this->extractTxtContent($filePath);
  13249. break;
  13250. case 'pdf':
  13251. $content = $this->extractPdfContent($filePath);
  13252. break;
  13253. case 'doc':
  13254. case 'docx':
  13255. $content = $this->extractWordContent($filePath);
  13256. break;
  13257. // case 'jpg':
  13258. // case 'jpeg':
  13259. // case 'png':
  13260. // case 'gif':
  13261. // case 'bmp':
  13262. // case 'webp':
  13263. // $content = $this->extractImageContent($filePath);
  13264. // break;
  13265. default:
  13266. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  13267. }
  13268. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  13269. if (!mb_check_encoding($content, 'UTF-8')) {
  13270. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  13271. $content = $cleaned === false ? $content : $cleaned;
  13272. }
  13273. return $content;
  13274. }
  13275. /**
  13276. * 提取 TXT 文件内容
  13277. */
  13278. private function extractTxtContent($filePath) {
  13279. if (!file_exists($filePath)) {
  13280. Utils::throwError('20003:文件不存在');
  13281. }
  13282. $content = file_get_contents($filePath);
  13283. // 尝试检测并转换编码
  13284. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  13285. if ($encoding && $encoding !== 'UTF-8') {
  13286. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  13287. }
  13288. return trim($content);
  13289. }
  13290. /**
  13291. * 提取 PDF 文件内容
  13292. */
  13293. private function extractPdfContent($filePath) {
  13294. if (!file_exists($filePath)) {
  13295. Utils::throwError('20003:文件不存在');
  13296. }
  13297. try {
  13298. $parser = new PdfParser();
  13299. $pdf = $parser->parseFile($filePath);
  13300. $content = $pdf->getText();
  13301. return trim($content);
  13302. } catch (\Exception $e) {
  13303. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  13304. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  13305. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  13306. }
  13307. }
  13308. /**
  13309. * 提取 Word 文件内容(支持 doc 和 docx)
  13310. */
  13311. private function extractWordContent($filePath) {
  13312. if (!file_exists($filePath)) {
  13313. Utils::throwError('20003:文件不存在');
  13314. }
  13315. try {
  13316. $phpWord = WordIOFactory::load($filePath);
  13317. $content = '';
  13318. foreach ($phpWord->getSections() as $section) {
  13319. foreach ($section->getElements() as $element) {
  13320. $content .= $this->extractWordElementText($element);
  13321. }
  13322. }
  13323. return trim($content);
  13324. } catch (\Exception $e) {
  13325. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  13326. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  13327. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  13328. }
  13329. }
  13330. /**
  13331. * 递归提取 Word 元素中的文本
  13332. */
  13333. private function extractWordElementText($element) {
  13334. $text = '';
  13335. if (method_exists($element, 'getText')) {
  13336. $text .= $element->getText() . "\n";
  13337. } elseif (method_exists($element, 'getElements')) {
  13338. foreach ($element->getElements() as $childElement) {
  13339. $text .= $this->extractWordElementText($childElement);
  13340. }
  13341. }
  13342. return $text;
  13343. }
  13344. /**
  13345. * 提取图片内容(使用火山引擎 OCR)
  13346. */
  13347. private function extractImageContent($filePath) {
  13348. if (!file_exists($filePath)) {
  13349. Utils::throwError('20003:文件不存在');
  13350. }
  13351. try {
  13352. // 读取图片并转换为 base64
  13353. $imageData = file_get_contents($filePath);
  13354. $base64Image = base64_encode($imageData);
  13355. // 调用火山引擎 OCR 服务
  13356. $content = $this->callVolcEngineOCR($base64Image);
  13357. return trim($content);
  13358. } catch (\Exception $e) {
  13359. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  13360. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  13361. Utils::throwError('20003:图片识别失败');
  13362. }
  13363. }
  13364. /**
  13365. * 调用火山引擎 OCR 服务识别图片文字
  13366. *
  13367. * @param string $base64Image base64 编码的图片数据
  13368. * @return string 识别的文字内容
  13369. */
  13370. private function callVolcEngineOCR($base64Image) {
  13371. $method = 'POST';
  13372. $service = 'cv';
  13373. $host = 'visual.volcengineapi.com';
  13374. $region = env('VOLC_REGION', 'cn-north-1');
  13375. $access_key = env('VOLC_AK');
  13376. $secret_key = env('VOLC_SK');
  13377. $action = 'OCRNormal';
  13378. $version = '2020-08-26';
  13379. if (!$access_key || !$secret_key) {
  13380. Utils::throwError('20003:请配置火山引擎 AK/SK');
  13381. }
  13382. // 请求体
  13383. $body = json_encode([
  13384. 'image_base64' => $base64Image
  13385. ]);
  13386. // 生成签名
  13387. $headers = $this->getVolcEngineSignHeaders(
  13388. $method, $service, $host, $region,
  13389. "Action={$action}&Version={$version}",
  13390. $access_key, $secret_key, $body
  13391. );
  13392. $client = new Client(['timeout' => 1800, 'verify' => false]);
  13393. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  13394. 'headers' => $headers,
  13395. 'body' => $body
  13396. ]);
  13397. $response_arr = json_decode($response->getBody()->getContents(), true);
  13398. // 提取识别的文字
  13399. $textLines = [];
  13400. if (isset($response_arr['data']['line_texts'])) {
  13401. $textLines = $response_arr['data']['line_texts'];
  13402. } elseif (isset($response_arr['data']['ocr_infos'])) {
  13403. foreach ($response_arr['data']['ocr_infos'] as $info) {
  13404. if (isset($info['text'])) {
  13405. $textLines[] = $info['text'];
  13406. }
  13407. }
  13408. }
  13409. if (empty($textLines)) {
  13410. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  13411. return '';
  13412. }
  13413. return implode("\n", $textLines);
  13414. }
  13415. /**
  13416. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  13417. */
  13418. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  13419. $contentType = 'application/json';
  13420. $accept = 'application/json';
  13421. // 获取当前UTC时间
  13422. $t = new DateTime('now', new DateTimeZone('UTC'));
  13423. $xDate = $t->format('Ymd\THis\Z');
  13424. $dateStamp = $t->format('Ymd');
  13425. // 计算 body 的 sha256 哈希
  13426. $payloadHash = hash('sha256', $body);
  13427. // 1. 拼接规范请求串
  13428. $canonicalUri = '/';
  13429. $canonicalQueryString = $queryString;
  13430. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  13431. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  13432. $canonicalRequest = implode("\n", [
  13433. $method,
  13434. $canonicalUri,
  13435. $canonicalQueryString,
  13436. $canonicalHeaders,
  13437. $signedHeaders,
  13438. $payloadHash
  13439. ]);
  13440. // 2. 拼接待签名字符串
  13441. $algorithm = 'HMAC-SHA256';
  13442. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  13443. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  13444. $stringToSign = implode("\n", [
  13445. $algorithm,
  13446. $xDate,
  13447. $credentialScope,
  13448. $hashedCanonicalRequest
  13449. ]);
  13450. // 3. 计算签名
  13451. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  13452. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  13453. // 4. 添加签名到请求头
  13454. $authorizationHeader = sprintf(
  13455. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  13456. $algorithm,
  13457. $access_key,
  13458. $credentialScope,
  13459. $signedHeaders,
  13460. $signature
  13461. );
  13462. return [
  13463. 'Accept' => $accept,
  13464. 'Content-Type' => $contentType,
  13465. 'Host' => $host,
  13466. 'X-Date' => $xDate,
  13467. 'X-Content-Sha256'=> $payloadHash,
  13468. 'Authorization' => $authorizationHeader
  13469. ];
  13470. }
  13471. public function generateScriptWords($cid, $model = 'r1') {
  13472. ini_set('max_execution_time', 0);
  13473. if (!$cid) Utils::throwError('20003: 请选择章节!');
  13474. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  13475. // 模型兼容性处理和思考模式设置
  13476. $thinkingMode = 'disabled';
  13477. $reasoningEffort = 'high';
  13478. if ($model == 'r1') {
  13479. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  13480. $thinkingMode = 'enabled';
  13481. } else {
  13482. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  13483. $thinkingMode = 'disabled';
  13484. }
  13485. $messages = [
  13486. [
  13487. 'role' => 'system',
  13488. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  13489. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  13490. 2.非对话部分请全部用旁白角色代替
  13491. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  13492. ],
  13493. [
  13494. 'role' => 'user',
  13495. 'content' => $content
  13496. ]
  13497. ];
  13498. $post_data = [
  13499. 'model' => $model,
  13500. 'messages' => $messages,
  13501. // 'max_tokens' => 8192,
  13502. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  13503. 'frequency_penalty' => 0,
  13504. 'presence_penalty' => 0,
  13505. 'thinking' => ['type' => $thinkingMode],
  13506. 'response_format' => [
  13507. 'type' => 'text'
  13508. ],
  13509. 'stream' => false
  13510. ];
  13511. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  13512. // 根据模型类型选择调用方法
  13513. $fullContent = '';
  13514. $usage = [];
  13515. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  13516. // DeepSeek 官方模型使用 DeepSeek API
  13517. $chatResult = $this->chatOnly($post_data);
  13518. } else if (in_array($model, $this->gpt_text_models)) {
  13519. // GPT-5.4 模型使用 TokenRouter API
  13520. $chatResult = $this->gpt54ChatOnly($post_data);
  13521. } else {
  13522. // 其他模型使用火山引擎API
  13523. $chatResult = $this->volcEngineChatCompletion($post_data);
  13524. }
  13525. if (is_array($chatResult)) {
  13526. $fullContent = $chatResult['fullContent'];
  13527. $usage = $chatResult['usage'] ?? [];
  13528. }
  13529. // 仅记录 token 使用明细(不扣积分)
  13530. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  13531. 'model' => $model,
  13532. 'cid' => $cid,
  13533. 'source' => 'generateScriptWords',
  13534. ], $model);
  13535. return $fullContent;
  13536. }
  13537. /**
  13538. * 智能化解析集数信息
  13539. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  13540. *
  13541. * @param string $prompt 用户输入的提示词
  13542. * @return int|null 解析出的集数,如果没有找到则返回null
  13543. */
  13544. private function extractEpisodeNumber($prompt)
  13545. {
  13546. if (empty($prompt)) {
  13547. return null;
  13548. }
  13549. // 定义各种可能的表达模式
  13550. $patterns = [
  13551. // 基本模式:改成N集、调整成N集、修改成N集
  13552. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  13553. // 扩展模式:分成N集、拆分成N集、分割成N集
  13554. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  13555. // 数量模式:N集、共N集、总共N集
  13556. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  13557. // 制作模式:制作N集、生成N集、创建N集
  13558. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  13559. // 计划模式:计划N集、预计N集、打算N集
  13560. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  13561. // 需要模式:需要N集、要N集
  13562. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  13563. // 中文数字模式:改成三集、调整成五集等
  13564. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  13565. // 英文数字模式
  13566. '/(?: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',
  13567. ];
  13568. // 中文数字转阿拉伯数字的映射
  13569. $chineseNumbers = [
  13570. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  13571. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  13572. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  13573. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  13574. ];
  13575. // 逐个尝试匹配模式
  13576. foreach ($patterns as $pattern) {
  13577. if (preg_match($pattern, $prompt, $matches)) {
  13578. $number = trim($matches[1]);
  13579. // 如果是中文数字,转换为阿拉伯数字
  13580. if (isset($chineseNumbers[$number])) {
  13581. return $chineseNumbers[$number];
  13582. }
  13583. // 如果是阿拉伯数字,直接返回
  13584. if (is_numeric($number)) {
  13585. $episodeNum = intval($number);
  13586. // 合理性检查:集数应该在1-100之间
  13587. if ($episodeNum >= 1 && $episodeNum <= 100) {
  13588. return $episodeNum;
  13589. }
  13590. }
  13591. }
  13592. }
  13593. return null;
  13594. }
  13595. /**
  13596. * 调用火山引擎对话(Chat) API
  13597. *
  13598. * @param array $params 包含以下参数:
  13599. * - model: 模型ID(必填)
  13600. * - messages: 消息列表(必填)
  13601. * - stream: 是否流式输出(可选,默认false)
  13602. * - max_tokens: 最大输出token数(可选)
  13603. * - temperature: 采样温度(可选,默认1)
  13604. * - top_p: 核采样概率(可选,默认0.7)
  13605. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  13606. * - presence_penalty: 存在惩罚系数(可选,默认0)
  13607. * - stop: 停止词(可选)
  13608. * - tools: 工具列表(可选)
  13609. * @return array|Generator 非流式返回数组,流式返回生成器
  13610. */
  13611. public function volcEngineChatCompletion(array $params)
  13612. {
  13613. $apiKey = env('VOLC_AI_API_KEY');
  13614. if (empty($apiKey)) {
  13615. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  13616. }
  13617. // 构建请求参数
  13618. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  13619. $requestData = [
  13620. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  13621. 'messages' => $params['messages'] ?? [],
  13622. ];
  13623. if (!in_array($originalModel, $this->valid_text_models)) {
  13624. Utils::throwError('20003:该模型不支持!');
  13625. }
  13626. // 添加可选参数
  13627. if (isset($params['stream'])) {
  13628. $requestData['stream'] = $params['stream'];
  13629. }
  13630. if (isset($params['stream_options'])) {
  13631. $requestData['stream_options'] = $params['stream_options'];
  13632. }
  13633. if (isset($params['max_tokens'])) {
  13634. $requestData['max_tokens'] = $params['max_tokens'];
  13635. }else if (isset($params['max_completion_tokens'])) {
  13636. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  13637. }else {
  13638. $requestData['max_completion_tokens'] = 100000;
  13639. }
  13640. if (isset($params['temperature'])) {
  13641. $requestData['temperature'] = $params['temperature'];
  13642. }
  13643. if (isset($params['top_p'])) {
  13644. $requestData['top_p'] = $params['top_p'];
  13645. }
  13646. if (isset($params['frequency_penalty'])) {
  13647. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  13648. }
  13649. if (isset($params['presence_penalty'])) {
  13650. $requestData['presence_penalty'] = $params['presence_penalty'];
  13651. }
  13652. if (isset($params['stop'])) {
  13653. $requestData['stop'] = $params['stop'];
  13654. }
  13655. if (isset($params['tools'])) {
  13656. $requestData['tools'] = $params['tools'];
  13657. }
  13658. if (isset($params['tool_choice'])) {
  13659. $requestData['tool_choice'] = $params['tool_choice'];
  13660. }
  13661. if (isset($params['response_format'])) {
  13662. $requestData['response_format'] = $params['response_format'];
  13663. }
  13664. if (isset($params['thinking'])) {
  13665. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  13666. if (is_array($params['thinking'])) {
  13667. $requestData['thinking'] = $params['thinking'];
  13668. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  13669. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13670. }
  13671. } else {
  13672. $requestData['thinking'] = ['type' => $params['thinking']];
  13673. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  13674. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13675. }
  13676. }
  13677. } else {
  13678. $requestData['thinking'] = ['type' => 'disabled'];
  13679. }
  13680. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  13681. $client = new Client(['verify' => false, 'timeout' => 1800]);
  13682. try {
  13683. // 判断是否为流式输出
  13684. $isStream = isset($params['stream']) && $params['stream'] === true;
  13685. if ($isStream) {
  13686. // 流式输出
  13687. // 流式请求默认声明返回 usage(未显式传参时)
  13688. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  13689. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  13690. } else {
  13691. // 非流式输出
  13692. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13693. 'headers' => [
  13694. 'Authorization' => 'Bearer ' . $apiKey,
  13695. 'Content-Type' => 'application/json',
  13696. ],
  13697. 'json' => $requestData
  13698. ]);
  13699. $responseData = json_decode($response->getBody(), true);
  13700. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  13701. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  13702. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  13703. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  13704. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  13705. }
  13706. return [
  13707. 'fullContent' => $fullContent,
  13708. 'fullReasoningContent' => $fullReasoningContent,
  13709. 'usage' => $usage
  13710. ];
  13711. }
  13712. } catch (\Exception $e) {
  13713. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  13714. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  13715. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  13716. }
  13717. }
  13718. /**
  13719. * 火山引擎对话API流式输出
  13720. *
  13721. * @param Client $client HTTP客户端
  13722. * @param string $apiKey API密钥
  13723. * @param array $requestData 请求数据
  13724. * @return Generator
  13725. */
  13726. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  13727. {
  13728. try {
  13729. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13730. 'headers' => [
  13731. 'Authorization' => 'Bearer ' . $apiKey,
  13732. 'Content-Type' => 'application/json',
  13733. ],
  13734. 'json' => $requestData,
  13735. 'stream' => true
  13736. ]);
  13737. $body = $response->getBody();
  13738. $buffer = '';
  13739. $fullContent = '';
  13740. $fullReasoningContent = '';
  13741. $usage = [];
  13742. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  13743. // 逐行读取流式响应
  13744. while (!$body->eof()) {
  13745. $chunk = $body->read(1024);
  13746. $buffer .= $chunk;
  13747. // 按行分割
  13748. $lines = explode("\n", $buffer);
  13749. $buffer = array_pop($lines);
  13750. foreach ($lines as $line) {
  13751. $line = trim($line);
  13752. if (empty($line)) {
  13753. continue;
  13754. }
  13755. // 检查是否是SSE数据行
  13756. if (strpos($line, 'data: ') !== 0) {
  13757. continue;
  13758. }
  13759. $data = substr($line, 6);
  13760. if ($data === '[DONE]') {
  13761. dLog('deepseek')->info('收到结束标记');
  13762. break 2;
  13763. }
  13764. try {
  13765. $json = json_decode($data, true);
  13766. if (json_last_error() !== JSON_ERROR_NONE) {
  13767. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  13768. continue;
  13769. }
  13770. if (isset($json['choices'][0]['delta'])) {
  13771. $delta = $json['choices'][0]['delta'];
  13772. // 处理思维链内容
  13773. if (isset($delta['reasoning_content'])) {
  13774. $fullReasoningContent .= $delta['reasoning_content'];
  13775. yield [
  13776. 'type' => 'reasoning',
  13777. 'content' => $delta['reasoning_content'],
  13778. 'full_reasoning' => $fullReasoningContent
  13779. ];
  13780. }
  13781. // 处理回答内容
  13782. if (isset($delta['content'])) {
  13783. $fullContent .= $delta['content'];
  13784. yield [
  13785. 'type' => 'content',
  13786. 'content' => $delta['content'],
  13787. ];
  13788. }
  13789. }
  13790. // 获取使用统计信息
  13791. if (isset($json['usage'])) {
  13792. $usage = $json['usage'];
  13793. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  13794. }
  13795. } catch (\Exception $e) {
  13796. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  13797. continue;
  13798. }
  13799. }
  13800. }
  13801. dLog('deepseek')->info('流式读取完成', [
  13802. 'content_length' => strlen($fullContent),
  13803. 'reasoning_length' => strlen($fullReasoningContent)
  13804. ]);
  13805. yield [
  13806. 'type' => 'done',
  13807. 'full_content' => $fullContent,
  13808. 'full_reasoning' => $fullReasoningContent,
  13809. 'usage' => $usage
  13810. ];
  13811. } catch (\Exception $e) {
  13812. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  13813. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  13814. throw $e;
  13815. }
  13816. }
  13817. /**
  13818. * 检查并创建图片生成任务
  13819. *
  13820. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  13821. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  13822. * @param string $nameKey 资源名称字段('role' 或 'scene')
  13823. * @param string $art_style 美术风格
  13824. * @return array 更新后的资源列表
  13825. */
  13826. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  13827. {
  13828. // 确保参数为数组
  13829. $merged_items = is_array($merged_items) ? $merged_items : [];
  13830. $global_items = is_array($global_items) ? $global_items : [];
  13831. // 构建全局资源映射表,用于快速查找
  13832. $global_map = [];
  13833. foreach ($global_items as $item) {
  13834. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13835. if ($itemKey === '') {
  13836. continue;
  13837. }
  13838. $global_map[$itemKey] = $item;
  13839. }
  13840. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  13841. foreach ($merged_items as &$item) {
  13842. $item_name = getProp($item, $nameKey);
  13843. $item_description = getProp($item, 'description');
  13844. // $item_url = getProp($item, 'url');
  13845. // // 如果已有图片URL,跳过
  13846. // if (!empty($item_url)) {
  13847. // continue;
  13848. // }
  13849. // 如果是旁白角色,跳过
  13850. if ($nameKey === 'role' && $item_name === '旁白') {
  13851. continue;
  13852. }
  13853. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13854. if ($itemKey === '') {
  13855. continue;
  13856. }
  13857. $need_create_task = false;
  13858. // 条件1:在全局资源中找不到匹配的名称
  13859. if (!isset($global_map[$itemKey])) {
  13860. $need_create_task = true;
  13861. } else {
  13862. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13863. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13864. $current_description = trim((string)$item_description);
  13865. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13866. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13867. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13868. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13869. $need_create_task = true;
  13870. }
  13871. }
  13872. // 如果需要创建任务,调用图片生成服务
  13873. if ($need_create_task) {
  13874. try {
  13875. // 优先使用 pic_prompt,如果没有则使用 description
  13876. $pic_prompt = getProp($item, 'pic_prompt');
  13877. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13878. // 添加美术风格前缀
  13879. if ($art_style) {
  13880. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13881. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13882. $description = "{$prefix}:{$description}";
  13883. }
  13884. $params = [
  13885. 'prompt' => $description,
  13886. 'ref_img_urls' => []
  13887. ];
  13888. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13889. $task_id = $task->id;
  13890. if ($task_id) {
  13891. $item['task_id'] = $task_id;
  13892. $item['task_status'] = 'processing';
  13893. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13894. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13895. }
  13896. } catch (\Exception $e) {
  13897. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13898. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13899. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13900. // 不抛出异常,继续处理其他资源
  13901. }
  13902. }
  13903. }
  13904. return $merged_items;
  13905. }
  13906. /**
  13907. * 同步新出现的主体和场景到全局
  13908. *
  13909. * @param int $anime_id 动漫ID
  13910. * @param array $merged_roles 合并后的角色列表
  13911. * @param array $merged_scenes 合并后的场景列表
  13912. * @param array $global_roles 全局角色列表
  13913. * @param array $global_scenes 全局场景列表
  13914. * @return void
  13915. */
  13916. private function syncNewResourcesToGlobal(
  13917. int $anime_id,
  13918. array $merged_roles,
  13919. array $merged_scenes,
  13920. array $global_roles,
  13921. array $global_scenes
  13922. ): void {
  13923. // 构建全局角色映射表
  13924. $global_role_map = [];
  13925. foreach ($global_roles as $role) {
  13926. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13927. if ($roleKey !== '') {
  13928. $global_role_map[$roleKey] = $role;
  13929. }
  13930. }
  13931. // 构建全局场景映射表
  13932. $global_scene_map = [];
  13933. foreach ($global_scenes as $scene) {
  13934. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13935. if ($sceneKey !== '') {
  13936. $global_scene_map[$sceneKey] = $scene;
  13937. }
  13938. }
  13939. $need_update = false;
  13940. $new_global_roles = $global_roles;
  13941. $new_global_scenes = $global_scenes;
  13942. // 检查并添加新角色到全局
  13943. foreach ($merged_roles as $role) {
  13944. $role_name = getProp($role, 'role');
  13945. // 跳过旁白
  13946. if ($role_name === '旁白') {
  13947. continue;
  13948. }
  13949. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13950. if ($roleKey === '') {
  13951. continue;
  13952. }
  13953. // 如果全局中不存在该角色,添加到全局
  13954. if (!isset($global_role_map[$roleKey])) {
  13955. $new_global_roles[] = [
  13956. 'role' => $role_name,
  13957. 'description' => getProp($role, 'description', ''),
  13958. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13959. 'voice_name' => getProp($role, 'voice_name', ''),
  13960. 'voice_type' => getProp($role, 'voice_type', ''),
  13961. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13962. 'url' => getProp($role, 'url', ''),
  13963. 'task_id' => getProp($role, 'task_id', ''),
  13964. 'task_status' => getProp($role, 'task_status', ''),
  13965. ];
  13966. $global_role_map[$roleKey] = true; // 标记已添加
  13967. $need_update = true;
  13968. dLog('deepseek')->info("新角色同步到全局", [
  13969. 'anime_id' => $anime_id,
  13970. 'role' => $role_name,
  13971. 'task_id' => getProp($role, 'task_id', ''),
  13972. ]);
  13973. }
  13974. // else {
  13975. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13976. // $global_role = $global_role_map[$roleKey];
  13977. // if (is_array($global_role)) {
  13978. // $updated = false;
  13979. // $update_fields = [];
  13980. // // 检查描述是否更新
  13981. // $current_description = trim((string)getProp($role, 'description'));
  13982. // $global_description = trim((string)getProp($global_role, 'description'));
  13983. // if ($current_description !== '' && $current_description !== $global_description) {
  13984. // $updated = true;
  13985. // $update_fields[] = 'description';
  13986. // }
  13987. // // 检查pic_prompt是否更新
  13988. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13989. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13990. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13991. // $updated = true;
  13992. // $update_fields[] = 'pic_prompt';
  13993. // }
  13994. // // 检查图片任务信息是否更新
  13995. // $current_task_id = getProp($role, 'task_id');
  13996. // $global_task_id = getProp($global_role, 'task_id');
  13997. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13998. // $updated = true;
  13999. // $update_fields[] = 'task_id';
  14000. // }
  14001. // // 如果有更新,同步到全局
  14002. // if ($updated) {
  14003. // foreach ($new_global_roles as &$global_role_item) {
  14004. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  14005. // if ($global_role_key === $roleKey) {
  14006. // if (in_array('description', $update_fields)) {
  14007. // $global_role_item['description'] = $current_description;
  14008. // }
  14009. // if (in_array('pic_prompt', $update_fields)) {
  14010. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  14011. // }
  14012. // if (in_array('task_id', $update_fields)) {
  14013. // $global_role_item['task_id'] = $current_task_id;
  14014. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  14015. // $global_role_item['url'] = getProp($role, 'url', '');
  14016. // }
  14017. // break;
  14018. // }
  14019. // }
  14020. // $need_update = true;
  14021. // dLog('deepseek')->info("角色信息更新到全局", [
  14022. // 'anime_id' => $anime_id,
  14023. // 'role' => $role_name,
  14024. // 'update_fields' => implode(',', $update_fields),
  14025. // ]);
  14026. // }
  14027. // }
  14028. // }
  14029. }
  14030. // 检查并添加新场景到全局
  14031. foreach ($merged_scenes as $scene) {
  14032. $scene_name = getProp($scene, 'scene');
  14033. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  14034. if ($sceneKey === '') {
  14035. continue;
  14036. }
  14037. // 如果全局中不存在该场景,添加到全局
  14038. if (!isset($global_scene_map[$sceneKey])) {
  14039. $new_global_scenes[] = [
  14040. 'scene' => $scene_name,
  14041. 'description' => getProp($scene, 'description', ''),
  14042. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  14043. 'url' => getProp($scene, 'url', ''),
  14044. 'task_id' => getProp($scene, 'task_id', ''),
  14045. 'task_status' => getProp($scene, 'task_status', ''),
  14046. ];
  14047. $global_scene_map[$sceneKey] = true; // 标记已添加
  14048. $need_update = true;
  14049. dLog('deepseek')->info("新场景同步到全局", [
  14050. 'anime_id' => $anime_id,
  14051. 'scene' => $scene_name,
  14052. 'task_id' => getProp($scene, 'task_id', ''),
  14053. ]);
  14054. }
  14055. // else {
  14056. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  14057. // $global_scene = $global_scene_map[$sceneKey];
  14058. // if (is_array($global_scene)) {
  14059. // $updated = false;
  14060. // $update_fields = [];
  14061. // // 检查描述是否更新
  14062. // $current_description = trim((string)getProp($scene, 'description'));
  14063. // $global_description = trim((string)getProp($global_scene, 'description'));
  14064. // if ($current_description !== '' && $current_description !== $global_description) {
  14065. // $updated = true;
  14066. // $update_fields[] = 'description';
  14067. // }
  14068. // // 检查pic_prompt是否更新
  14069. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  14070. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  14071. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  14072. // $updated = true;
  14073. // $update_fields[] = 'pic_prompt';
  14074. // }
  14075. // // 检查图片任务信息是否更新
  14076. // $current_task_id = getProp($scene, 'task_id');
  14077. // $global_task_id = getProp($global_scene, 'task_id');
  14078. // if ($current_task_id && $current_task_id !== $global_task_id) {
  14079. // $updated = true;
  14080. // $update_fields[] = 'task_id';
  14081. // }
  14082. // // 如果有更新,同步到全局
  14083. // if ($updated) {
  14084. // foreach ($new_global_scenes as &$global_scene_item) {
  14085. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  14086. // if ($global_scene_key === $sceneKey) {
  14087. // if (in_array('description', $update_fields)) {
  14088. // $global_scene_item['description'] = $current_description;
  14089. // }
  14090. // if (in_array('pic_prompt', $update_fields)) {
  14091. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  14092. // }
  14093. // if (in_array('task_id', $update_fields)) {
  14094. // $global_scene_item['task_id'] = $current_task_id;
  14095. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  14096. // $global_scene_item['url'] = getProp($scene, 'url', '');
  14097. // }
  14098. // break;
  14099. // }
  14100. // }
  14101. // $need_update = true;
  14102. // dLog('deepseek')->info("场景信息更新到全局", [
  14103. // 'anime_id' => $anime_id,
  14104. // 'scene' => $scene_name,
  14105. // 'update_fields' => implode(',', $update_fields),
  14106. // ]);
  14107. // }
  14108. // }
  14109. // }
  14110. }
  14111. // 如果有新增或更新,更新数据库
  14112. if ($need_update) {
  14113. $update_data = [
  14114. 'roles' => json_encode($new_global_roles, 256),
  14115. 'scenes' => json_encode($new_global_scenes, 256),
  14116. 'updated_at' => date('Y-m-d H:i:s'),
  14117. ];
  14118. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  14119. if ($result !== false) {
  14120. dLog('deepseek')->info("全局角色和场景更新成功", [
  14121. 'anime_id' => $anime_id,
  14122. 'roles_count' => count($new_global_roles),
  14123. 'scenes_count' => count($new_global_scenes),
  14124. ]);
  14125. } else {
  14126. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  14127. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  14128. }
  14129. }
  14130. }
  14131. }