DeepSeekService.php 735 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302
  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\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\PointsService;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Redis;
  15. use OSS\Core\OssException;
  16. use OSS\OssClient;
  17. use Smalot\PdfParser\Parser as PdfParser;
  18. use TCPDF;
  19. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  20. use Predis\Command\Traits\Get\Get;
  21. class DeepSeekService
  22. {
  23. private $url;
  24. private $api_key;
  25. private $sys_message;
  26. private $headers;
  27. private $valid_text_models;
  28. private $gpt_text_models;
  29. protected $aiImageGenerationService;
  30. protected $pointsService;
  31. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  32. $this->aiImageGenerationService = $aiImageGenerationService;
  33. $this->pointsService = $pointsService;
  34. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. // 火山引擎模型列表
  41. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  42. // GPT文本模型列表
  43. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  44. $this->sys_message = [
  45. 'role' => 'system',
  46. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  47. 强制要求:\n
  48. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  49. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  50. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  51. 普通要求:\n
  52. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  53. 2.<分集剧本>的要求如下:
  54.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  55.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  56.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  57.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  58. \n\n
  59. 示例如下:\n
  60. ###剧本名:西昆仑
  61. ###故事梗概
  62. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  63. ###剧本亮点
  64. 亮点1:绝境奇药,生死一线
  65. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  66. 亮点2:结拜兄妹,化解尴尬
  67. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  68. 亮点3:纤发夺命,情愫暗涌
  69. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  70. ###人物关系
  71. 阿雪与梁萧之间存在兄妹之情。
  72. ###核心矛盾
  73. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  74. ###主体列表
  75. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  76. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  77. 阴阳球:天地异宝,能化生精气,救人于危难。
  78. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  79. ###美术风格
  80. 基础画风风格词:厚涂古风
  81. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  82. ###场景列表
  83. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  84. ###分集剧本
  85. ##分集01
  86. 第1集: 第一集的标题
  87. 场景描述:地点、时间、场景
  88. 运镜:固定近距离
  89. 出场角色:男主、女主
  90. 台词内容:
  91. 女主: 女主对话
  92. 男主:男主对话
  93. 女主: 女主对话
  94. 男主: 男主对话
  95. ##分集02
  96. 第2集: 第二集的标题
  97. 场景描述:地点、时间、场景
  98. 运镜:固定近距离
  99. 出场角色:男主、女主
  100. 台词内容:
  101. 女主: 女主对话
  102. 男主:男主对话
  103. 女主: 女主对话
  104. 男主: 男主对话"
  105. ];
  106. }
  107. /**
  108. * 通用文生文方法 - 支持多模型流式输出和图片输入
  109. *
  110. * @param array $data 请求参数
  111. * @return \Generator 返回生成器,用于流式输出
  112. */
  113. public function generateText($data) {
  114. // 获取请求参数
  115. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  116. $messages = getProp($data, 'messages', []);
  117. $systemPrompt = getProp($data, 'system_prompt', '');
  118. $prompt = getProp($data, 'prompt', '');
  119. $images = getProp($data, 'images', []); // 支持多张图片
  120. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  121. // 如果没有提供messages,则根据system_prompt、content和images构建
  122. if (empty($messages)) {
  123. $messages = [];
  124. // 添加系统提示词
  125. if (!empty($systemPrompt)) {
  126. $messages[] = [
  127. 'role' => 'system',
  128. 'content' => $systemPrompt
  129. ];
  130. }
  131. // 构建用户消息内容(支持文本+图片)
  132. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  133. $userMessage = [
  134. 'role' => 'user',
  135. 'content' => []
  136. ];
  137. // 添加文本内容
  138. if (!empty($prompt)) {
  139. $userMessage['content'][] = [
  140. 'type' => 'text',
  141. 'text' => $prompt
  142. ];
  143. }
  144. // 处理上传的图片文件
  145. if (!empty($images)) {
  146. if (!is_array($images)) {
  147. $images = [$images];
  148. }
  149. foreach ($images as $image) {
  150. $imageBase64 = $this->processImageToBase64($image);
  151. if ($imageBase64) {
  152. $userMessage['content'][] = [
  153. 'type' => 'image_url',
  154. 'image_url' => [
  155. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  156. ]
  157. ];
  158. }
  159. }
  160. }
  161. // 处理图片URL
  162. if (!empty($imageUrls)) {
  163. if (!is_array($imageUrls)) {
  164. $imageUrls = [$imageUrls];
  165. }
  166. foreach ($imageUrls as $url) {
  167. if (!empty($url)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'image_url',
  170. 'image_url' => [
  171. 'url' => $url
  172. ]
  173. ];
  174. }
  175. }
  176. }
  177. // 如果只有文本内容,简化为字符串格式
  178. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  179. $userMessage['content'] = $userMessage['content'][0]['text'];
  180. }
  181. $messages[] = $userMessage;
  182. }
  183. }
  184. // 验证messages不为空
  185. if (empty($messages)) {
  186. Utils::throwError('20003:请提供有效的对话内容');
  187. }
  188. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  189. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  190. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  191. if ($model === 'deepseek-chat') {
  192. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  193. $model = 'deepseek-v4-flash';
  194. $thinkingMode = 'disabled';
  195. } elseif ($model === 'deepseek-reasoner') {
  196. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  197. $model = 'deepseek-v4-flash';
  198. $thinkingMode = 'enabled';
  199. }
  200. // 构建请求参数
  201. $post_data = [
  202. 'model' => $model,
  203. 'messages' => $messages,
  204. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  205. 'temperature' => getProp($data, 'temperature', 1),
  206. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  207. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  208. 'thinking' => ['type' => $thinkingMode],
  209. 'stream' => true // 启用流式输出
  210. ];
  211. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  212. // 添加可选参数
  213. if (isset($data['top_p'])) {
  214. $post_data['top_p'] = $data['top_p'];
  215. }
  216. if (isset($data['response_format'])) {
  217. $post_data['response_format'] = $data['response_format'];
  218. }
  219. // 根据模型类型选择调用方法
  220. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  221. // DeepSeek 官方模型使用 DeepSeek API
  222. return $this->deepSeekStreamResponse($post_data);
  223. } else if (in_array($model, $this->gpt_text_models)) {
  224. // GPT 模型使用 TokenRouter API
  225. return $this->gpt54StreamResponse($post_data);
  226. } else if (in_array($model, $this->valid_text_models)) {
  227. // 火山引擎支持的模型使用火山引擎 API
  228. return $this->volcEngineChatCompletion($post_data);
  229. } else {
  230. Utils::throwError('20003:不支持的模型: ' . $model);
  231. }
  232. }
  233. public function createGenerateText($data) {
  234. $file = getProp($data, 'file');
  235. $uid = Site::getUid();
  236. $cpid = Site::getCpid();
  237. if (!$file) {
  238. Utils::throwError('20003:请上传文件');
  239. }
  240. // 提取文件内容
  241. $content = $this->extractFileContent($file);
  242. if (!$content) {
  243. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  244. }
  245. // 获取原始文件名(不含扩展名)作为script_name
  246. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  247. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  248. // 字节安全剥离,不依赖服务器locale设置
  249. $originalName = $file->getClientOriginalName();
  250. $extension = $file->getClientOriginalExtension();
  251. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  252. ? substr($originalName, 0, -strlen($extension) - 1)
  253. : $originalName;
  254. if ($script_name === '') {
  255. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  256. }
  257. // 如果同一用户的剧本名存在则提示
  258. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  259. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  260. }
  261. // 插入数据到mp_scripts表
  262. $script_id = DB::table('mp_scripts')->insertGetId([
  263. 'script_name' => $script_name,
  264. 'user_id' => $uid,
  265. 'cpid' => $cpid,
  266. 'content' => $content,
  267. 'created_at' => date('Y-m-d H:i:s'),
  268. 'updated_at' => date('Y-m-d H:i:s')
  269. ]);
  270. return [
  271. 'script_id' => $script_id,
  272. 'script_name' => $script_name
  273. ];
  274. }
  275. /**
  276. * AI对话调用成功后的积分扣费(返回结果前调用)
  277. *
  278. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  279. *
  280. * @param int $uid
  281. * @param int $tokens
  282. * @param array $chargeInfo
  283. * @return void
  284. */
  285. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  286. {
  287. $result = $this->pointsService->recordChatCharge(
  288. $uid,
  289. PointsService::CHAT_CHARGE_POINTS,
  290. $tokens,
  291. $chargeInfo
  292. );
  293. if (empty($result['charged'])) {
  294. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  295. }
  296. }
  297. /**
  298. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  299. *
  300. * @param array $data 请求参数
  301. * @return array 返回结果数组
  302. */
  303. public function newGenerateText($data) {
  304. // 获取请求参数
  305. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  306. $messages = getProp($data, 'messages', []);
  307. $systemPrompt = getProp($data, 'system_prompt', '');
  308. $prompt = getProp($data, 'prompt', '');
  309. $images = getProp($data, 'images', []); // 支持多张图片
  310. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  311. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  312. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  313. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  314. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  315. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  316. $generateTaskId = 0;
  317. $uid = Site::getUid();
  318. if ($script_id > 0) {
  319. $existingTask = DB::table('mp_script_generate_tasks')
  320. ->where('uid', $uid)
  321. ->where('script_id', $script_id)
  322. ->orderByDesc('id')
  323. ->first();
  324. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  325. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  326. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  327. }
  328. }
  329. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  330. $originalContent = '';
  331. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  332. if ($script_id > 0) {
  333. $script = DB::table('mp_scripts')
  334. ->where('id', $script_id)
  335. ->where('is_deleted', 0)
  336. ->first();
  337. if (!$script) {
  338. Utils::throwError('20003:剧本不存在或已删除');
  339. }
  340. $originalContent = $script->content ?? '';
  341. if (empty($originalContent)) {
  342. Utils::throwError('20003:剧本内容为空');
  343. }
  344. $hasValidScript = true;
  345. // 将剧本内容添加到提示词前面
  346. if (!empty($originalContent)) {
  347. if (!empty($prompt)) {
  348. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  349. } else {
  350. $prompt = "原文内容:\n" . $originalContent;
  351. }
  352. }
  353. }
  354. // 新增: 如果提供了template_id,从数据库获取template_prompt
  355. if ($templateId > 0) {
  356. $template = DB::table('mp_prompt_templates')
  357. ->where('id', $templateId)
  358. ->where('is_deleted', 0)
  359. ->first();
  360. if (!$template) {
  361. Utils::throwError('20003:模板不存在或已删除');
  362. }
  363. $templatePrompt = $template->template_prompt ?? '';
  364. // 将模板提示词和用户输入的prompt组合
  365. // 模板为准,用户输入作为补充要求
  366. if (!empty($templatePrompt)) {
  367. if (!empty($prompt)) {
  368. $prompt = $templatePrompt . "\n\n" . $prompt;
  369. } else {
  370. $prompt = $templatePrompt;
  371. }
  372. }
  373. }
  374. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  375. if (empty($messages)) {
  376. $messages = [];
  377. // 添加系统提示词
  378. if (!empty($systemPrompt)) {
  379. $messages[] = [
  380. 'role' => 'system',
  381. 'content' => $systemPrompt
  382. ];
  383. }
  384. // 构建用户消息内容(支持文本+图片)
  385. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  386. $userMessage = [
  387. 'role' => 'user',
  388. 'content' => []
  389. ];
  390. // 添加文本内容
  391. if (!empty($prompt)) {
  392. $userMessage['content'][] = [
  393. 'type' => 'text',
  394. 'text' => $prompt
  395. ];
  396. }
  397. // 处理上传的图片文件
  398. if (!empty($images)) {
  399. if (!is_array($images)) {
  400. $images = [$images];
  401. }
  402. foreach ($images as $image) {
  403. $imageBase64 = $this->processImageToBase64($image);
  404. if ($imageBase64) {
  405. $userMessage['content'][] = [
  406. 'type' => 'image_url',
  407. 'image_url' => [
  408. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  409. ]
  410. ];
  411. }
  412. }
  413. }
  414. // 处理图片URL
  415. if (!empty($imageUrls)) {
  416. if (!is_array($imageUrls)) {
  417. $imageUrls = [$imageUrls];
  418. }
  419. foreach ($imageUrls as $url) {
  420. if (!empty($url)) {
  421. $userMessage['content'][] = [
  422. 'type' => 'image_url',
  423. 'image_url' => [
  424. 'url' => $url
  425. ]
  426. ];
  427. }
  428. }
  429. }
  430. // 如果只有文本内容,简化为字符串格式
  431. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  432. $userMessage['content'] = $userMessage['content'][0]['text'];
  433. }
  434. $messages[] = $userMessage;
  435. }
  436. }
  437. // 验证messages不为空
  438. if (empty($messages)) {
  439. Utils::throwError('20003:请提供有效的对话内容');
  440. }
  441. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  442. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  443. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  444. if ($model === 'deepseek-chat') {
  445. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  446. $model = 'deepseek-v4-flash';
  447. $thinkingMode = 'disabled';
  448. } elseif ($model === 'deepseek-reasoner') {
  449. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  450. $model = 'deepseek-v4-flash';
  451. $thinkingMode = 'enabled';
  452. }
  453. // 构建请求参数(非流式)
  454. $post_data = [
  455. 'model' => $model,
  456. 'messages' => $messages,
  457. 'temperature' => getProp($data, 'temperature', 1),
  458. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  459. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  460. 'thinking' => ['type' => $thinkingMode],
  461. 'stream' => false // 非流式输出
  462. ];
  463. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  464. // 添加可选参数
  465. if (isset($data['top_p'])) {
  466. $post_data['top_p'] = $data['top_p'];
  467. }
  468. // 新增: 根据response_format设置响应格式
  469. if ($responseFormat === 'json') {
  470. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  471. $hasJsonKeyword = false;
  472. foreach ($post_data['messages'] as $message) {
  473. if (isset($message['content'])) {
  474. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  475. if (stripos($content, 'json') !== false) {
  476. $hasJsonKeyword = true;
  477. break;
  478. }
  479. }
  480. }
  481. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  482. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  483. if (!$hasJsonKeyword) {
  484. $lastMessageIndex = count($post_data['messages']) - 1;
  485. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  486. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  487. // 如果content是字符串,直接追加
  488. if (is_string($lastContent)) {
  489. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  490. }
  491. // 如果content是数组(包含文本和图片),在文本部分追加
  492. else if (is_array($lastContent)) {
  493. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  494. if ($contentPart['type'] === 'text') {
  495. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  496. break;
  497. }
  498. }
  499. }
  500. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  501. }
  502. }
  503. // 设置response_format参数(所有支持的模型)
  504. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  505. // DeepSeek模型
  506. $post_data['response_format'] = ['type' => 'json_object'];
  507. } else if (in_array($model, $this->gpt_text_models)) {
  508. // GPT模型
  509. $post_data['response_format'] = ['type' => 'json_object'];
  510. } else if (in_array($model, $this->valid_text_models)) {
  511. // 火山引擎模型
  512. $post_data['response_format'] = ['type' => 'json_object'];
  513. }
  514. }
  515. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  516. if ($script_id > 0) {
  517. $uid = Site::getUid();
  518. // 创建新的生成任务
  519. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  520. 'uid' => $uid,
  521. 'script_id' => $script_id,
  522. 'sequence' => $sequence,
  523. 'status' => 'processing',
  524. 'prompt' => getProp($data, 'prompt', ''),
  525. 'started_at' => date('Y-m-d H:i:s'),
  526. 'created_at' => date('Y-m-d H:i:s'),
  527. 'updated_at' => date('Y-m-d H:i:s')
  528. ]);
  529. }
  530. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  531. if ($hasValidScript) {
  532. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  533. }
  534. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  535. try {
  536. $aiResult = null;
  537. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  538. // DeepSeek 官方模型使用现有的 chatOnly 方法
  539. $result = $this->chatOnly($post_data);
  540. // 记录实际使用的模型
  541. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  542. $aiResult = [
  543. 'content' => $result['fullContent'],
  544. 'reasoning_content' => $result['fullReasoningContent'],
  545. 'usage' => $result['usage'],
  546. 'model' => $model,
  547. 'finish_reason' => 'stop'
  548. ];
  549. } else if (in_array($model, $this->gpt_text_models)) {
  550. // GPT 模型使用现有的 gpt54ChatOnly 方法
  551. $result = $this->gpt54ChatOnly($post_data);
  552. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  553. $aiResult = [
  554. 'content' => $result['fullContent'],
  555. 'reasoning_content' => '',
  556. 'usage' => $result['usage'],
  557. 'model' => $model,
  558. 'finish_reason' => 'stop'
  559. ];
  560. } else if (in_array($model, $this->valid_text_models)) {
  561. // 火山引擎支持的模型使用火山引擎 API(非流式)
  562. $post_data['stream'] = false;
  563. $result = $this->volcEngineChatCompletion($post_data);
  564. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  565. 'requested_model' => $model,
  566. 'result_keys' => array_keys($result),
  567. 'has_fullContent' => isset($result['fullContent']),
  568. 'has_content' => isset($result['content'])
  569. ]);
  570. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  571. $aiResult = [
  572. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  573. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  574. 'usage' => $result['usage'] ?? [],
  575. 'model' => $model,
  576. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  577. ];
  578. } else {
  579. Utils::throwError('20003:不支持的模型: ' . $model);
  580. }
  581. } catch (\Exception $e) {
  582. // 生成失败,更新任务状态
  583. if ($generateTaskId) {
  584. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  585. 'status' => 'failed',
  586. 'error_message' => $e->getMessage(),
  587. 'completed_at' => date('Y-m-d H:i:s'),
  588. 'updated_at' => date('Y-m-d H:i:s')
  589. ]);
  590. }
  591. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  592. }
  593. // 生成成功,更新任务状态
  594. if ($generateTaskId && $aiResult) {
  595. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  596. 'status' => 'success',
  597. 'result' => getProp($aiResult, 'content', ''),
  598. 'completed_at' => date('Y-m-d H:i:s'),
  599. 'updated_at' => date('Y-m-d H:i:s')
  600. ]);
  601. $aiResult['generate_task_id'] = $generateTaskId;
  602. }
  603. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  604. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  605. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  606. 'model' => $model,
  607. 'script_id' => $script_id,
  608. 'sequence' => $sequence,
  609. 'source' => 'newGenerateText',
  610. ]);
  611. }
  612. // 新增: 如果提供了script_id,保存对话记录
  613. if ($script_id > 0 && $aiResult) {
  614. try {
  615. $uid = Site::getUid();
  616. $now = now();
  617. // 获取用户原始的prompt(不包含剧本内容)
  618. $originalPrompt = getProp($data, 'prompt', '');
  619. $recordsToInsert = [
  620. [
  621. 'uid' => $uid,
  622. 'script_id' => $script_id,
  623. 'sequence' => $sequence,
  624. 'role' => 'user',
  625. 'content' => $originalPrompt,
  626. 'created_at' => $now,
  627. 'updated_at' => $now,
  628. ],
  629. [
  630. 'uid' => $uid,
  631. 'script_id' => $script_id,
  632. 'sequence' => $sequence,
  633. 'role' => 'assistant',
  634. 'content' => $aiResult['content'],
  635. 'created_at' => $now,
  636. 'updated_at' => $now,
  637. ]
  638. ];
  639. DB::table('mp_script_records')->insert($recordsToInsert);
  640. // 获取刚插入的记录ID(假设按插入顺序返回)
  641. $insertedRecords = DB::table('mp_script_records')
  642. ->where('uid', $uid)
  643. ->where('script_id', $script_id)
  644. ->where('sequence', $sequence)
  645. ->orderBy('id', 'desc')
  646. ->limit(2)
  647. ->get()
  648. ->map(function ($record) {
  649. return [
  650. 'rid' => $record->id,
  651. 'script_id' => $record->script_id,
  652. 'sequence' => $record->sequence,
  653. 'role' => $record->role,
  654. 'content' => $record->content,
  655. 'created_at' => $record->created_at,
  656. ];
  657. })
  658. ->reverse()
  659. ->values()
  660. ->toArray();
  661. // 将记录信息添加到返回结果中
  662. $aiResult['records'] = $insertedRecords;
  663. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  664. } catch (\Exception $e) {
  665. // 记录错误但不影响主流程
  666. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  667. }
  668. }
  669. return $aiResult;
  670. }
  671. /**
  672. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  673. *
  674. * @param array $data
  675. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  676. */
  677. public function getScriptGenerateTasks($data) {
  678. $uid = Site::getUid();
  679. return DB::table('mp_script_generate_tasks as t')
  680. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  681. ->where('t.uid', $uid)
  682. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  683. ->orderByDesc('t.id')
  684. ->paginate(15);
  685. }
  686. public function saveScriptChatHistory($data) {
  687. $uid = Site::getUid();
  688. $rid = getProp($data, 'rid');
  689. $script_id = getProp($data, 'script_id');
  690. $sequence = getProp($data, 'sequence', 0);
  691. $content = getProp($data, 'content');
  692. if (!$rid) {
  693. Utils::throwError('20003:请选择对话记录ID');
  694. }
  695. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  696. if (!$record) {
  697. Utils::throwError('20003:对话记录不存在');
  698. }
  699. if (!$script_id) {
  700. Utils::throwError('20003:请选择剧本');
  701. }
  702. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  703. if (!$script) {
  704. Utils::throwError('20003:剧本不存在');
  705. }
  706. // 批量插入数据
  707. return DB::table('mp_script_records')->where('id', $rid)->update([
  708. 'content' => $content,
  709. 'updated_at' => date('Y-m-d H:i:s')
  710. ]);
  711. }
  712. /**
  713. * 获取剧本的历史对话记录
  714. *
  715. * @param array $data 请求参数
  716. * @return array 返回历史记录数组
  717. */
  718. public function getScriptChatHistory($data) {
  719. $uid = Site::getUid();
  720. $script_id = getProp($data, 'script_id');
  721. $rid = getProp($data, 'rid');
  722. $sequence = getProp($data, 'sequence', null);
  723. if (!$script_id) {
  724. Utils::throwError('20003:请提供剧本ID');
  725. }
  726. // 验证剧本是否存在
  727. $script = DB::table('mp_scripts')
  728. ->where('id', $script_id)
  729. ->where('is_deleted', 0)
  730. ->first();
  731. if (!$script) {
  732. Utils::throwError('20003:剧本不存在');
  733. }
  734. // 构建查询
  735. $query = DB::table('mp_script_records')
  736. ->where('script_id', $script_id);
  737. // ->where('uid', $uid);
  738. // 如果提供了 sequence,则过滤指定剧集
  739. if ($sequence !== null) {
  740. $query->where('sequence', $sequence);
  741. }
  742. // 记录ID筛选
  743. if ($rid) {
  744. $query->where('id', $rid);
  745. }
  746. // 查询记录并按 id 正序排序
  747. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  748. ->orderBy('created_at', 'asc')
  749. ->orderBy('id', 'asc')
  750. ->get()
  751. ->map(function ($record) {
  752. return [
  753. 'rid' => $record->id,
  754. 'script_id' => $record->script_id,
  755. 'sequence' => $record->sequence,
  756. 'role' => $record->role,
  757. 'content' => $record->content,
  758. 'products' => $record->products ? json_decode($record->products) : [],
  759. 'created_at' => $record->created_at,
  760. ];
  761. })
  762. ->toArray();
  763. return $records;
  764. }
  765. /**
  766. * 处理图片转换为base64
  767. *
  768. * @param mixed $image 图片文件对象或文件路径
  769. * @return string|null base64编码的图片数据
  770. */
  771. private function processImageToBase64($image) {
  772. try {
  773. // 获取文件路径
  774. if (is_string($image)) {
  775. $filePath = $image;
  776. } else {
  777. // Laravel UploadedFile 对象
  778. $filePath = $image->getRealPath();
  779. }
  780. if (!file_exists($filePath)) {
  781. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  782. return null;
  783. }
  784. // 验证是否为图片文件
  785. $imageInfo = @getimagesize($filePath);
  786. if ($imageInfo === false) {
  787. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  788. return null;
  789. }
  790. // 读取图片并转换为base64
  791. $imageData = file_get_contents($filePath);
  792. $base64Image = base64_encode($imageData);
  793. dLog('deepseek')->info('图片转换成功', [
  794. 'size' => strlen($imageData),
  795. 'type' => $imageInfo['mime']
  796. ]);
  797. return $base64Image;
  798. } catch (\Exception $e) {
  799. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  800. return null;
  801. }
  802. }
  803. private function getArtStylePromptMappings($art_style='')
  804. {
  805. $arr = [
  806. '唯美真人风格' => [
  807. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  808. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  809. ],
  810. '真人古风风格' => [
  811. 'aliases' => ['真人古风风格', '真人古风'],
  812. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  813. ],
  814. '日系动漫风格' => [
  815. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  816. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  817. ],
  818. '国漫风格' => [
  819. 'aliases' => ['国漫风格', '国漫'],
  820. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  821. ],
  822. 'Q版卡通风格' => [
  823. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  824. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  825. ],
  826. '简约扁平风格' => [
  827. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  828. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  829. ],
  830. '武侠风格' => [
  831. 'aliases' => ['武侠风格', '武侠'],
  832. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  833. ],
  834. '古风仙侠风格' => [
  835. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  836. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  837. ],
  838. '新中式水墨风格' => [
  839. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  840. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  841. ],
  842. '写实插画风格' => [
  843. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  844. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  845. ],
  846. '3D卡通风格' => [
  847. 'aliases' => ['3D卡通风格', '3D卡通'],
  848. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  849. ],
  850. '条漫风格' => [
  851. 'aliases' => ['条漫风格', '条漫'],
  852. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  853. ],
  854. '赛博朋克风格' => [
  855. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  856. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  857. ],
  858. '暗黑悬疑风格' => [
  859. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  860. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  861. ],
  862. '治愈清新风格' => [
  863. 'aliases' => ['治愈清新风格', '治愈清新'],
  864. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  865. ],
  866. '3D真人风格' => [
  867. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  868. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  869. ],
  870. ];
  871. if($art_style) {
  872. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  873. }
  874. return $arr;
  875. $arr = [
  876. '唯美真人风格' => [
  877. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  878. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  879. 2. 色彩色调
  880. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  881. 3. 画质精度
  882. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  883. 4. 画面观感
  884. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  885. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  886. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  887. ],
  888. '真人古风风格' => [
  889. 'aliases' => ['真人古风风格', '真人古风'],
  890. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  891. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  892. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  893. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  894. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  895. ],
  896. '日系动漫风格' => [
  897. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  898. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  899. 正向提示词(中文)
  900. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  901. 必须遵守规则
  902. • 全程保持日系动漫风格,不混入其他画风
  903. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  904. • 画面适配所选画面比例,构图居中,主体突出
  905. • 线条干净、色彩统一,不杂乱、不突兀
  906. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  907. ],
  908. '国漫风格' => [
  909. 'aliases' => ['国漫风格', '国漫'],
  910. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  911. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  912. 必须遵守规则
  913. • 严格保持国漫画风,不串风格、不混画风
  914. • 角色形象统一,不随意改变五官、身材、服饰
  915. • 画面构图稳定,适合漫剧叙事展示
  916. • 色调统一,不出现脏色、杂色
  917. 禁止/避免词汇
  918. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  919. ],
  920. 'Q版卡通风格' => [
  921. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  922. 'prompt' => "风格说明
  923. 头大身小,造型可爱圆润,简约干净
  924. 正向提示词(中文)
  925. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  926. 必须遵守规则
  927. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  928. • 角色造型统一,表情可爱,不诡异
  929. • 画面简洁清爽,无多余复杂元素
  930. • 色彩明亮柔和,不刺眼
  931. 禁止/避免词汇
  932. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  933. ],
  934. '简约扁平风格' => [
  935. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  936. 'prompt' => "风格说明
  937. 色块简洁、无复杂渐变,现代极简风
  938. 正向提示词(中文)
  939. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  940. 必须遵守规则
  941. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  942. • 构图简洁,主体突出,无多余装饰
  943. • 色彩统一、干净,不杂乱
  944. 禁止/避免词汇
  945. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  946. ],
  947. '武侠风格' => [
  948. 'aliases' => ['武侠风格', '武侠'],
  949. 'prompt' => "风格说明
  950. 江湖气息,线条硬朗,动作感强
  951. 正向提示词(中文)
  952. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  953. 必须遵守规则
  954. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  955. • 角色形象、服饰、身材比例统一
  956. • 画面动作自然,不扭曲、不畸形
  957. 禁止/避免词汇
  958. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  959. ],
  960. '古风仙侠风格' => [
  961. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  962. 'prompt' => "风格说明
  963. 飘逸汉服、云雾仙气、唯美空灵
  964. 正向提示词(中文)
  965. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  966. 必须遵守规则
  967. • 保持古风仙侠统一画风,不混入现代、科幻元素
  968. • 角色服饰、发型、形象前后一致
  969. • 场景仙气飘逸,色调清雅统一
  970. • 画面唯美柔和,不阴暗、不诡异
  971. 禁止/避免词汇
  972. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  973. ],
  974. '新中式水墨风格' => [
  975. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  976. 'prompt' => "风格说明
  977. 淡墨渲染,毛笔笔触,留白意境
  978. 正向提示词(中文)
  979. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  980. 必须遵守规则
  981. • 严格保持水墨质感,不混入厚涂、写实、卡通
  982. • 色调淡雅统一,不浓艳杂乱
  983. • 画面干净有意境,不堆砌元素
  984. 禁止/避免词汇
  985. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  986. ],
  987. '写实插画风格' => [
  988. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  989. 'prompt' => "风格说明
  990. 接近真人比例,光影真实,质感细腻
  991. 正向提示词(中文)
  992. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  993. 必须遵守规则
  994. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  995. • 角色五官、身材、服饰高度统一
  996. • 画面清晰、光影自然、不扭曲
  997. 禁止/避免词汇
  998. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  999. ],
  1000. '3D卡通风格' => [
  1001. 'aliases' => ['3D卡通风格', '3D卡通'],
  1002. 'prompt' => "风格说明
  1003. 3D建模质感,柔和渲染,圆润可爱
  1004. 正向提示词(中文)
  1005. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1006. 必须遵守规则
  1007. • 保持3D卡通统一质感,不出现2D杂乱线条
  1008. • 角色模型、比例、形象前后一致
  1009. • 画面干净,不模糊、不穿模
  1010. 禁止/避免词汇
  1011. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1012. ],
  1013. '条漫风格' => [
  1014. 'aliases' => ['条漫风格', '条漫'],
  1015. 'prompt' => "风格说明
  1016. 纵向分镜,上下滑动阅读,轻量化
  1017. 正向提示词(中文)
  1018. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1019. 必须遵守规则
  1020. • 保持条漫纵向阅读逻辑,构图简洁
  1021. • 画风统一,不混写实、3D、水墨
  1022. • 画面干净,不杂乱
  1023. 禁止/避免词汇
  1024. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1025. ],
  1026. '赛博朋克风格' => [
  1027. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1028. 'prompt' => "风格说明
  1029. 霓虹灯光、未来都市、暗色调、科技机械
  1030. 正向提示词(中文)
  1031. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1032. 必须遵守规则
  1033. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1034. • 色调以暗调+霓虹为主,色彩统一
  1035. • 画面科技感强,不杂乱
  1036. 禁止/避免词汇
  1037. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1038. ],
  1039. '暗黑悬疑风格' => [
  1040. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1041. 'prompt' => "风格说明
  1042. 低饱和、冷色调、阴影重、神秘压抑
  1043. 正向提示词(中文)
  1044. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1045. 必须遵守规则
  1046. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1047. • 画面氛围压抑神秘,但不低俗、不血腥
  1048. • 角色形象统一,不崩坏
  1049. 禁止/避免词汇
  1050. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1051. ],
  1052. '治愈清新风格' => [
  1053. 'aliases' => ['治愈清新风格', '治愈清新'],
  1054. 'prompt' => "风格说明
  1055. 马卡龙色系、柔光、温暖干净
  1056. 正向提示词(中文)
  1057. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1058. 必须遵守规则
  1059. • 保持治愈清新统一色调,不阴暗、不诡异
  1060. • 画面柔和干净,无杂乱元素
  1061. • 角色形象柔和可爱,不狰狞
  1062. 禁止/避免词汇
  1063. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1064. ],
  1065. ];
  1066. return $arr;
  1067. }
  1068. public function getArtStylePromptByInput($inputArtStyle): string
  1069. {
  1070. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1071. if ($normalizedInput === '') {
  1072. return '';
  1073. }
  1074. return $this->getArtStylePromptMappings($normalizedInput);
  1075. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1076. // foreach ($mapping['aliases'] as $alias) {
  1077. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1078. // if ($normalizedAlias === '') {
  1079. // continue;
  1080. // }
  1081. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1082. // return $mapping['prompt'];
  1083. // }
  1084. // }
  1085. // }
  1086. return '';
  1087. }
  1088. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1089. $stylePrefixes = [
  1090. '唯美真人风格' => [
  1091. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1092. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1093. ],
  1094. '真人古风风格' => [
  1095. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1096. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1097. ],
  1098. '日系动漫风格' => [
  1099. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1100. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1101. ],
  1102. '国漫风格' => [
  1103. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1104. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1105. ],
  1106. 'Q版卡通风格' => [
  1107. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1108. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1109. ],
  1110. '简约扁平风格' => [
  1111. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1112. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1113. ],
  1114. '武侠风格' => [
  1115. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1116. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1117. ],
  1118. '古风仙侠风格' => [
  1119. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1120. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1121. ],
  1122. '新中式水墨风格' => [
  1123. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1124. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1125. ],
  1126. '写实插画风格' => [
  1127. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1128. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1129. ],
  1130. '3D卡通风格' => [
  1131. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1132. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1133. ],
  1134. '条漫风格' => [
  1135. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1136. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1137. ],
  1138. '赛博朋克风格' => [
  1139. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1140. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1141. ],
  1142. '暗黑悬疑风格' => [
  1143. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1144. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1145. ],
  1146. '治愈清新风格' => [
  1147. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1148. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1149. ]
  1150. ];
  1151. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1152. }
  1153. private function normalizeArtStyleInput($value): string
  1154. {
  1155. $value = trim((string)$value);
  1156. if ($value === '') {
  1157. return '';
  1158. }
  1159. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1160. return mb_strtolower($value, 'UTF-8');
  1161. }
  1162. private function replaceArtStyleSection(string $content, string $artStyle): string
  1163. {
  1164. if ($content === '' || $artStyle === '') {
  1165. return $content;
  1166. }
  1167. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1168. if (!preg_match($pattern, $content)) {
  1169. return $content;
  1170. }
  1171. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1172. }
  1173. /**
  1174. * DeepSeek流式输出处理方法
  1175. *
  1176. * @param array $post_data DeepSeek API请求参数
  1177. * @return \Generator 返回生成器,用于流式输出
  1178. */
  1179. private function deepSeekStreamResponse($post_data) {
  1180. // 设置最大输出tokens
  1181. $post_data['max_tokens'] = 300000;
  1182. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1183. $post_data['stream_options'] = ['include_usage' => true];
  1184. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1185. $response = $client->post($this->url, [
  1186. 'json' => $post_data,
  1187. 'headers' => $this->headers,
  1188. 'stream' => true // 启用流式响应
  1189. ]);
  1190. $body = $response->getBody();
  1191. $fullContent = '';
  1192. $fullReasoningContent = '';
  1193. $usage = [];
  1194. $buffer = '';
  1195. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1196. // 逐行读取流式响应
  1197. while (!$body->eof()) {
  1198. $chunk = $body->read(1024); // 每次读取 1KB
  1199. $buffer .= $chunk;
  1200. // 按行分割
  1201. $lines = explode("\n", $buffer);
  1202. // 保留最后一个不完整的行
  1203. $buffer = array_pop($lines);
  1204. foreach ($lines as $line) {
  1205. $line = trim($line);
  1206. // 跳过空行
  1207. if (empty($line)) {
  1208. continue;
  1209. }
  1210. // 检查是否是 SSE 数据行
  1211. if (strpos($line, 'data: ') !== 0) {
  1212. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1213. continue;
  1214. }
  1215. $data = substr($line, 6); // 移除 "data: " 前缀
  1216. if ($data === '[DONE]') {
  1217. dLog('deepseek')->info('收到结束标记');
  1218. break 2; // 跳出两层循环
  1219. }
  1220. try {
  1221. $json = json_decode($data, true);
  1222. if (json_last_error() !== JSON_ERROR_NONE) {
  1223. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1224. continue;
  1225. }
  1226. if (isset($json['choices'][0]['delta'])) {
  1227. $delta = $json['choices'][0]['delta'];
  1228. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1229. if (isset($delta['reasoning_content'])) {
  1230. $fullReasoningContent .= $delta['reasoning_content'];
  1231. yield [
  1232. 'type' => 'reasoning',
  1233. 'content' => $delta['reasoning_content'],
  1234. 'full_reasoning' => $fullReasoningContent
  1235. ];
  1236. }
  1237. // 处理最终回答内容
  1238. if (isset($delta['content'])) {
  1239. $fullContent .= $delta['content'];
  1240. yield [
  1241. 'type' => 'content',
  1242. 'content' => $delta['content'],
  1243. ];
  1244. }
  1245. }
  1246. // 获取使用统计信息
  1247. if (isset($json['usage'])) {
  1248. $usage = $json['usage'];
  1249. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1250. }
  1251. } catch (\Exception $e) {
  1252. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1253. continue;
  1254. }
  1255. }
  1256. }
  1257. dLog('deepseek')->info('流式读取完成', [
  1258. 'content_length' => strlen($fullContent),
  1259. 'reasoning_length' => strlen($fullReasoningContent)
  1260. ]);
  1261. yield [
  1262. 'type' => 'done',
  1263. 'full_content' => $fullContent,
  1264. 'full_reasoning' => $fullReasoningContent,
  1265. 'usage' => $usage
  1266. ];
  1267. }
  1268. /**
  1269. * GPT 重试次数(env 可配置,默认 5 次)
  1270. */
  1271. private function gptRetryTimes()
  1272. {
  1273. return (int)env('GPT_RETRY_TIMES', 5);
  1274. }
  1275. /**
  1276. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1277. */
  1278. private function gptRetryInterval()
  1279. {
  1280. return (int)env('GPT_RETRY_INTERVAL', 10);
  1281. }
  1282. /**
  1283. * 判断 GPT 请求异常是否可重试
  1284. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1285. */
  1286. private function isGptRetryableException(\Exception $e)
  1287. {
  1288. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1289. return false;
  1290. }
  1291. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1292. $status = $e->getResponse()->getStatusCode();
  1293. return $status >= 500 || $status == 429;
  1294. }
  1295. return true;
  1296. }
  1297. /**
  1298. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1299. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1300. */
  1301. private function checkGptServiceAvailable()
  1302. {
  1303. $apiKey = env('GPT_54_API_KEY');
  1304. if (empty($apiKey)) {
  1305. return false;
  1306. }
  1307. try {
  1308. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  1309. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  1310. 'headers' => [
  1311. 'Authorization' => 'Bearer ' . $apiKey,
  1312. 'Content-Type' => 'application/json'
  1313. ]
  1314. ]);
  1315. $status = $response->getStatusCode();
  1316. return $status < 500 && $status != 429;
  1317. } catch (\Exception $e) {
  1318. return false;
  1319. }
  1320. }
  1321. /**
  1322. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  1323. * 全部失败抛出友好错误
  1324. */
  1325. private function ensureGptServiceAvailable()
  1326. {
  1327. $maxRetries = $this->gptRetryTimes();
  1328. $interval = $this->gptRetryInterval();
  1329. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  1330. if ($this->checkGptServiceAvailable()) {
  1331. return;
  1332. }
  1333. if ($attempt < $maxRetries) {
  1334. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  1335. 'retry' => $attempt + 1,
  1336. 'max_retries' => $maxRetries
  1337. ]);
  1338. sleep($interval);
  1339. }
  1340. }
  1341. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  1342. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  1343. 'max_retries' => $maxRetries,
  1344. 'interval' => $interval
  1345. ]);
  1346. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  1347. }
  1348. /**
  1349. * GPT 流式输出处理方法
  1350. *
  1351. * @param array $post_data GPT API请求参数
  1352. * @return \Generator 返回生成器,用于流式输出
  1353. */
  1354. private function gpt54StreamResponse($post_data) {
  1355. $apiKey = env('GPT_54_API_KEY');
  1356. if (empty($apiKey)) {
  1357. Utils::throwError('20003:GPT API Key未配置');
  1358. }
  1359. // 先探活,服务不可用时自动重试
  1360. $this->ensureGptServiceAvailable();
  1361. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1362. $headers = [
  1363. 'Authorization' => 'Bearer ' . $apiKey,
  1364. 'Content-Type' => 'application/json'
  1365. ];
  1366. // 移除 thinking 参数,GPT-5.4 不支持
  1367. if (isset($post_data['thinking'])) {
  1368. unset($post_data['thinking']);
  1369. }
  1370. if (isset($post_data['reasoning_effort'])) {
  1371. unset($post_data['reasoning_effort']);
  1372. }
  1373. $post_data['max_completion_tokens'] = 100000;
  1374. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1375. $post_data['stream_options'] = ['include_usage' => true];
  1376. $maxRetries = $this->gptRetryTimes();
  1377. $interval = $this->gptRetryInterval();
  1378. $attempt = 0;
  1379. while (true) {
  1380. $fullContent = '';
  1381. $usage = [];
  1382. $buffer = '';
  1383. try {
  1384. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1385. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1386. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1387. 'json' => $post_data,
  1388. 'headers' => $headers,
  1389. 'stream' => true // 启用流式响应
  1390. ]);
  1391. $body = $response->getBody();
  1392. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1393. // 逐行读取流式响应
  1394. while (!$body->eof()) {
  1395. $chunk = $body->read(1024); // 每次读取 1KB
  1396. $buffer .= $chunk;
  1397. // 按行分割
  1398. $lines = explode("\n", $buffer);
  1399. // 保留最后一个不完整的行
  1400. $buffer = array_pop($lines);
  1401. foreach ($lines as $line) {
  1402. $line = trim($line);
  1403. // 跳过空行
  1404. if (empty($line)) {
  1405. continue;
  1406. }
  1407. // 检查是否是 SSE 数据行
  1408. if (strpos($line, 'data: ') !== 0) {
  1409. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1410. continue;
  1411. }
  1412. $data = substr($line, 6); // 移除 "data: " 前缀
  1413. if ($data === '[DONE]') {
  1414. dLog('deepseek')->info('收到结束标记');
  1415. break 2; // 跳出 foreach 和流读取循环
  1416. }
  1417. try {
  1418. $json = json_decode($data, true);
  1419. if (json_last_error() !== JSON_ERROR_NONE) {
  1420. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1421. continue;
  1422. }
  1423. if (isset($json['choices'][0]['delta'])) {
  1424. $delta = $json['choices'][0]['delta'];
  1425. // 处理回答内容
  1426. if (isset($delta['content'])) {
  1427. $fullContent .= $delta['content'];
  1428. yield [
  1429. 'type' => 'content',
  1430. 'content' => $delta['content'],
  1431. ];
  1432. }
  1433. }
  1434. // 获取使用统计信息
  1435. if (isset($json['usage'])) {
  1436. $usage = $json['usage'];
  1437. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1438. }
  1439. } catch (\Exception $e) {
  1440. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1441. continue;
  1442. }
  1443. }
  1444. }
  1445. dLog('deepseek')->info('流式读取完成', [
  1446. 'content_length' => strlen($fullContent)
  1447. ]);
  1448. yield [
  1449. 'type' => 'done',
  1450. 'full_content' => $fullContent,
  1451. 'full_reasoning' => '',
  1452. 'usage' => $usage
  1453. ];
  1454. return;
  1455. } catch (\Exception $e) {
  1456. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  1457. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  1458. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  1459. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  1460. throw $e;
  1461. }
  1462. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  1463. 'retry' => $attempt + 1,
  1464. 'max_retries' => $maxRetries,
  1465. 'error' => $e->getMessage()
  1466. ]);
  1467. sleep($interval);
  1468. $attempt++;
  1469. }
  1470. }
  1471. }
  1472. // 与推理模型对话
  1473. public function chatWithReasoner($data) {
  1474. $content = getProp($data, 'content');
  1475. $model = getProp($data, 'model', 'r1');
  1476. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1477. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1478. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1479. if ($model == 'r1') {
  1480. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1481. $thinkingMode = 'disabled';
  1482. } else {
  1483. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1484. $thinkingMode = 'disabled';
  1485. }
  1486. // 获取可选情感(根据音色可支持情感选)
  1487. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1488. $emotion_list = [];
  1489. foreach ($timbre_emotion as $emotion) {
  1490. $tmp = explode(',', $emotion);
  1491. $emotion_list = array_merge($emotion_list, $tmp);
  1492. }
  1493. $emotion_list = array_unique($emotion_list);
  1494. $emotion_str = implode('、', $emotion_list);
  1495. // // 获取可选情感
  1496. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1497. // $emotion_str = implode('、', $emotion_list);
  1498. // 是否启用情感
  1499. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1500. if ($enable_emotion) {
  1501. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1502. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1503. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1504. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1505. }else {
  1506. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1507. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1508. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1509. }
  1510. $messages = [
  1511. [
  1512. 'role' => 'system',
  1513. 'content' => $sys_content
  1514. ],
  1515. [
  1516. 'role' => 'user',
  1517. 'content' => $content
  1518. ]
  1519. ];
  1520. $post_data = [
  1521. 'model' => $model,
  1522. 'messages' => $messages,
  1523. // 'max_tokens' => 8192,
  1524. 'temperature' => 1,
  1525. 'frequency_penalty' => 0,
  1526. 'presence_penalty' => 0,
  1527. 'thinking' => ['type' => $thinkingMode],
  1528. 'response_format' => [
  1529. 'type' => 'text'
  1530. ],
  1531. 'stream' => false
  1532. ];
  1533. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1534. // 根据模型类型选择调用方法
  1535. $fullContent = '';
  1536. $usage = [];
  1537. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1538. // DeepSeek 官方模型使用 DeepSeek API
  1539. $chatResult = $this->chatOnly($post_data);
  1540. } else if (in_array($model, $this->gpt_text_models)) {
  1541. // GPT-5.4 模型使用 TokenRouter API
  1542. $chatResult = $this->gpt54ChatOnly($post_data);
  1543. } else {
  1544. // 其他模型使用火山引擎API
  1545. $chatResult = $this->volcEngineChatCompletion($post_data);
  1546. }
  1547. if (is_array($chatResult)) {
  1548. $fullContent = $chatResult['fullContent'];
  1549. $usage = $chatResult['usage'];
  1550. }
  1551. // 处理获取到的剧本数据
  1552. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1553. $result = [
  1554. 'origin_content' => $fullContent,
  1555. 'roles' => getProp($script_content, 'roles'),
  1556. 'words' => getProp($script_content, 'words'),
  1557. ];
  1558. return $result;
  1559. }
  1560. public function resetParagraphAudio($data) {
  1561. $bid = getProp($data, 'bid');
  1562. $cid = getProp($data, 'cid');
  1563. $version_id = getProp($data, 'version_id');
  1564. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1565. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1566. 'generate_status' => '待制作',
  1567. 'updated_at' => date('Y-m-d H:i:s')
  1568. ]);
  1569. }
  1570. public function saveParagraphAudio($data) {
  1571. $bid = getProp($data, 'bid');
  1572. $cid = getProp($data, 'cid');
  1573. $version_id = getProp($data, 'version_id');
  1574. $sequence = getProp($data, 'sequence');
  1575. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1576. // 获取所有情感
  1577. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1578. $emotion_list = array_flip($emotion_list);
  1579. // 获取音色支持情感
  1580. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1581. $timbre_emotion = explode(',', $timbre_emotion);
  1582. $emotion = getProp($data, 'emotion');
  1583. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1584. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1585. $list = [
  1586. 'bid' => $bid,
  1587. 'cid' => $cid,
  1588. 'version_id' => $version_id,
  1589. 'sequence' => $sequence,
  1590. 'role' => getProp($data, 'role'),
  1591. 'gender' => getProp($data, 'gender'),
  1592. 'text' => trim(getProp($data, 'text')),
  1593. 'emotion' => $emotion,
  1594. 'emotion_type' => $emotion_type,
  1595. 'voice_type' => getProp($data, 'voice_type'),
  1596. 'voice_name' => getProp($data, 'voice_name'),
  1597. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1598. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1599. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1600. 'pitch' => getProp($data, 'pitch', 0),
  1601. // 'paragraph_audio_url' => '',
  1602. 'generate_status' => '制作中',
  1603. 'error_msg' => '',
  1604. 'updated_at' => date('Y-m-d H:i:s')
  1605. ];
  1606. $continue = false;
  1607. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1608. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1609. $list['generate_status'] = '制作成功';
  1610. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1611. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1612. $continue = true;
  1613. }
  1614. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1615. if ($id) {
  1616. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1617. }else {
  1618. $list['created_at'] = date('Y-m-d H:i:s');
  1619. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1620. $boolen = $id ? true : false;
  1621. }
  1622. // 如果更新成功则加入查询队列
  1623. if ($boolen) {
  1624. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1625. Redis::sadd($redis_key, $id);
  1626. }
  1627. if ($boolen && !$continue) {
  1628. $boolen = false;
  1629. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1630. // 根据ID通过API通知合成音频
  1631. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1632. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1633. $response = $result->getBody()->getContents();
  1634. $response_arr = json_decode($response, true);
  1635. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1636. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1637. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1638. Utils::throwError('20003:通知火山生成段落音频失败');
  1639. }
  1640. $boolen = true;
  1641. }
  1642. return $boolen;
  1643. }
  1644. public function insertAudioEffect($data) {
  1645. $audio_id = getProp($data, 'audio_id');
  1646. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1647. $bid = getProp($chapter_audio, 'bid');
  1648. $version_id = getProp($chapter_audio, 'version_id');
  1649. $cid = getProp($chapter_audio, 'cid');
  1650. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1651. $audio_effect_json = getProp($data, 'audio_effect_json');
  1652. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1653. try {
  1654. DB::beginTransaction();
  1655. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1656. if (!$count) {
  1657. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1658. }else {
  1659. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1660. }
  1661. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1662. 'audio_effect_status' => '添加中',
  1663. 'audio_effect_json' => $audio_effect_json,
  1664. 'updated_at' => date('Y-m-d H:i:s')
  1665. ]);
  1666. if (!$boolen1) {
  1667. DB::rollBack();
  1668. Utils::throwError('20003:更新生成数据失败');
  1669. }
  1670. $id = DB::table('mp_audio_tasks')->insertGetId([
  1671. 'audio_id' => $audio_id,
  1672. 'generate_status' => '执行中',
  1673. 'generate_json' => json_encode([], 256),
  1674. 'bid' => $bid,
  1675. 'book_name' => getProp($chapter_audio, 'book_name'),
  1676. 'version_id' => $version_id,
  1677. 'version_name' => getProp($chapter_audio, 'version_name'),
  1678. 'cid' => $cid,
  1679. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1680. 'task_name' => $task_name,
  1681. 'created_at' => date('Y-m-d H:i:s'),
  1682. 'updated_at' => date('Y-m-d H:i:s')
  1683. ]);
  1684. if (!$id) {
  1685. DB::rollBack();
  1686. Utils::throwError('20003:创建任务失败');
  1687. }
  1688. }catch (\Exception $e) {
  1689. DB::rollBack();
  1690. Utils::throwError('20003:'.$e->getMessage());
  1691. }
  1692. DB::commit();
  1693. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1694. // 根据ID通过API通知合成音频
  1695. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1696. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1697. $response = $result->getBody()->getContents();
  1698. $response_arr = json_decode($response, true);
  1699. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1700. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1701. Log::info('通知火山插入音效失败: '.$error_msg);
  1702. Utils::throwError('20003:通知火山插入音效失败');
  1703. }
  1704. return true;
  1705. }
  1706. public function insertBgm($data) {
  1707. $audio_id = getProp($data, 'audio_id');
  1708. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1709. $bid = getProp($chapter_audio, 'bid');
  1710. $version_id = getProp($chapter_audio, 'version_id');
  1711. $cid = getProp($chapter_audio, 'cid');
  1712. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1713. $bgm_json = getProp($data, 'bgm_json');
  1714. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1715. if (!$bgm_json) {
  1716. $bgm_json = getProp($data, 'audio_effect_json');
  1717. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1718. }
  1719. try {
  1720. DB::beginTransaction();
  1721. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1722. if (!$count) {
  1723. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1724. }else {
  1725. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1726. }
  1727. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1728. 'bgm_status' => '添加中',
  1729. 'bgm_json' => $bgm_json,
  1730. 'updated_at' => date('Y-m-d H:i:s')
  1731. ]);
  1732. if (!$boolen1) {
  1733. DB::rollBack();
  1734. Utils::throwError('20003:更新生成数据失败');
  1735. }
  1736. $id = DB::table('mp_audio_tasks')->insertGetId([
  1737. 'audio_id' => $audio_id,
  1738. 'generate_status' => '执行中',
  1739. 'generate_json' => json_encode([], 256),
  1740. 'bid' => $bid,
  1741. 'book_name' => getProp($chapter_audio, 'book_name'),
  1742. 'version_id' => $version_id,
  1743. 'version_name' => getProp($chapter_audio, 'version_name'),
  1744. 'cid' => $cid,
  1745. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1746. 'task_name' => $task_name,
  1747. 'created_at' => date('Y-m-d H:i:s'),
  1748. 'updated_at' => date('Y-m-d H:i:s')
  1749. ]);
  1750. if (!$id) {
  1751. DB::rollBack();
  1752. Utils::throwError('20003:创建任务失败');
  1753. }
  1754. }catch (\Exception $e) {
  1755. DB::rollBack();
  1756. Utils::throwError('20003:'.$e->getMessage());
  1757. }
  1758. DB::commit();
  1759. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1760. // 根据ID通过API通知合成音频
  1761. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1762. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1763. $response = $result->getBody()->getContents();
  1764. $response_arr = json_decode($response, true);
  1765. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1766. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1767. Log::info('通知火山插入bgm失败: '.$error_msg);
  1768. Utils::throwError('20003:通知火山插入bgm失败');
  1769. }
  1770. return true;
  1771. }
  1772. public function getParagraphAudios($data) {
  1773. $bid = getProp($data, 'bid');
  1774. $cid = getProp($data, 'cid');
  1775. $version_id = getProp($data, 'version_id');
  1776. $sequence = getProp($data, 'sequence');
  1777. // 获取已生成的音频
  1778. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1779. if ($sequence) $query->where('sequence', $sequence);
  1780. $paragraph_audios = $query->orderBy('sequence')->get();
  1781. $result = [];
  1782. foreach($paragraph_audios as $item) {
  1783. $result[] = [
  1784. 'sequence' => getProp($item, 'sequence'),
  1785. 'role' => getProp($item, 'role'),
  1786. 'gender' => getProp($item, 'gender'),
  1787. 'text' => trim(getProp($item, 'text')),
  1788. 'emotion' => getProp($item, 'emotion'),
  1789. 'emotion_type' => getProp($item, 'emotion_type'),
  1790. 'voice_type' => getProp($item, 'voice_type'),
  1791. 'voice_name' => getProp($item, 'voice_name'),
  1792. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1793. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1794. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1795. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1796. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1797. ];
  1798. }
  1799. return $result;
  1800. }
  1801. // 新增合成任务
  1802. public function addGenerateTask($data) {
  1803. $bid = getProp($data, 'bid');
  1804. $cid = getProp($data, 'cid');
  1805. $version_id = getProp($data, 'version_id');
  1806. $generate_json = getProp($data, 'generate_json');
  1807. // 获取已生成的音频
  1808. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1809. $paragraph_list = [];
  1810. foreach($paragraph_audios as $item) {
  1811. $paragraph_list[getProp($item, 'sequence')] = [
  1812. 'role' => getProp($item, 'role'),
  1813. 'gender' => getProp($item, 'gender'),
  1814. 'text' => trim(getProp($item, 'text')),
  1815. 'emotion' => getProp($item, 'emotion'),
  1816. 'emotion_type' => getProp($item, 'emotion_type'),
  1817. 'voice_type' => getProp($item, 'voice_type'),
  1818. 'voice_name' => getProp($item, 'voice_name'),
  1819. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1820. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1821. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1822. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1823. ];
  1824. }
  1825. // 更新角色-音色信息
  1826. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1827. $existed_role_info = json_decode($existed_role_info, true);
  1828. if (!$existed_role_info) $existed_role_info = [];
  1829. // 获取情感信息
  1830. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1831. $emotion_list = array_flip($emotion_list);
  1832. // 获取音色对应情感组
  1833. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1834. $timbre_emotion_list = [];
  1835. foreach($timbre_emotions as $item) {
  1836. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1837. }
  1838. // 构造生成音频的json
  1839. $words = json_decode($generate_json, true);
  1840. // 最终合成前的参数组
  1841. $mp_chapter_paragraph_audios = [];
  1842. $sequence = 1;
  1843. $complete_paragraph_sequences = [];
  1844. foreach($words as &$word) {
  1845. 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:参数格式有误');
  1846. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1847. $role = getProp($word, 'role');
  1848. $word['gender'] = (int)$word['gender'];
  1849. // 判断音色对应情感是否支持,不支持则调整为中性
  1850. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1851. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1852. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1853. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1854. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1855. }else {
  1856. $word['emotion'] = '中性';
  1857. $word['emotion_type'] = 'neutral';
  1858. }
  1859. $existed_role_info[$role] = [
  1860. 'timbre_type' => $word['voice_type'],
  1861. 'timbre_name' => $word['voice_name'],
  1862. 'emotion' => $word['emotion'],
  1863. 'emotion_type' => $word['emotion_type'],
  1864. 'speed_ratio' => $word['speed_ratio'],
  1865. 'loudness_ratio'=> $word['loudness_ratio'],
  1866. 'emotion_scale' => $word['emotion_scale'],
  1867. 'pitch' => $word['pitch']
  1868. ];
  1869. $word['paragraph_audio_url'] = '';
  1870. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1871. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1872. // 如果音频存在并且参数都未改变则使用已生成的音频
  1873. if (getProp($paragraph, 'paragraph_audio_url')) {
  1874. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1875. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1876. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1877. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1878. // {
  1879. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1880. // }
  1881. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1882. }
  1883. $tmp = $word;
  1884. // 组装章节分句音频数据
  1885. // $tmp['sequence'] = getProp($word, 'sequence');
  1886. // $tmp['text'] = getProp($word, 'text');
  1887. // $tmp['emotion'] = getProp($word, 'emotion');
  1888. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1889. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1890. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1891. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1892. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1893. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1894. $tmp['bid'] = $bid;
  1895. $tmp['version_id'] = $version_id;
  1896. $tmp['cid'] = $cid;
  1897. $tmp['sequence'] = $sequence;
  1898. $tmp['created_at'] = date('Y-m-d H:i:s');
  1899. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1900. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1901. $mp_chapter_paragraph_audios[] = $tmp;
  1902. $complete_paragraph_sequences[] = $sequence;
  1903. $sequence++;
  1904. }
  1905. $generate_json = json_encode($words, 256);
  1906. // 判断是否有未生成字幕的段落
  1907. $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();
  1908. if ($no_subtitle_sequences) {
  1909. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1910. }
  1911. try {
  1912. DB::beginTransaction();
  1913. $role_info = json_encode($existed_role_info, 256);
  1914. $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')]);
  1915. if (!$boolen) {
  1916. DB::rollBack();
  1917. Utils::throwError('20003:更新角色信息失败');
  1918. }
  1919. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1920. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1921. if (!$count) {
  1922. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1923. }else {
  1924. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1925. }
  1926. $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')]);
  1927. if (!$boolen1) {
  1928. DB::rollBack();
  1929. Utils::throwError('20003:更新生成数据失败');
  1930. }
  1931. $id = DB::table('mp_audio_tasks')->insertGetId([
  1932. 'audio_id' => getProp($chapter_audio, 'id'),
  1933. 'generate_status' => '执行中',
  1934. 'generate_json' => $generate_json,
  1935. 'bid' => $bid,
  1936. 'book_name' => getProp($chapter_audio, 'book_name'),
  1937. 'version_id' => $version_id,
  1938. 'version_name' => getProp($chapter_audio, 'version_name'),
  1939. 'cid' => $cid,
  1940. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1941. 'task_name' => $task_name,
  1942. 'created_at' => date('Y-m-d H:i:s'),
  1943. 'updated_at' => date('Y-m-d H:i:s')
  1944. ]);
  1945. if (!$id) {
  1946. DB::rollBack();
  1947. Utils::throwError('20003:创建任务失败');
  1948. }
  1949. // 删除不在段落序号范围内的其他数据
  1950. if ($complete_paragraph_sequences) {
  1951. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1952. }
  1953. // // 删除章节分句音频数据并重新插入
  1954. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1955. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1956. // if (!$boolen3) {
  1957. // DB::rollBack();
  1958. // Utils::throwError('20003:更新章节分句音频失败');
  1959. // }
  1960. } catch (\Exception $e) {
  1961. DB::rollBack();
  1962. Utils::throwError('20003:'.$e->getMessage());
  1963. }
  1964. DB::commit();
  1965. // 通知火山生成音频
  1966. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1967. // 根据ID通过API通知合成音频
  1968. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1969. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1970. $response = $result->getBody()->getContents();
  1971. $response_arr = json_decode($response, true);
  1972. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1973. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1974. Log::info('通知火山生成音频失败: '.$error_msg);
  1975. Utils::throwError('20003:通知火山生成音频失败');
  1976. }
  1977. return true;
  1978. }
  1979. public function timbreList($data) {
  1980. $gender = getProp($data, 'gender');
  1981. $timbre_name = getProp($data, 'voice_name');
  1982. $category_id = getProp($data, 'category_id');
  1983. $age_stage = getProp($data, 'age_stage');
  1984. $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');
  1985. if ($gender) {
  1986. $query->where('gender', $gender);
  1987. }
  1988. if ($timbre_name) {
  1989. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1990. }
  1991. if ($category_id) {
  1992. $query->where(function ($query) use ($category_id) {
  1993. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1994. });
  1995. }
  1996. if ($age_stage) {
  1997. $query->where('age_stage', $age_stage);
  1998. }
  1999. $list = $query->get()->map(function ($value) {
  2000. $value = (array)$value;
  2001. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2002. return $value;
  2003. })->toArray();
  2004. return $list;
  2005. }
  2006. // 生成火山临时token
  2007. public function setStsToken() {
  2008. // ************* 配置参数 *************
  2009. $method = 'GET';
  2010. $service = 'sts';
  2011. $host = 'open.volcengineapi.com';
  2012. $region = env('VOLC_REGION');
  2013. $endpoint = 'https://open.volcengineapi.com';
  2014. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2015. $access_key = env('VOLC_AK');
  2016. $secret_key = env('VOLC_SK');
  2017. // 获取缓存中的token,如果没有则请求接口
  2018. $token = Redis::get('volc_sts_token');
  2019. if (!$token) {
  2020. // 查询参数
  2021. $query_parameters = [
  2022. 'Action' => 'AssumeRole',
  2023. 'RoleSessionName' => 'user@zw',
  2024. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2025. 'Version' => '2018-01-01'
  2026. ];
  2027. // 生成URL编码的查询字符串
  2028. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2029. // 获取签名头信息
  2030. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2031. // 构建完整URL
  2032. $request_url = $endpoint . '?' . $request_parameters;
  2033. $client = new Client(['verify' => false]);
  2034. $response = $client->get($request_url, ['headers' => $headers]);
  2035. $response_arr = json_decode($response->getBody()->getContents(), true);
  2036. $result = [
  2037. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2038. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2039. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2040. 'Region' => env('VOLC_REGION'),
  2041. 'Endpoint' => env('VOLC_END_POINT'),
  2042. 'Bucket' => env('VOLC_BUCKET'),
  2043. ];
  2044. // 缓存token
  2045. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2046. return $result;
  2047. } else {
  2048. return json_decode($token, true);
  2049. }
  2050. // $response = $response['Response'];
  2051. // $access_key = $response['Credentials']['AccessKeyId'];
  2052. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2053. // $security_token = $response['Credentials']['SecurityToken'];
  2054. // $expiration = $response['Credentials']['Expiration'];
  2055. // dd($response_arr);
  2056. }
  2057. public function emotionGroups($data) {
  2058. $id = getProp($data, 'group_id');
  2059. $group_name = getProp($data, 'group_name');
  2060. $voice_type = getProp($data, 'voice_type');
  2061. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2062. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2063. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2064. if ($group_name) {
  2065. $query->where('group_name', 'like', "%{$group_name}%");
  2066. }
  2067. if ($id) {
  2068. $query->where('id', $id);
  2069. }
  2070. if ($voice_type) {
  2071. $query->where('voice_type', $voice_type);
  2072. }
  2073. return $query->orderBy('id')->get()->map(function ($value) {
  2074. return (array)$value;
  2075. })->toArray();
  2076. }
  2077. private function sign($key, $msg) {
  2078. return hash_hmac('sha256', $msg, $key, true);
  2079. }
  2080. // 生成签名密钥
  2081. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2082. $kDate = $this->sign($key, $dateStamp);
  2083. $kRegion = $this->sign($kDate, $regionName);
  2084. $kService = $this->sign($kRegion, $serviceName);
  2085. $kSigning = $this->sign($kService, 'request');
  2086. return $kSigning;
  2087. }
  2088. // 获取签名头信息
  2089. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2090. $contenttype = 'application/x-www-form-urlencoded';
  2091. $accept = 'application/json';
  2092. // 获取当前UTC时间
  2093. $t = new DateTime('now', new DateTimeZone('UTC'));
  2094. $xdate = $t->format('Ymd\THis\Z');
  2095. $datestamp = $t->format('Ymd');
  2096. // 1. 拼接规范请求串
  2097. $canonical_uri = '/';
  2098. $canonical_querystring = $request_parameters;
  2099. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2100. $signed_headers = 'content-type;host;x-date';
  2101. // 空请求体的SHA256哈希
  2102. $payload_hash = hash('sha256', '');
  2103. $canonical_request = implode("\n", [
  2104. $method,
  2105. $canonical_uri,
  2106. $canonical_querystring,
  2107. $canonical_headers,
  2108. $signed_headers,
  2109. $payload_hash
  2110. ]);
  2111. // 2. 拼接待签名字符串
  2112. $algorithm = 'HMAC-SHA256';
  2113. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2114. $hashed_canonical_request = hash('sha256', $canonical_request);
  2115. $string_to_sign = implode("\n", [
  2116. $algorithm,
  2117. $xdate,
  2118. $credential_scope,
  2119. $hashed_canonical_request
  2120. ]);
  2121. // 3. 计算签名
  2122. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2123. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2124. // 4. 添加签名到请求头
  2125. $authorization_header = sprintf(
  2126. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2127. $algorithm,
  2128. $access_key,
  2129. $credential_scope,
  2130. $signed_headers,
  2131. $signature
  2132. );
  2133. return [
  2134. 'Accept' => $accept,
  2135. 'Content-Type' => $contenttype,
  2136. 'X-Date' => $xdate,
  2137. 'Authorization' => $authorization_header
  2138. ];
  2139. }
  2140. // 文字合成语音(火山引擎)
  2141. public function tts($data) {
  2142. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2143. $headers = [
  2144. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2145. 'Content-Type' => 'application/json; charset=UTF-8'
  2146. ];
  2147. $post_data = [
  2148. 'app' => [
  2149. 'appid' => env('VOLC_APPID'),
  2150. 'token' => env('VOLC_TOKEN'),
  2151. 'cluster' => 'volcano_tts'
  2152. ],
  2153. 'user' => [
  2154. 'uid' => 'mp_audio'
  2155. ],
  2156. // 'audio' => [
  2157. // 'voice_type' =>
  2158. // ],
  2159. ];
  2160. }
  2161. public function scriptList($data) {
  2162. $uid = Site::getUid();
  2163. $script_id = getProp($data, 'script_id');
  2164. $script_name = getProp($data, 'script_name');
  2165. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2166. if ($script_id) {
  2167. $query->where('id', $script_id);
  2168. }
  2169. if ($script_name) {
  2170. $query->where('script_name', 'like', "%{$script_name}%");
  2171. }
  2172. return $query->orderBy('created_at', 'desc')->paginate(12);
  2173. }
  2174. public function scripts($data) {
  2175. $uid = Site::getUid();
  2176. $script_id = getProp($data, 'script_id');
  2177. $script_name = getProp($data, 'script_name');
  2178. $is_products = getProp($data, 'is_products');
  2179. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2180. if ($script_id) {
  2181. $query->where('id', $script_id);
  2182. }
  2183. if ($is_products !== '') {
  2184. $query->where('is_products', $is_products);
  2185. }
  2186. if ($script_name) {
  2187. $query->where('script_name', 'like', "%{$script_name}%");
  2188. }
  2189. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2190. return (array)$value;
  2191. })->toArray();
  2192. }
  2193. public function scriptInfo($data) {
  2194. $uid = Site::getUid();
  2195. $script_id = getProp($data, 'script_id');
  2196. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2197. // ->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();
  2198. ->selectRaw('id as script_id, script_name')->first();
  2199. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2200. $script = (array)$script;
  2201. // 获取分集组信息
  2202. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2203. ->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')
  2204. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2205. $value = (array)$value;
  2206. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2207. return (array)$value;
  2208. })->toArray();
  2209. $script['group'] = $groups;
  2210. return $script;
  2211. }
  2212. public function createScript($data) {
  2213. $script_name = getProp($data, 'script_name');
  2214. $uid = Site::getUid(); // 获取当前用户ID
  2215. $cpid = Site::getCpid(); // 获取当前公司组ID
  2216. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2217. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2218. $script_name .= '_'.date('YmdHis');
  2219. }
  2220. return DB::table('mp_scripts')->insertGetId([
  2221. 'script_name' => $script_name,
  2222. 'user_id' => $uid,
  2223. 'cpid' => $cpid,
  2224. 'created_at' => date('Y-m-d H:i:s'),
  2225. 'updated_at' => date('Y-m-d H:i:s')
  2226. ]);
  2227. }
  2228. public function editScript($data) {
  2229. $script_id = getProp($data, 'script_id');
  2230. $script_name = getProp($data, 'script_name');
  2231. $uid = Site::getUid(); // 获取当前用户ID
  2232. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2233. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2234. if ($id && (int)$id !== (int)$script_id) {
  2235. $script_name .= '_'.date('YmdHis');
  2236. }
  2237. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2238. 'script_name' => $script_name,
  2239. 'updated_at' => date('Y-m-d H:i:s')
  2240. ]);
  2241. }
  2242. public function delScript($data) {
  2243. $script_id = getProp($data, 'script_id');
  2244. $uid = Site::getUid(); // 获取当前用户ID
  2245. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2246. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2247. 'is_deleted' => 1,
  2248. 'updated_at' => date('Y-m-d H:i:s')
  2249. ]);
  2250. }
  2251. public function createEpisode($data) {
  2252. $script_id = getProp($data, 'script_id');
  2253. $group_name = getProp($data, 'group_name');
  2254. $remark = getProp($data, 'remark');
  2255. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2256. $uid = Site::getUid(); // 获取当前用户ID
  2257. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2258. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2259. $group_name .= '_'.date('YmdHis');
  2260. }
  2261. return DB::table('mp_script_episode_group')->insertGetId([
  2262. 'script_id' => $script_id,
  2263. 'group_name' => $group_name,
  2264. 'user_id' => $uid,
  2265. 'remark' => $remark,
  2266. 'created_at' => date('Y-m-d H:i:s'),
  2267. 'updated_at' => date('Y-m-d H:i:s')
  2268. ]);
  2269. }
  2270. public function editEpisode($data) {
  2271. $group_id = getProp($data, 'group_id');
  2272. $start_episode_number = getProp($data, 'start_episode_number');
  2273. $end_episode_number = getProp($data, 'end_episode_number');
  2274. $group_name = getProp($data, 'group_name');
  2275. $uid = Site::getUid(); // 获取当前用户ID
  2276. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2277. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2278. if ($id && (int)$id !== (int)$group_id) {
  2279. $group_name .= '_'.date('YmdHis');
  2280. }
  2281. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2282. 'group_name' => $group_name,
  2283. 'start_episode_number' => $start_episode_number,
  2284. 'end_episode_number' => $end_episode_number,
  2285. 'updated_at' => date('Y-m-d H:i:s')
  2286. ]);
  2287. }
  2288. public function delEpisode($data) {
  2289. $group_id = getProp($data, 'group_id');
  2290. $uid = Site::getUid(); // 获取当前用户ID
  2291. if (!$group_id) Utils::throwError('20003:请选择分集');
  2292. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2293. 'is_deleted' => 1,
  2294. 'updated_at' => date('Y-m-d H:i:s')
  2295. ]);
  2296. }
  2297. /**
  2298. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2299. *
  2300. * @param array $data 包含以下参数:
  2301. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2302. * - question: 用户问题(可选)
  2303. * - model: 使用的模型(r1 或 v3,默认 v3)
  2304. * @return \Generator 返回生成器,用于流式输出
  2305. */
  2306. public function generateEpisodes($data) {
  2307. $script_id = getProp($data, 'script_id');
  2308. $group_id = getProp($data, 'group_id');
  2309. // $file = getProp($data, 'file');
  2310. $file = '';
  2311. $content = getProp($data, 'content', '');
  2312. // $bid = getProp($data, 'bid', 0);
  2313. $bid = 0;
  2314. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2315. if (!$group) {
  2316. Utils::throwError('20003:剧本分集不存在');
  2317. }
  2318. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2319. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2320. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2321. $prompt = getProp($data, 'prompt');
  2322. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2323. $model = getProp($data, 'model');
  2324. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2325. Utils::throwError('20003:该模型不存在!');
  2326. }
  2327. // 检查是否存在重叠的剧集序号范围
  2328. $exists_groups = DB::table('mp_script_episode_group')
  2329. ->where('script_id', $script_id)
  2330. ->where('id', '<>', $group_id) // 排除当前组
  2331. ->where('is_deleted', 0)
  2332. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2333. // 检查新范围是否与现有范围重叠
  2334. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2335. // 新范围的开始在现有范围内
  2336. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2337. ->where('end_episode_number', '>=', $start_episode_sequence);
  2338. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2339. // 新范围的结束在现有范围内
  2340. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2341. ->where('end_episode_number', '>=', $end_episode_sequence);
  2342. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2343. // 新范围完全包含现有范围
  2344. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2345. ->where('end_episode_number', '<=', $end_episode_sequence);
  2346. });
  2347. })
  2348. ->select('start_episode_number', 'end_episode_number')
  2349. ->get();
  2350. if ($exists_groups->isNotEmpty()) {
  2351. $conflict_ranges = [];
  2352. foreach ($exists_groups as $group) {
  2353. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2354. }
  2355. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2356. }
  2357. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2358. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2359. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2360. if ($model === 'deepseek-chat') {
  2361. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2362. $model = 'deepseek-v4-flash';
  2363. $thinkingMode = 'disabled';
  2364. } elseif ($model === 'deepseek-reasoner') {
  2365. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2366. $model = 'deepseek-v4-flash';
  2367. $thinkingMode = 'enabled';
  2368. }
  2369. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2370. if (!$script) {
  2371. Utils::throwError('20003:剧本不存在');
  2372. }
  2373. $content = getProp($group, 'content');
  2374. if (!$file && !$content && !$bid) {
  2375. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2376. }
  2377. // 提取文件内容
  2378. if ($file) {
  2379. $content = $this->extractFileContent($file);
  2380. if (!$content) {
  2381. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2382. }
  2383. } elseif ($bid) {
  2384. $content = $this->getContentByBid($bid);
  2385. if (!$content) {
  2386. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2387. }
  2388. } elseif ($content) {
  2389. $content = filterContent($content);
  2390. } elseif ($prompt) {
  2391. $content = filterContent($prompt);
  2392. } else {
  2393. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2394. }
  2395. // 构建消息
  2396. $messages = [
  2397. $this->sys_message,
  2398. [
  2399. 'role' => 'user',
  2400. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2401. ]
  2402. ];
  2403. $post_data = [
  2404. 'model' => $model,
  2405. 'messages' => $messages,
  2406. // 'max_tokens' => 8192,
  2407. 'temperature' => 0.7,
  2408. 'frequency_penalty' => 0,
  2409. 'presence_penalty' => 0,
  2410. 'thinking' => ['type' => $thinkingMode],
  2411. 'response_format' => ['type' => 'text'],
  2412. 'stream' => true
  2413. ];
  2414. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2415. // 根据模型类型选择调用方法
  2416. $fullContent = '';
  2417. $fullReasoningContent = '';
  2418. $usage = [];
  2419. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2420. // DeepSeek 官方模型使用 DeepSeek API
  2421. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2422. } else if (in_array($model, $this->gpt_text_models)) {
  2423. // GPT-5.4 模型使用 TokenRouter API
  2424. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2425. } else {
  2426. // 其他模型使用火山引擎API
  2427. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2428. }
  2429. // 处理流式输出
  2430. foreach ($streamGenerator as $chunk) {
  2431. if (isset($chunk['type'])) {
  2432. if ($chunk['type'] === 'done') {
  2433. // 最终结果
  2434. $fullContent = $chunk['full_content'];
  2435. $fullReasoningContent = $chunk['full_reasoning'];
  2436. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2437. } else {
  2438. // 逐块yield数据
  2439. yield $chunk;
  2440. }
  2441. }
  2442. }
  2443. dLog('deepseek')->info('完整内容: '.$fullContent);
  2444. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2445. // 处理完整内容并返回最终结果
  2446. $script_arr = [];
  2447. if ($fullContent) {
  2448. $script_arr = extractScriptContent($fullContent);
  2449. }
  2450. logDB('deepseek', 'info', '解析内容', $script_arr);
  2451. if (!$script_arr['episodes']) {
  2452. Utils::throwError('20003:未生成剧本相关信息');
  2453. // yield [
  2454. // 'type' => 'done',
  2455. // 'script' => $script_arr,
  2456. // 'msg' => '未生成剧本相关信息',
  2457. // 'answer' => $fullContent,
  2458. // 'reasoning' => $fullReasoningContent,
  2459. // 'usage' => $usage
  2460. // ];
  2461. // return ;
  2462. }
  2463. try {
  2464. DB::beginTransaction();
  2465. // // 返回前保存剧本内容
  2466. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2467. // 'content' => $content,
  2468. // 'updated_at' => date('Y-m-d H:i:s')
  2469. // ]);
  2470. // if (!$boolen) {
  2471. // Utils::throwError('20003:保存剧本内容失败');
  2472. // }
  2473. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2474. // 'start_episode_number' => $start_episode_sequence,
  2475. // 'end_episode_number' => $end_episode_sequence,
  2476. // 'updated_at' => date('Y-m-d H:i:s')
  2477. // ]);
  2478. // if (!$boolen1) {
  2479. // Utils::throwError('20003:保存分集失败');
  2480. // }
  2481. $episode_content = '';
  2482. $episodes = [];
  2483. foreach ($script_arr['episodes'] as $item) {
  2484. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2485. // $episodes[] = [
  2486. // 'script_id' => $script_id,
  2487. // 'episode_number' => $item['episode_number'],
  2488. // 'episode_name' => $item['episode_name'],
  2489. // 'episode_content' => $item['episode_content'],
  2490. // 'created_at' => date('Y-m-d H:i:s'),
  2491. // 'updated_at' => date('Y-m-d H:i:s'),
  2492. // ];
  2493. }
  2494. if ($episode_content) {
  2495. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2496. 'episode_content' => $episode_content,
  2497. 'updated_at' => date('Y-m-d H:i:s')
  2498. ]);
  2499. if (!$boolen2) {
  2500. Utils::throwError('20003:保存分集内容失败');
  2501. }
  2502. }else {
  2503. Utils::throwError('20003:分集剧本解析失败');
  2504. }
  2505. }catch (\Exception $e) {
  2506. DB::rollBack();
  2507. Utils::throwError('20003:'.$e->getMessage());
  2508. }
  2509. DB::commit();
  2510. yield [
  2511. 'type' => 'done',
  2512. 'script' => $script_arr,
  2513. 'episode_content' => $episode_content,
  2514. 'answer' => $fullContent,
  2515. 'reasoning' => $fullReasoningContent,
  2516. 'usage' => $usage
  2517. ];
  2518. }
  2519. public function chatWithFileStream($data) {
  2520. $script_id = getProp($data, 'script_id');
  2521. $group_id = getProp($data, 'group_id');
  2522. $file = getProp($data, 'file');
  2523. $content = getProp($data, 'content', '');
  2524. $bid = getProp($data, 'bid', 0);
  2525. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2526. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2527. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2528. $prompt = getProp($data, 'prompt');
  2529. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2530. if (!empty($prompt)) {
  2531. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2532. }
  2533. $question = getProp($data, 'question', $baseQuestion);
  2534. $model = getProp($data, 'model');
  2535. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2536. Utils::throwError('20003:该模型不存在!');
  2537. }
  2538. // 检查是否存在重叠的剧集序号范围
  2539. $exists_groups = DB::table('mp_script_episode_group')
  2540. ->where('script_id', $script_id)
  2541. ->where('id', '<>', $group_id)
  2542. ->where('is_deleted', 0)
  2543. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2544. // 检查新范围是否与现有范围重叠
  2545. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2546. // 新范围的开始在现有范围内
  2547. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2548. ->where('end_episode_number', '>=', $start_episode_sequence);
  2549. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2550. // 新范围的结束在现有范围内
  2551. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2552. ->where('end_episode_number', '>=', $end_episode_sequence);
  2553. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2554. // 新范围完全包含现有范围
  2555. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2556. ->where('end_episode_number', '<=', $end_episode_sequence);
  2557. });
  2558. })
  2559. ->select('start_episode_number', 'end_episode_number')
  2560. ->get();
  2561. if ($exists_groups->isNotEmpty()) {
  2562. $conflict_ranges = [];
  2563. foreach ($exists_groups as $group) {
  2564. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2565. }
  2566. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2567. }
  2568. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2569. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2570. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2571. if ($model === 'deepseek-chat') {
  2572. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2573. $model = 'deepseek-v4-flash';
  2574. $thinkingMode = 'disabled';
  2575. } elseif ($model === 'deepseek-reasoner') {
  2576. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2577. $model = 'deepseek-v4-flash';
  2578. $thinkingMode = 'enabled';
  2579. }
  2580. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2581. if (!$script) {
  2582. Utils::throwError('20003:剧本不存在');
  2583. }
  2584. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2585. if (!$group) {
  2586. Utils::throwError('20003:剧本分集不存在');
  2587. }
  2588. if (!$file && !$content && !$bid) {
  2589. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2590. }
  2591. // 提取文件内容
  2592. if ($file) {
  2593. $content = $this->extractFileContent($file);
  2594. if (!$content) {
  2595. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2596. }
  2597. } elseif ($bid) {
  2598. $content = $this->getContentByBid($bid);
  2599. if (!$content) {
  2600. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2601. }
  2602. } elseif ($content) {
  2603. $content = filterContent($content);
  2604. } elseif ($prompt) {
  2605. $content = filterContent($prompt);
  2606. } else {
  2607. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2608. }
  2609. // 构建消息
  2610. $messages = [
  2611. [
  2612. 'role' => 'system',
  2613. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2614. 强制要求:\n
  2615. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2616. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2617. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2618. 普通要求:\n
  2619. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2620. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2621. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2622. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2623. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2624. 示例如下:\n
  2625. ###剧本名:西昆仑
  2626. ###故事梗概
  2627. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2628. ###剧本亮点
  2629. 亮点1:绝境奇药,生死一线
  2630. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2631. 亮点2:结拜兄妹,化解尴尬
  2632. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2633. 亮点3:纤发夺命,情愫暗涌
  2634. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2635. ###人物关系
  2636. 阿雪与梁萧之间存在兄妹之情。
  2637. ###核心矛盾
  2638. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2639. ###主体列表
  2640. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2641. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2642. 阴阳球:天地异宝,能化生精气,救人于危难。
  2643. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2644. ###美术风格
  2645. 基础画风风格词:厚涂古风
  2646. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2647. ###场景列表
  2648. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2649. [
  2650. 'role' => 'user',
  2651. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2652. ]
  2653. ];
  2654. $post_data = [
  2655. 'model' => $model,
  2656. 'messages' => $messages,
  2657. // 'max_tokens' => 8192,
  2658. 'temperature' => 0.7,
  2659. 'frequency_penalty' => 0,
  2660. 'presence_penalty' => 0,
  2661. 'thinking' => ['type' => $thinkingMode],
  2662. 'response_format' => ['type' => 'text'],
  2663. 'stream' => true
  2664. ];
  2665. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2666. // 根据模型类型选择调用方法
  2667. $fullContent = '';
  2668. $fullReasoningContent = '';
  2669. $usage = [];
  2670. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2671. // DeepSeek 官方模型使用 DeepSeek API
  2672. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2673. } else if (in_array($model, $this->gpt_text_models)) {
  2674. // GPT-5.4 模型使用 TokenRouter API
  2675. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2676. } else {
  2677. // 其他模型使用火山引擎API
  2678. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2679. }
  2680. // 处理流式输出
  2681. foreach ($streamGenerator as $chunk) {
  2682. if (isset($chunk['type'])) {
  2683. if ($chunk['type'] === 'done') {
  2684. // 最终结果
  2685. $fullContent = $chunk['full_content'];
  2686. $fullReasoningContent = $chunk['full_reasoning'];
  2687. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2688. } else {
  2689. // 逐块yield数据
  2690. yield $chunk;
  2691. }
  2692. }
  2693. }
  2694. dLog('deepseek')->info('完整内容: '.$fullContent);
  2695. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2696. // 处理完整内容并返回最终结果
  2697. $script_arr = [];
  2698. if ($fullContent) {
  2699. $script_arr = extractScriptContent($fullContent);
  2700. }
  2701. logDB('deepseek', 'info', '解析内容', $script_arr);
  2702. if (!$script_arr['roles']) {
  2703. Utils::throwError('20003:未生成剧本相关信息');
  2704. // yield [
  2705. // 'type' => 'done',
  2706. // 'script' => $script_arr,
  2707. // 'msg' => '未生成剧本相关信息',
  2708. // 'answer' => $fullContent,
  2709. // 'reasoning' => $fullReasoningContent,
  2710. // 'usage' => $usage
  2711. // ];
  2712. }
  2713. try {
  2714. DB::beginTransaction();
  2715. // // 返回前保存剧本内容
  2716. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2717. // 'content' => $content,
  2718. // 'status' => '解析完成',
  2719. // 'updated_at' => date('Y-m-d H:i:s')
  2720. // ]);
  2721. // if (!$boolen) {
  2722. // Utils::throwError('20003:保存剧本内容失败');
  2723. // }
  2724. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2725. 'start_episode_number' => $start_episode_sequence,
  2726. 'end_episode_number' => $end_episode_sequence,
  2727. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2728. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2729. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2730. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2731. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2732. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2733. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2734. 'status' => '解析完成',
  2735. 'content' => $content,
  2736. 'updated_at' => date('Y-m-d H:i:s')
  2737. ]);
  2738. if (!$boolen1) {
  2739. Utils::throwError('20003:保存分集失败');
  2740. }
  2741. // $episodes = [];
  2742. // foreach ($script_arr['episodes'] as $item) {
  2743. // $episodes[] = [
  2744. // 'script_id' => $script_id,
  2745. // 'episode_number' => $item['episode_number'],
  2746. // 'episode_name' => $item['episode_name'],
  2747. // 'episode_content' => $item['episode_content'],
  2748. // 'created_at' => date('Y-m-d H:i:s'),
  2749. // 'updated_at' => date('Y-m-d H:i:s'),
  2750. // ];
  2751. // }
  2752. // if ($episodes) {
  2753. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2754. // if (!$boolen2) {
  2755. // Utils::throwError('20003:保存分集内容失败');
  2756. // }
  2757. // }else {
  2758. // Utils::throwError('20003:分集剧本解析失败');
  2759. // }
  2760. }catch (\Exception $e) {
  2761. DB::rollBack();
  2762. Utils::throwError('20003:'.$e->getMessage());
  2763. }
  2764. DB::commit();
  2765. yield [
  2766. 'type' => 'done',
  2767. 'script' => $script_arr,
  2768. 'answer' => $fullContent,
  2769. 'reasoning' => $fullReasoningContent,
  2770. 'usage' => $usage
  2771. ];
  2772. }
  2773. /**
  2774. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2775. *
  2776. * @param array $data 包含以下参数:
  2777. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2778. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2779. * - model: 使用的模型(r1 或 v3,默认 v3)
  2780. * @return array
  2781. */
  2782. public function chatWithFile($data) {
  2783. $script_id = getProp($data, 'script_id');
  2784. $file = getProp($data, 'file');
  2785. $content = getProp($data, 'content', '');
  2786. $bid = getProp($data, 'bid', 0);
  2787. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2788. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2789. $prompt = getProp($data, 'prompt');
  2790. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2791. if (!empty($prompt)) {
  2792. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2793. }
  2794. $question = getProp($data, 'question', $baseQuestion);
  2795. // 处理文本模型
  2796. $model = getProp($data, 'model');
  2797. if (!$model) {
  2798. // 用户没有输入,使用默认值
  2799. $model = 'doubao-seed-2-0-mini-260215';
  2800. }
  2801. // 验证模型是否在可用模型表中
  2802. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2803. $model = 'doubao-seed-2-0-mini-260215';
  2804. }
  2805. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2806. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2807. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2808. if ($model === 'deepseek-chat') {
  2809. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2810. $model = 'deepseek-v4-flash';
  2811. $thinkingMode = 'disabled';
  2812. } elseif ($model === 'deepseek-reasoner') {
  2813. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2814. $model = 'deepseek-v4-flash';
  2815. $thinkingMode = 'enabled';
  2816. }
  2817. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2818. if (!$script) {
  2819. Utils::throwError('20003:剧本不存在');
  2820. }
  2821. if (!$file && !$content && !$bid) {
  2822. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2823. }
  2824. // 提取文件内容
  2825. if ($file) {
  2826. $content = $this->extractFileContent($file);
  2827. if (!$content) {
  2828. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2829. }
  2830. } elseif ($bid) {
  2831. $content = $this->getContentByBid($bid);
  2832. if (!$content) {
  2833. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2834. }
  2835. } elseif ($content) {
  2836. $content = filterContent($content);
  2837. } elseif ($prompt) {
  2838. $content = filterContent($prompt);
  2839. } else {
  2840. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2841. }
  2842. // 构建消息
  2843. $messages = [
  2844. $this->sys_message,
  2845. [
  2846. 'role' => 'user',
  2847. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2848. ]
  2849. ];
  2850. $post_data = [
  2851. 'model' => $model,
  2852. 'messages' => $messages,
  2853. // 'max_tokens' => 8192,
  2854. 'temperature' => 0.7,
  2855. 'frequency_penalty' => 0,
  2856. 'presence_penalty' => 0,
  2857. 'thinking' => ['type' => $thinkingMode],
  2858. 'response_format' => ['type' => 'text'],
  2859. 'stream' => false
  2860. ];
  2861. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2862. // 根据模型类型选择调用方法
  2863. $fullContent = '';
  2864. $usage = [];
  2865. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2866. // DeepSeek 官方模型使用 DeepSeek API
  2867. $chatResult = $this->chatOnly($post_data);
  2868. } else if (in_array($model, $this->gpt_text_models)) {
  2869. // GPT-5.4 模型使用 TokenRouter API
  2870. $chatResult = $this->gpt54ChatOnly($post_data);
  2871. } else {
  2872. // 其他模型使用火山引擎API
  2873. $chatResult = $this->volcEngineChatCompletion($post_data);
  2874. }
  2875. if (is_array($chatResult)) {
  2876. $fullContent = $chatResult['fullContent'];
  2877. $usage = $chatResult['usage'];
  2878. }
  2879. $script_arr = [];
  2880. // 处理结果
  2881. if ($fullContent) {
  2882. $script_arr = extractScriptContent($fullContent);
  2883. }
  2884. // 返回前保存剧本内容
  2885. DB::table('mp_scripts')->where('id', $script_id)->update([
  2886. 'content' => $content,
  2887. 'updated_at' => date('Y-m-d H:i:s')
  2888. ]);
  2889. return [
  2890. 'script' => $script_arr,
  2891. 'answer' => $fullContent,
  2892. 'usage' => $usage
  2893. ];
  2894. }
  2895. public function getEpisodeContent($data) {
  2896. $group_id = getProp($data, 'group_id');
  2897. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2898. }
  2899. public function saveEpisodeContent($data) {
  2900. $script_id = getProp($data, 'script_id');
  2901. $group_id = getProp($data, 'group_id');
  2902. $start_episode_sequence = getProp($data, 'start_episode_number');
  2903. $end_episode_sequence = getProp($data, 'end_episode_number');
  2904. // 检查是否存在重叠的剧集序号范围
  2905. $exists_groups = DB::table('mp_script_episode_group')
  2906. ->where('script_id', $script_id)
  2907. ->where('id', '<>', $group_id) // 排除当前组
  2908. ->where('is_deleted', 0)
  2909. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2910. // 检查新范围是否与现有范围重叠
  2911. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2912. // 新范围的开始在现有范围内
  2913. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2914. ->where('end_episode_number', '>=', $start_episode_sequence);
  2915. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2916. // 新范围的结束在现有范围内
  2917. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2918. ->where('end_episode_number', '>=', $end_episode_sequence);
  2919. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2920. // 新范围完全包含现有范围
  2921. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2922. ->where('end_episode_number', '<=', $end_episode_sequence);
  2923. });
  2924. })
  2925. ->select('start_episode_number', 'end_episode_number')
  2926. ->get();
  2927. if ($exists_groups->isNotEmpty()) {
  2928. $conflict_ranges = [];
  2929. foreach ($exists_groups as $group) {
  2930. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2931. }
  2932. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2933. }
  2934. $episode_content = getProp($data, 'episode_content');
  2935. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2936. 'content' => $episode_content,
  2937. 'start_episode_number' => $start_episode_sequence,
  2938. 'end_episode_number' => $end_episode_sequence,
  2939. 'updated_at' => date('Y-m-d H:i:s')
  2940. ]);
  2941. $script_arr =getProp($data, 'script', []);
  2942. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2943. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2944. $script_id = getProp($data, 'script_id');
  2945. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2946. try {
  2947. DB::beginTransaction();
  2948. $update_data = [
  2949. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2950. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2951. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2952. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2953. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2954. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2955. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2956. 'status' => 3,
  2957. 'start_episode_sequence' => $start_episode_sequence,
  2958. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2959. 'episode_num' => count($script_arr['episodes']),
  2960. 'updated_at' => date('Y-m-d H:i:s')
  2961. ];
  2962. // 保存剧本内容
  2963. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2964. if (!$boolen) {
  2965. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2966. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2967. Utils::throwError('20003:剧本内容保存失败');
  2968. }
  2969. // 保存分集内容
  2970. // 删除历史分集内容
  2971. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2972. $episodes = [];
  2973. $sequence = 1;
  2974. foreach ($script_arr['episodes'] as $episode) {
  2975. $segment_number = 1;
  2976. foreach($episode['segments'] as $segment) {
  2977. $episodes[] = [
  2978. 'script_id' => $script_id,
  2979. 'episode_number' => $episode['episode_number'],
  2980. 'title' => $episode['title'],
  2981. // 'content' => $episode['content'],
  2982. 'content' => '',
  2983. 'segment_number' => $segment_number,
  2984. 'segment_content' => $segment['segment_content'],
  2985. 'sequence' => $sequence,
  2986. 'created_at' => date('Y-m-d H:i:s'),
  2987. 'updated_at' => date('Y-m-d H:i:s')
  2988. ];
  2989. $sequence++;
  2990. $segment_number++;
  2991. }
  2992. }
  2993. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2994. if (!$boolen2) {
  2995. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2996. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2997. Utils::throwError('20003:分集内容保存失败');
  2998. }
  2999. } catch (\Exception $e) {
  3000. DB::rollBack();
  3001. Utils::throwError('20003:'.$e->getMessage());
  3002. }
  3003. DB::commit();
  3004. return true;
  3005. }
  3006. public function getBookContent($data) {
  3007. $bid = getProp($data, 'bid');
  3008. $start_sequence = getProp($data, 'start_sequence');
  3009. $end_sequence = getProp($data, 'end_sequence');
  3010. $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])
  3011. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3012. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3013. return $return_content;
  3014. }
  3015. public function exportScript($data) {
  3016. $filename = getProp($data, 'filename');
  3017. $script_id = getProp($data, 'script_id');
  3018. $group_id = getProp($data, 'group_id');
  3019. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3020. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3021. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3022. $script = (array)$script;
  3023. // 获取分集组信息
  3024. if ($group_id) {
  3025. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3026. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3027. ->get()->map(function($value) {
  3028. return (array)$value;
  3029. })->toArray();
  3030. }else {
  3031. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3032. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3033. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3034. return (array)$value;
  3035. })->toArray();
  3036. }
  3037. if (!$groups) Utils::throwError('20003:分集不存在');
  3038. $script['group'] = $groups;
  3039. $export_type = getProp($data, 'export_type', 'txt');
  3040. // 生成文件名
  3041. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3042. // 根据导出类型生成不同格式的文件
  3043. switch ($export_type) {
  3044. case 'txt':
  3045. return $this->exportScriptAsTxt($script, $filename);
  3046. case 'pdf':
  3047. return $this->exportScriptAsPdf($script, $filename);
  3048. default:
  3049. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3050. }
  3051. }
  3052. /**
  3053. * 导出剧本为TXT格式
  3054. */
  3055. private function exportScriptAsTxt($script, $filename) {
  3056. // 构建TXT内容
  3057. $content = $this->buildScriptContent($script);
  3058. // 设置响应头,直接下载
  3059. header('Content-Type: text/plain; charset=utf-8');
  3060. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3061. header('Content-Length: ' . strlen($content));
  3062. // 输出内容并结束
  3063. echo $content;
  3064. exit();
  3065. }
  3066. /**
  3067. * 导出剧本为PDF格式
  3068. */
  3069. private function exportScriptAsPdf($script, $filename) {
  3070. // 使用HTML转PDF的方式来更好地支持中文
  3071. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3072. // 创建PDF实例
  3073. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3074. // 设置文档信息
  3075. $pdf->SetCreator('剧本导出系统');
  3076. $pdf->SetAuthor('系统');
  3077. $pdf->SetTitle($script['script_name']);
  3078. $pdf->SetSubject('剧本导出');
  3079. // 设置边距
  3080. $pdf->SetMargins(15, 15, 15);
  3081. $pdf->SetAutoPageBreak(TRUE, 15);
  3082. // 添加页面
  3083. $pdf->AddPage();
  3084. // 注册并使用 simsun.ttf 字体
  3085. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3086. // 使用HTML内容生成PDF
  3087. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3088. // 直接输出PDF文件供下载
  3089. header('Content-Type: application/pdf');
  3090. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3091. // 直接输出PDF内容
  3092. $pdf->Output($filename . '.pdf', 'D');
  3093. exit();
  3094. }
  3095. /**
  3096. * 构建用于PDF的HTML内容
  3097. */
  3098. private function buildScriptHtmlForPdf($script) {
  3099. $html = '<style>
  3100. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3101. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3102. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3103. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3104. .info { margin-bottom: 8px; }
  3105. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3106. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3107. .segment { margin-bottom: 10px; margin-left: 20px; }
  3108. .episode-content { white-space: pre-wrap; }
  3109. </style>';
  3110. // 标题
  3111. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3112. // 处理分组数据
  3113. if (!empty($script['group']) && is_array($script['group'])) {
  3114. $groups = (array)$script['group'];
  3115. foreach ($groups as $group) {
  3116. $html .= '<div class="group">';
  3117. // 分组标题
  3118. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3119. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3120. // 故事梗概
  3121. if (!empty($group['intro'])) {
  3122. $html .= '<h3>故事梗概</h3>';
  3123. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3124. }
  3125. // 剧本亮点
  3126. if (!empty($group['highlights'])) {
  3127. $html .= '<h3>剧本亮点</h3>';
  3128. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3129. }
  3130. // 人物关系
  3131. if (!empty($group['role_relationship'])) {
  3132. $html .= '<h3>人物关系</h3>';
  3133. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3134. }
  3135. // 核心矛盾
  3136. if (!empty($group['core_contradiction'])) {
  3137. $html .= '<h3>核心矛盾</h3>';
  3138. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3139. }
  3140. // 主体列表
  3141. if (!empty($group['roles']) && is_array($group['roles'])) {
  3142. $html .= '<h3>主体列表</h3>';
  3143. $html .= '<ul>';
  3144. foreach ($group['roles'] as $role) {
  3145. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3146. }
  3147. $html .= '</ul>';
  3148. }
  3149. // 美术风格
  3150. if (!empty($group['art_style'])) {
  3151. $html .= '<h3>美术风格</h3>';
  3152. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3153. }
  3154. // 场景列表
  3155. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3156. $html .= '<h3>场景列表</h3>';
  3157. $html .= '<ul>';
  3158. foreach ($group['scenes'] as $scene) {
  3159. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3160. }
  3161. $html .= '</ul>';
  3162. }
  3163. // 分集剧本
  3164. if (!empty($group['episode_content'])) {
  3165. $html .= '<h3>分集剧本</h3>';
  3166. // 去除零宽字符和其他不可见字符
  3167. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3168. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3169. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3170. }
  3171. $html .= '</div>';
  3172. }
  3173. }
  3174. return $html;
  3175. }
  3176. /**
  3177. * 构建PDF内容
  3178. */
  3179. private function buildPdfContent($pdf, $script) {
  3180. // 标题
  3181. $pdf->SetFont('dejavusans', 'B', 18);
  3182. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3183. $pdf->Ln(5);
  3184. // 基本信息
  3185. $pdf->SetFont('dejavusans', '', 12);
  3186. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3187. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3188. $pdf->Ln(5);
  3189. // 剧本简介
  3190. if (!empty($script['intro'])) {
  3191. $pdf->SetFont('dejavusans', 'B', 14);
  3192. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3193. $pdf->SetFont('dejavusans', '', 12);
  3194. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3195. $pdf->Ln(3);
  3196. }
  3197. // 亮点
  3198. if (!empty($script['highlights'])) {
  3199. $pdf->SetFont('dejavusans', 'B', 14);
  3200. $pdf->Cell(0, 10, '亮点', 0, 1);
  3201. $pdf->SetFont('dejavusans', '', 12);
  3202. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3203. $pdf->Ln(3);
  3204. }
  3205. // 核心矛盾
  3206. if (!empty($script['core_contradiction'])) {
  3207. $pdf->SetFont('dejavusans', 'B', 14);
  3208. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3209. $pdf->SetFont('dejavusans', '', 12);
  3210. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3211. $pdf->Ln(3);
  3212. }
  3213. // 艺术风格
  3214. if (!empty($script['art_style'])) {
  3215. $pdf->SetFont('dejavusans', 'B', 14);
  3216. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3217. $pdf->SetFont('dejavusans', '', 12);
  3218. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3219. $pdf->Ln(3);
  3220. }
  3221. // 备注
  3222. if (!empty($script['remark'])) {
  3223. $pdf->SetFont('dejavusans', 'B', 14);
  3224. $pdf->Cell(0, 10, '备注', 0, 1);
  3225. $pdf->SetFont('dejavusans', '', 12);
  3226. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3227. $pdf->Ln(3);
  3228. }
  3229. // 角色列表
  3230. if (!empty($script['roles']) && is_array($script['roles'])) {
  3231. $pdf->SetFont('dejavusans', 'B', 14);
  3232. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3233. $pdf->SetFont('dejavusans', '', 12);
  3234. foreach ($script['roles'] as $index => $role) {
  3235. if (is_array($role) || is_object($role)) {
  3236. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3237. } else {
  3238. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3239. }
  3240. }
  3241. $pdf->Ln(3);
  3242. }
  3243. // 角色关系
  3244. if (!empty($script['role_relationship'])) {
  3245. $pdf->SetFont('dejavusans', 'B', 14);
  3246. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3247. $pdf->SetFont('dejavusans', '', 12);
  3248. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3249. $pdf->Ln(3);
  3250. }
  3251. // 场景列表
  3252. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3253. $pdf->SetFont('dejavusans', 'B', 14);
  3254. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3255. $pdf->SetFont('dejavusans', '', 12);
  3256. foreach ($script['scenes'] as $index => $scene) {
  3257. if (is_array($scene) || is_object($scene)) {
  3258. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3259. } else {
  3260. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3261. }
  3262. }
  3263. $pdf->Ln(5);
  3264. }
  3265. // 分集内容
  3266. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3267. $pdf->SetFont('dejavusans', 'B', 16);
  3268. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3269. $pdf->Ln(3);
  3270. foreach ($script['episodes'] as $episode) {
  3271. // 检查是否需要新页面
  3272. if ($pdf->GetY() > 250) {
  3273. $pdf->AddPage();
  3274. }
  3275. $pdf->SetFont('dejavusans', 'B', 14);
  3276. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3277. if (!empty($episode['title'])) {
  3278. $episodeTitle .= ':' . $episode['title'];
  3279. }
  3280. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3281. // 处理分段内容
  3282. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3283. $pdf->SetFont('dejavusans', '', 12);
  3284. foreach ($episode['segments'] as $segment) {
  3285. if (!empty($segment['segment_content'])) {
  3286. // 如果有分段编号,显示分段标题
  3287. if (!empty($segment['segment_number'])) {
  3288. $pdf->SetFont('dejavusans', 'B', 12);
  3289. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3290. $pdf->SetFont('dejavusans', '', 12);
  3291. }
  3292. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3293. $pdf->Ln(2);
  3294. }
  3295. }
  3296. }
  3297. $pdf->Ln(5);
  3298. }
  3299. }
  3300. }
  3301. /**
  3302. * 构建剧本文本内容
  3303. */
  3304. private function buildScriptContent($script) {
  3305. $content = '';
  3306. $groups = $script['group'];
  3307. $groups = (array)$groups;
  3308. foreach ($groups as $group) {
  3309. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3310. // 剧本基本信息
  3311. if (!empty($group['intro'])) {
  3312. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3313. }
  3314. if (!empty($group['highlights'])) {
  3315. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3316. }
  3317. if (!empty($group['role_relationship'])) {
  3318. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3319. }
  3320. if (!empty($group['core_contradiction'])) {
  3321. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3322. }
  3323. if (!empty($group['roles']) && is_array($group['roles'])) {
  3324. $content .= "###主体列表\n";
  3325. foreach ($group['roles'] as $role) {
  3326. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3327. }
  3328. $content .= "\n\n";
  3329. }
  3330. if (!empty($group['art_style'])) {
  3331. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3332. }
  3333. // 场景信息
  3334. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3335. $content .= "###场景列表\n";
  3336. foreach ($group['scenes'] as $scene) {
  3337. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3338. }
  3339. $content .= "\n\n";
  3340. }
  3341. // 分集内容
  3342. if (!empty($group['episode_content'])) {
  3343. $content .= "###分集剧本\n";
  3344. $content .= $group['episode_content'];
  3345. // foreach ($script['episodes'] as $episode) {
  3346. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3347. // // if (!empty($episode['episode_name'])) {
  3348. // // $content .= ":" . $episode['episode_name'];
  3349. // // }
  3350. // // $content .= "\n";
  3351. // $content .= $episode['episode_content'] . "\n\n";
  3352. // }
  3353. }
  3354. }
  3355. return $content;
  3356. }
  3357. /**
  3358. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3359. *
  3360. * @param array $data 包含以下参数:
  3361. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3362. * - question: 用户问题(可选)
  3363. * - model: 使用的模型(r1 或 v3,默认 v3)
  3364. * @return \Generator 返回生成器,用于流式输出
  3365. */
  3366. public function addChat($data) {
  3367. $uid = Site::getUid();
  3368. $anime_id = getProp($data, 'anime_id');
  3369. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3370. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3371. if (!$anime) Utils::throwError('20003:对话不存在');
  3372. $file = getProp($data, 'file');
  3373. $content = getProp($data, 'content', '');
  3374. $bid = getProp($data, 'bid', 0);
  3375. $script_id = getProp($data, 'script_id', 0);
  3376. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3377. $prompt = getProp($data, 'prompt');
  3378. $user_anime_name = getProp($anime, 'anime_name');
  3379. // 处理文本模型
  3380. $model = getProp($data, 'model');
  3381. if (!$model) {
  3382. // 用户没有输入,从anime表获取
  3383. $model = getProp($anime, 'model');
  3384. if (!$model) {
  3385. // anime表也没有,使用默认值
  3386. $model = 'doubao-seed-2-0-mini-260215';
  3387. }
  3388. }
  3389. // 验证模型是否在可用模型表中
  3390. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3391. $model = 'doubao-seed-2-0-mini-260215';
  3392. }
  3393. $is_multi = getProp($anime, 'is_multi');
  3394. $is_single = (int)$is_multi !== 1;
  3395. // 积分余额预检(仅单剧集模式收费)
  3396. if ($is_single) {
  3397. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  3398. }
  3399. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3400. if ($prompt) {
  3401. $question .= "本次修改要求如下:\n{$prompt}";
  3402. }
  3403. // if (!$file && !$content && !$bid) {
  3404. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3405. // }
  3406. // 提取文件内容
  3407. if ($file) {
  3408. $content = $this->extractFileContent($file);
  3409. if (!$content) {
  3410. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3411. }
  3412. } elseif ($script_id) {
  3413. $content = $this->getContentByScriptId($script_id);
  3414. if (!$content) {
  3415. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3416. }
  3417. } elseif ($bid) {
  3418. $content = $this->getContentByBid($bid);
  3419. if (!$content) {
  3420. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3421. }
  3422. } elseif ($content) {
  3423. $content = filterContent($content);
  3424. } else {
  3425. $content = getProp($anime, 'content');
  3426. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3427. $need_generate_content = true;
  3428. }
  3429. }
  3430. // 美术风格
  3431. $input_art_style = getProp($data, 'art_style');
  3432. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3433. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3434. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3435. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3436. 中年女:邻居阿姨
  3437. 老年男:幽默大爷
  3438. 老年女:婆婆
  3439. 萌娃:奶气萌娃";
  3440. // 判断是否需要生成原文内容
  3441. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3442. // 如果需要生成原文内容,添加额外的要求
  3443. $content_generation_requirement = $need_generate_content
  3444. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3445. : "";
  3446. // 美术风格
  3447. if (!$mappedArtStyle) {
  3448. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3449. }else {
  3450. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3451. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3452. }else {
  3453. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3454. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3455. }
  3456. }
  3457. $systemPrompt = $is_single
  3458. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3459. 强制要求:
  3460. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3461. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3462. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3463. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3464. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3465. 普通要求:
  3466. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3467. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3468. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3469. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3470. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3471. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3472. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3473. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3474. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3475. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3476. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3477. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3478. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3479. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3480. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3481. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3482. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3483. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3484. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3485. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3486. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3487. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3488. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3489. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3490. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3491. 5.{$mappedArtStyle_prompt}\n\n
  3492. 示例如下:\n
  3493. ###剧本名:西昆仑
  3494. ###故事梗概
  3495. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3496. ###剧本亮点
  3497. 亮点1:绝境奇药,生死一线
  3498. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3499. 亮点2:结拜兄妹,化解尴尬
  3500. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3501. 亮点3:纤发夺命,情愫暗涌
  3502. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3503. ###人物关系
  3504. 阿雪与梁萧之间存在兄妹之情。
  3505. ###核心矛盾
  3506. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3507. ###主体列表
  3508. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3509. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3510. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3511. 姿态:站立。}{{甜心小美}}
  3512. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3513. 全景,正面拍摄,青年女性,亚洲人。
  3514. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3515. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3516. 姿态:站立。}{{阳光青年}}
  3517. ###美术风格
  3518. 基础画风风格词:厚涂古风
  3519. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3520. ###场景列表
  3521. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3522. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3523. 无人物。}
  3524. ###分镜剧本
  3525. ##第1幕:徐家老旧厨房 白天 室内
  3526. 分镜1
  3527. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3528. 场景:徐家老旧厨房
  3529. 构图设计:全景,低角度仰视
  3530. 运镜调度:手持拍摄
  3531. 配音角色:旁白
  3532. 出镜角色:许芸-校服装、徐母
  3533. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3534. 画面类型:普通画面
  3535. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3536. 分镜2
  3537. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3538. 场景:徐家老旧厨房
  3539. 构图设计:近景,徐母面部特写
  3540. 运镜调度:固定镜头
  3541. 配音角色:徐母
  3542. 出镜角色:徐母
  3543. 台词内容:问我夜不归宿死哪儿去了。
  3544. 画面类型:对口型
  3545. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3546. ##第2幕:徐家简陋客厅 黄昏 室内
  3547. 分镜3
  3548. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3549. 场景:徐家简陋客厅
  3550. 构图设计:全景,景深虚化
  3551. 运镜调度:固定镜头
  3552. 配音角色:旁白
  3553. 出镜角色:无
  3554. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3555. 画面类型:普通画面
  3556. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3557. 分镜4
  3558. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3559. 场景:徐家简陋客厅
  3560. 构图设计:特写,火车票
  3561. 运镜调度:固定镜头
  3562. 配音角色:旁白
  3563. 出镜角色:无
  3564. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3565. 画面类型:普通画面
  3566. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3567. "
  3568. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3569. 强制要求:\n
  3570. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3571. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3572. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3573. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3574. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3575. 普通要求:\n
  3576. 1.剧本名(必须生成)必须与文档内容高度相关
  3577. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3578. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3579. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3580. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3581. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3582. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3583. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3584. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3585. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3586. 4.{$mappedArtStyle_prompt}\n\n
  3587. 示例如下:\n
  3588. ###剧本名:西昆仑
  3589. ###故事梗概
  3590. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3591. ###剧本亮点
  3592. 亮点1:绝境奇药,生死一线
  3593. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3594. 亮点2:结拜兄妹,化解尴尬
  3595. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3596. 亮点3:纤发夺命,情愫暗涌
  3597. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3598. ###人物关系
  3599. 阿雪与梁萧之间存在兄妹之情。
  3600. ###核心矛盾
  3601. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3602. ###主体列表
  3603. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3604. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3605. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3606. 姿态:站立。}{{甜心小美}}
  3607. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3608. 全景,正面拍摄,青年女性,亚洲人。
  3609. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3610. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3611. 姿态:站立。}{{阳光青年}}
  3612. ###美术风格
  3613. 基础画风风格词:厚涂古风
  3614. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3615. ###场景列表
  3616. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3617. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3618. 无人物。}";
  3619. // 构建消息
  3620. $messages = [
  3621. [
  3622. 'role' => 'system',
  3623. 'content' => $systemPrompt
  3624. ],
  3625. [
  3626. 'role' => 'user',
  3627. 'content' => "以下是文档内容:
  3628. {$content}
  3629. 用户问题:
  3630. {$question}"
  3631. ]
  3632. ];
  3633. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3634. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3635. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3636. if ($model === 'deepseek-chat') {
  3637. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3638. $model = 'deepseek-v4-flash';
  3639. $thinkingMode = 'disabled';
  3640. } elseif ($model === 'deepseek-reasoner') {
  3641. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3642. $model = 'deepseek-v4-flash';
  3643. $thinkingMode = 'enabled';
  3644. }
  3645. $post_data = [
  3646. 'model' => $model,
  3647. 'messages' => $messages,
  3648. // 'max_tokens' => 8192,
  3649. 'temperature' => 0.7,
  3650. 'frequency_penalty' => 0,
  3651. 'presence_penalty' => 0,
  3652. 'response_format' => ['type' => 'text'],
  3653. 'thinking' => ['type'=>$thinkingMode],
  3654. 'stream' => true // 启用流式输出
  3655. ];
  3656. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3657. // 根据模型类型选择调用方法
  3658. $fullContent = '';
  3659. $fullReasoningContent = '';
  3660. $usage = [];
  3661. try {
  3662. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3663. // DeepSeek 官方模型使用 DeepSeek API
  3664. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3665. } else if (in_array($model, $this->gpt_text_models)) {
  3666. // GPT-5.4 模型使用 TokenRouter API
  3667. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3668. } else {
  3669. // 其他模型使用火山引擎API
  3670. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3671. }
  3672. // 验证返回值类型
  3673. if (!is_iterable($streamGenerator)) {
  3674. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3675. dLog('deepseek')->error('addChat流式生成器无效', [
  3676. 'generator_type' => $errorType,
  3677. 'model' => $model,
  3678. 'anime_id' => $anime_id
  3679. ]);
  3680. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3681. 'type' => $errorType,
  3682. 'model' => $model
  3683. ]);
  3684. yield [
  3685. 'type' => 'error',
  3686. 'script' => [],
  3687. 'episode' => [],
  3688. 'answer' => '',
  3689. 'reasoning' => '',
  3690. 'usage' => [],
  3691. 'error' => '接口返回数据异常,请重新请求'
  3692. ];
  3693. return;
  3694. }
  3695. // 处理流式输出
  3696. foreach ($streamGenerator as $chunk) {
  3697. if (isset($chunk['type'])) {
  3698. if ($chunk['type'] === 'done') {
  3699. // 最终结果
  3700. $fullContent = $chunk['full_content'];
  3701. $fullReasoningContent = $chunk['full_reasoning'];
  3702. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3703. } else {
  3704. // 逐块yield数据
  3705. yield $chunk;
  3706. }
  3707. }
  3708. }
  3709. } catch (\Exception $e) {
  3710. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3711. 'model' => $model,
  3712. 'anime_id' => $anime_id,
  3713. 'trace' => $e->getTraceAsString()
  3714. ]);
  3715. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3716. 'error' => $e->getMessage(),
  3717. 'model' => $model
  3718. ]);
  3719. yield [
  3720. 'type' => 'error',
  3721. 'script' => [],
  3722. 'episode' => [],
  3723. 'answer' => '',
  3724. 'reasoning' => '',
  3725. 'usage' => [],
  3726. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3727. ];
  3728. return;
  3729. }
  3730. dLog('deepseek')->info('完整内容: '.$fullContent);
  3731. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3732. // 处理完整内容并返回最终结果
  3733. $script_arr = [];
  3734. if ($fullContent) {
  3735. $script_arr = handleScriptContent($fullContent);
  3736. dLog('deepseek')->info('解析内容', $script_arr);
  3737. logDB('deepseek', 'info', '解析内容', $script_arr);
  3738. }
  3739. if (empty($script_arr['roles'])) {
  3740. // 未生成剧本相关内容,保存对话记录并返回提示
  3741. dLog('deepseek')->info('未生成剧本相关的内容');
  3742. try {
  3743. DB::beginTransaction();
  3744. $now = date('Y-m-d H:i:s');
  3745. // 保存对话记录
  3746. $records = [
  3747. [
  3748. 'uid' => $uid,
  3749. 'anime_id' => $anime_id,
  3750. 'sequence' => 0,
  3751. 'role' => 'user',
  3752. 'content' => $prompt,
  3753. 'created_at' => $now,
  3754. 'updated_at' => $now
  3755. ],
  3756. [
  3757. 'uid' => $uid,
  3758. 'anime_id' => $anime_id,
  3759. 'sequence' => 0,
  3760. 'role' => 'assistant',
  3761. // 'content' => $fullContent,
  3762. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3763. 'created_at' => $now,
  3764. 'updated_at' => $now
  3765. ]
  3766. ];
  3767. DB::table('mp_anime_records')->insert($records);
  3768. DB::commit();
  3769. } catch (\Exception $e) {
  3770. DB::rollBack();
  3771. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3772. }
  3773. yield [
  3774. 'type' => 'done',
  3775. 'script' => [],
  3776. 'episode' => [],
  3777. 'answer' => $fullContent,
  3778. 'reasoning' => $fullReasoningContent,
  3779. 'usage' => $usage,
  3780. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3781. ];
  3782. return;
  3783. }
  3784. // 如果需要生成原文内容,从script_arr中提取
  3785. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3786. $content = $script_arr['content'];
  3787. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3788. if (!$content) {
  3789. yield [
  3790. 'type' => 'done',
  3791. 'script' => [],
  3792. 'episode' => [],
  3793. 'answer' => $fullContent,
  3794. 'reasoning' => $fullReasoningContent,
  3795. 'usage' => $usage,
  3796. 'error' => '未生成剧本内容,请调整提示词再试'
  3797. ];
  3798. return;
  3799. }
  3800. }
  3801. // 替换美术风格
  3802. if ($mappedArtStyle !== '') {
  3803. $script_arr['art_style'] = $mappedArtStyle;
  3804. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3805. }
  3806. // 新建动漫
  3807. if ($user_anime_name == '新剧本策划') {
  3808. $anime_name = getProp($script_arr, 'script_name');
  3809. // if (!$anime_name) {
  3810. // // 未识别到剧本名,保存对话记录并返回提示
  3811. // dLog('deepseek')->info('未能识别到剧本名称');
  3812. // try {
  3813. // DB::beginTransaction();
  3814. // $now = date('Y-m-d H:i:s');
  3815. // // 保存对话记录
  3816. // $records = [
  3817. // [
  3818. // 'uid' => $uid,
  3819. // 'anime_id' => $anime_id,
  3820. // 'sequence' => 0,
  3821. // 'role' => 'user',
  3822. // 'content' => $prompt,
  3823. // 'created_at' => $now,
  3824. // 'updated_at' => $now
  3825. // ],
  3826. // [
  3827. // 'uid' => $uid,
  3828. // 'anime_id' => $anime_id,
  3829. // 'sequence' => 0,
  3830. // 'role' => 'assistant',
  3831. // 'content' => '未能生成剧本名称,请重试',
  3832. // 'created_at' => $now,
  3833. // 'updated_at' => $now
  3834. // ]
  3835. // ];
  3836. // DB::table('mp_anime_records')->insert($records);
  3837. // DB::commit();
  3838. // } catch (\Exception $e) {
  3839. // DB::rollBack();
  3840. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3841. // }
  3842. // yield [
  3843. // 'type' => 'done',
  3844. // 'script' => [],
  3845. // 'episode' => [],
  3846. // 'answer' => $fullContent,
  3847. // 'reasoning' => $fullReasoningContent,
  3848. // 'usage' => $usage,
  3849. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3850. // ];
  3851. // return;
  3852. // }
  3853. // 确认对话名称唯一性
  3854. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3855. $anime_name = $anime_name . '_' . date('YmdHis');
  3856. }
  3857. }else {
  3858. $anime_name = $user_anime_name;
  3859. }
  3860. $table_data = [
  3861. 'user_id' => $uid,
  3862. 'anime_name' => $anime_name,
  3863. 'model' => $model,
  3864. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3865. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3866. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3867. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3868. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3869. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3870. 'art_style_type' => $input_art_style,
  3871. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3872. 'status' => '解析完成',
  3873. 'content' => $content,
  3874. 'is_multi' => $is_multi,
  3875. 'ace_mode' => $ace_mode,
  3876. 'generate_status' => '待执行',
  3877. 'updated_at' => date('Y-m-d H:i:s')
  3878. ];
  3879. if ($table_data['content']) {
  3880. $chapters = splitContent($table_data['content']);
  3881. $chapter_count = count($chapters);
  3882. if ($chapter_count > 0) {
  3883. $table_data['start_episode_sequence'] = 1;
  3884. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3885. }
  3886. }
  3887. // 如果有剧本ID则进行绑定
  3888. if ($script_id) {
  3889. $table_data['script_id'] = $script_id;
  3890. }
  3891. $single_episode = [];
  3892. try {
  3893. DB::beginTransaction();
  3894. $now = date('Y-m-d H:i:s');
  3895. // 更新动漫大纲
  3896. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3897. if (!$boolen) {
  3898. dLog('deepseek')->info('动漫保存失败', $table_data);
  3899. Utils::throwError('20003:动漫保存失败');
  3900. }
  3901. // 保存对话记录
  3902. $records = [
  3903. [
  3904. 'uid' => $uid,
  3905. 'anime_id' => $anime_id,
  3906. 'sequence' => 0,
  3907. 'role' => 'user',
  3908. 'content' => $prompt,
  3909. 'created_at' => date('Y-m-d H:i:s'),
  3910. 'updated_at' => date('Y-m-d H:i:s')
  3911. ],
  3912. [
  3913. 'uid' => $uid,
  3914. 'anime_id' => $anime_id,
  3915. 'sequence' => 0,
  3916. 'role' => 'assistant',
  3917. 'content' => $fullContent,
  3918. 'created_at' => date('Y-m-d H:i:s'),
  3919. 'updated_at' => date('Y-m-d H:i:s')
  3920. ]
  3921. ];
  3922. // 保存对话记录
  3923. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3924. if (!$boolen3) {
  3925. Utils::throwError('20003:对话记录保存失败');
  3926. }
  3927. if ($is_single) {
  3928. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3929. if (empty($episode_arr['acts'])) {
  3930. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3931. }
  3932. $saveResult = $this->saveEpisodeVersionData(
  3933. $anime_id,
  3934. 1,
  3935. $episode_arr,
  3936. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3937. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3938. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3939. null,
  3940. null,
  3941. false,
  3942. $content,
  3943. $now
  3944. );
  3945. $single_episode = $saveResult['episode'];
  3946. $episode_id = $saveResult['episode_id'];
  3947. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3948. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3949. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3950. 'props' => json_encode($saveResult['merged_props'], 256),
  3951. 'updated_at' => $now
  3952. ]);
  3953. if ($boolen5 === false) {
  3954. Utils::throwError('20003:单剧集主表资源同步失败');
  3955. }
  3956. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3957. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3958. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3959. $episode_record_content = '确认分镜大纲';
  3960. if ($content !== '') {
  3961. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3962. }
  3963. $episode_records = [
  3964. [
  3965. 'uid' => $uid,
  3966. 'anime_id' => $anime_id,
  3967. 'role' => 'user',
  3968. 'content' => $episode_record_content,
  3969. 'sequence' => 1,
  3970. 'episode_id' => $episode_id,
  3971. 'created_at' => $now,
  3972. 'updated_at' => $now
  3973. ],
  3974. [
  3975. 'uid' => $uid,
  3976. 'anime_id' => $anime_id,
  3977. 'role' => 'assistant',
  3978. 'content' => $fullContent,
  3979. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3980. 'sequence' => 1,
  3981. 'episode_id' => $episode_id,
  3982. 'created_at' => $now,
  3983. 'updated_at' => $now
  3984. ]
  3985. ];
  3986. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3987. if (!$boolen4) {
  3988. Utils::throwError('20003:单剧集分镜记录保存失败');
  3989. }
  3990. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  3991. if ($is_single && !empty($single_episode)) {
  3992. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3993. 'anime_id' => $anime_id,
  3994. 'episode_id' => $episode_id ?? 0,
  3995. ]);
  3996. }
  3997. }
  3998. }catch (\Exception $e) {
  3999. DB::rollBack();
  4000. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4001. yield [
  4002. 'type' => 'done',
  4003. 'answer' => $fullContent,
  4004. 'reasoning' => $fullReasoningContent,
  4005. 'usage' => $usage,
  4006. 'error' => $e->getMessage(),
  4007. ];
  4008. return;
  4009. }
  4010. DB::commit();
  4011. dLog('deepseek')->info('保存完毕');
  4012. if ($is_single && !empty($single_episode)) {
  4013. // $this->batchSetGlobalRoleImg([
  4014. // 'anime_id' => $anime_id,
  4015. // ]);
  4016. // $this->batchSetGlobalSceneImg([
  4017. // 'anime_id' => $anime_id,
  4018. // ]);
  4019. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4020. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4021. }
  4022. $table_data['anime_id'] = $anime_id;
  4023. $table_data['roles'] = json_decode($table_data['roles'], true);
  4024. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4025. // $table_data['episodes'] = $script_arr['episodes'];
  4026. unset($table_data['created_at']);
  4027. unset($table_data['updated_at']);
  4028. unset($table_data['status']);
  4029. dLog('deepseek')->info('开始返回');
  4030. yield [
  4031. 'type' => 'done',
  4032. 'script' => $table_data,
  4033. 'episode' => $single_episode,
  4034. 'answer' => $fullContent,
  4035. 'reasoning' => $fullReasoningContent,
  4036. 'usage' => $usage
  4037. ];
  4038. }
  4039. public function reGenerateAnime($data) {
  4040. $uid = Site::getUid();
  4041. $file = getProp($data, 'file');
  4042. $content = getProp($data, 'content', '');
  4043. $bid = getProp($data, 'bid', 0);
  4044. $script_id = getProp($data, 'script_id', 0);
  4045. $anime_id = getProp($data, 'anime_id');
  4046. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4047. if (!$anime) {
  4048. Utils::throwError('20003:该对话不存在');
  4049. }
  4050. $user_anime_name = getProp($anime, 'anime_name');
  4051. $prompt = getProp($data, 'prompt');
  4052. // 处理文本模型
  4053. $model = getProp($data, 'model');
  4054. if (!$model) {
  4055. // 用户没有输入,从anime表获取
  4056. $model = getProp($anime, 'model');
  4057. if (!$model) {
  4058. // anime表也没有,使用默认值
  4059. $model = 'doubao-seed-2-0-mini-260215';
  4060. }
  4061. }
  4062. // 验证模型是否在可用模型表中
  4063. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4064. $model = 'doubao-seed-2-0-mini-260215';
  4065. }
  4066. $is_multi = getProp($anime, 'is_multi', 1);
  4067. $is_single = (int)$is_multi !== 1;
  4068. // 积分余额预检(仅单剧集模式收费)
  4069. if ($is_single) {
  4070. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4071. }
  4072. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4073. if ($is_single) {
  4074. $episode_exists = DB::table('mp_anime_episodes')
  4075. ->where('anime_id', $anime_id)
  4076. ->where('sequence', 1)
  4077. ->exists();
  4078. if ($episode_exists) {
  4079. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4080. }
  4081. }
  4082. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4083. if ($prompt) {
  4084. $question .= "本次修改要求如下:\n{$prompt}";
  4085. }
  4086. // 提取文件内容
  4087. if ($file) {
  4088. $content = $this->extractFileContent($file);
  4089. if (!$content) {
  4090. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4091. }
  4092. } elseif ($script_id) {
  4093. $content = $this->getContentByScriptId($script_id);
  4094. if (!$content) {
  4095. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4096. }
  4097. } elseif ($bid) {
  4098. $content = $this->getContentByBid($bid);
  4099. if (!$content) {
  4100. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4101. }
  4102. } elseif ($content) {
  4103. $content = filterContent($content);
  4104. }else {
  4105. $content = filterContent(getProp($anime, 'content'));
  4106. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4107. $need_generate_content = true;
  4108. }
  4109. }
  4110. // 判断是否需要生成原文内容
  4111. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4112. // 如果需要生成原文内容,添加额外的要求
  4113. $content_generation_requirement = $need_generate_content
  4114. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4115. : "";
  4116. // 美术风格
  4117. $input_art_style = getProp($anime, 'art_style');
  4118. if (!$input_art_style) {
  4119. $input_art_style = getProp($data, 'art_style');
  4120. }
  4121. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4122. // 美术风格
  4123. if (!$mappedArtStyle) {
  4124. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4125. }else {
  4126. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4127. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4128. }else {
  4129. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4130. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4131. }
  4132. }
  4133. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4134. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4135. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4136. 中年女:邻居阿姨
  4137. 老年男:幽默大爷
  4138. 老年女:婆婆
  4139. 萌娃:奶气萌娃";
  4140. $system_message = ['role'=>'system', 'content'=>$is_single
  4141. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4142. 强制要求:
  4143. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4144. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4145. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4146. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4147. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4148. 普通要求:
  4149. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4150. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4151. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4152. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4153. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4154. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4155. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4156. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4157. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4158. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4159. 3.$mappedArtStyle_prompt\n\n
  4160. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4161. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4162. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4163. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4164. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4165. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4166. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4167. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4168. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4169. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4170. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4171. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4172. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4173. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4174. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4175. 示例如下:\n
  4176. ###剧本名:西昆仑
  4177. ###故事梗概
  4178. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4179. ###剧本亮点
  4180. 亮点1:绝境奇药,生死一线
  4181. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4182. 亮点2:结拜兄妹,化解尴尬
  4183. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4184. 亮点3:纤发夺命,情愫暗涌
  4185. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4186. ###人物关系
  4187. 阿雪与梁萧之间存在兄妹之情。
  4188. ###核心矛盾
  4189. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4190. ###主体列表
  4191. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4192. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4193. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4194. 姿态:站立。}{{甜心小美}}
  4195. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4196. 全景,正面拍摄,青年女性,亚洲人。
  4197. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4198. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4199. 姿态:站立。}{{阳光青年}}
  4200. ###美术风格
  4201. 基础画风风格词:厚涂古风
  4202. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4203. ###场景列表
  4204. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4205. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4206. 无人物。}
  4207. ###分镜剧本
  4208. ##第1幕:徐家老旧厨房 白天 室内
  4209. 分镜1
  4210. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4211. 场景:徐家老旧厨房
  4212. 构图设计:全景,低角度仰视
  4213. 运镜调度:手持拍摄
  4214. 配音角色:旁白
  4215. 出镜角色:许芸-校服装、徐母
  4216. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4217. 画面类型:普通画面
  4218. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4219. 分镜2
  4220. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4221. 场景:徐家老旧厨房
  4222. 构图设计:近景,徐母面部特写
  4223. 运镜调度:固定镜头
  4224. 配音角色:徐母
  4225. 出镜角色:徐母
  4226. 台词内容:问我夜不归宿死哪儿去了。
  4227. 画面类型:对口型
  4228. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4229. ##第2幕:徐家简陋客厅 黄昏 室内
  4230. 分镜3
  4231. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4232. 场景:徐家简陋客厅
  4233. 构图设计:全景,景深虚化
  4234. 运镜调度:固定镜头
  4235. 配音角色:旁白
  4236. 出镜角色:无
  4237. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4238. 画面类型:普通画面
  4239. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4240. 分镜4
  4241. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4242. 场景:徐家简陋客厅
  4243. 构图设计:特写,火车票
  4244. 运镜调度:固定镜头
  4245. 配音角色:旁白
  4246. 出镜角色:无
  4247. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4248. 画面类型:普通画面
  4249. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4250. "
  4251. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4252. 强制要求:\n
  4253. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4254. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4255. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4256. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4257. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4258. 普通要求:\n
  4259. 1.剧本名(必须生成)必须与文档内容高度相关
  4260. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4261. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4262. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4263. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4264. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4265. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4266. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4267. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4268. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4269. 4.$mappedArtStyle_prompt\n\n
  4270. 示例如下:\n
  4271. ###剧本名:西昆仑
  4272. ###故事梗概
  4273. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4274. ###剧本亮点
  4275. 亮点1:绝境奇药,生死一线
  4276. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4277. 亮点2:结拜兄妹,化解尴尬
  4278. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4279. 亮点3:纤发夺命,情愫暗涌
  4280. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4281. ###人物关系
  4282. 阿雪与梁萧之间存在兄妹之情。
  4283. ###核心矛盾
  4284. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4285. ###主体列表
  4286. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4287. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4288. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4289. 姿态:站立。}{{甜心小美}}
  4290. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4291. 全景,正面拍摄,青年女性,亚洲人。
  4292. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4293. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4294. 姿态:站立。}{{阳光青年}}
  4295. ###美术风格
  4296. 基础画风风格词:厚涂古风
  4297. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4298. ###场景列表
  4299. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4300. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4301. 无人物。}"];
  4302. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4303. $episode_count = $this->extractEpisodeNumber($prompt);
  4304. if ((int)getProp($anime, 'is_multi') !== 1) {
  4305. yield [
  4306. 'type' => 'done',
  4307. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4308. 'reasoning' => '',
  4309. 'usage' => []
  4310. ];
  4311. return;
  4312. }
  4313. if ($episode_count) {
  4314. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4315. $system_message = [
  4316. 'role' => 'system',
  4317. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4318. 强制要求:\n
  4319. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4320. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4321. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4322. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4323. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4324. 普通要求:\n
  4325. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4326. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4327. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4328. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4329. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4330. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4331. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4332. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4333. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4334. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4335. 示例如下:\n
  4336. ###剧本名:西昆仑
  4337. ###故事梗概
  4338. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4339. ###剧本亮点
  4340. 亮点1:绝境奇药,生死一线
  4341. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4342. 亮点2:结拜兄妹,化解尴尬
  4343. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4344. 亮点3:纤发夺命,情愫暗涌
  4345. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4346. ###人物关系
  4347. 阿雪与梁萧之间存在兄妹之情。
  4348. ###核心矛盾
  4349. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4350. ###主体列表
  4351. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4352. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4353. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4354. 姿态:站立。}{{甜心小美}}
  4355. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4356. 全景,正面拍摄,青年女性,亚洲人。
  4357. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4358. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4359. 姿态:站立。}{{阳光青年}}
  4360. ###美术风格
  4361. 基础画风风格词:厚涂古风
  4362. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4363. ###场景列表
  4364. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4365. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4366. 无人物。}
  4367. ###分集详细内容
  4368. ##第1章 重生
  4369. 我重生了。
  4370. 源于一个男人偏执的暗恋。
  4371. ##第2章 相救
  4372. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4373. 我眼睛扫向站在锅炉后的卞大伟。"
  4374. ];
  4375. // 构建消息
  4376. $messages = [
  4377. $system_message,
  4378. [
  4379. 'role' => 'user',
  4380. 'content' => "以下是文档内容:
  4381. {$content}
  4382. 用户问题:
  4383. {$question}"
  4384. ]
  4385. ];
  4386. }else {
  4387. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4388. // 构建消息
  4389. $messages = [
  4390. $system_message,
  4391. [
  4392. 'role' => 'user',
  4393. 'content' => "以下是文档内容:
  4394. {$content}
  4395. 用户问题:
  4396. {$question}"
  4397. ]
  4398. ];
  4399. }else {
  4400. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4401. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4402. return (array)$value;
  4403. })->toArray();
  4404. array_unshift($messages, $system_message);
  4405. $messages[] = [
  4406. 'role' => 'user',
  4407. 'content' => $prompt
  4408. ];
  4409. }
  4410. }
  4411. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4412. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4413. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4414. if ($model === 'deepseek-chat') {
  4415. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4416. $model = 'deepseek-v4-flash';
  4417. $thinkingMode = 'disabled';
  4418. } elseif ($model === 'deepseek-reasoner') {
  4419. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4420. $model = 'deepseek-v4-flash';
  4421. $thinkingMode = 'enabled';
  4422. }
  4423. $post_data = [
  4424. 'model' => $model,
  4425. 'messages' => $messages,
  4426. // 'max_tokens' => 8192,
  4427. 'temperature' => 0.7,
  4428. 'frequency_penalty' => 0,
  4429. 'presence_penalty' => 0,
  4430. 'response_format' => ['type' => 'text'],
  4431. 'thinking' => ['type' => $thinkingMode],
  4432. 'stream' => true // 启用流式输出
  4433. ];
  4434. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4435. // 根据模型类型选择调用方法
  4436. $fullContent = '';
  4437. $fullReasoningContent = '';
  4438. $usage = [];
  4439. // dd($post_data);
  4440. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4441. try {
  4442. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4443. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4444. } else if (in_array($model, $this->gpt_text_models)) {
  4445. // GPT-5.4 模型使用 TokenRouter API
  4446. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4447. } else {
  4448. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4449. }
  4450. // 验证返回值类型
  4451. if (!is_iterable($streamGenerator)) {
  4452. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4453. dLog('deepseek')->error('方法名流式生成器无效', [
  4454. 'generator_type' => $errorType,
  4455. 'model' => $model,
  4456. // 添加其他上下文信息
  4457. ]);
  4458. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4459. 'type' => $errorType,
  4460. 'model' => $model
  4461. ]);
  4462. yield [
  4463. 'type' => 'error',
  4464. // 根据方法返回相应的空数据结构
  4465. 'answer' => '',
  4466. 'reasoning' => '',
  4467. 'usage' => [],
  4468. 'error' => '接口返回数据异常,请重新请求'
  4469. ];
  4470. return;
  4471. }
  4472. // 处理流式输出
  4473. foreach ($streamGenerator as $chunk) {
  4474. if (isset($chunk['type'])) {
  4475. if ($chunk['type'] === 'done') {
  4476. $fullContent = $chunk['full_content'];
  4477. $fullReasoningContent = $chunk['full_reasoning'];
  4478. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4479. } else {
  4480. yield $chunk;
  4481. }
  4482. }
  4483. }
  4484. } catch (\Exception $e) {
  4485. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4486. 'model' => $model,
  4487. 'trace' => $e->getTraceAsString()
  4488. ]);
  4489. logDB('deepseek', 'error', '方法名流式处理失败', [
  4490. 'error' => $e->getMessage(),
  4491. 'model' => $model
  4492. ]);
  4493. yield [
  4494. 'type' => 'error',
  4495. // 根据方法返回相应的空数据结构
  4496. 'answer' => '',
  4497. 'reasoning' => '',
  4498. 'usage' => [],
  4499. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4500. ];
  4501. return;
  4502. }
  4503. dLog('deepseek')->info('完整内容: '.$fullContent);
  4504. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4505. // 处理完整内容并返回最终结果
  4506. $script_arr = [];
  4507. if ($fullContent) {
  4508. $script_arr = handleScriptContent($fullContent);
  4509. dLog('deepseek')->info('解析内容', $script_arr);
  4510. logDB('deepseek', 'info', '解析内容', $script_arr);
  4511. }
  4512. if (empty($script_arr['roles'])) {
  4513. // 未生成剧本相关内容,保存对话记录并返回提示
  4514. dLog('deepseek')->info('未生成剧本相关的内容');
  4515. try {
  4516. $now = date('Y-m-d H:i:s');
  4517. // 保存对话记录
  4518. $records = [
  4519. [
  4520. 'uid' => $uid,
  4521. 'anime_id' => $anime_id,
  4522. 'sequence' => 0,
  4523. 'role' => 'user',
  4524. 'content' => $prompt,
  4525. 'created_at' => $now,
  4526. 'updated_at' => $now
  4527. ],
  4528. [
  4529. 'uid' => $uid,
  4530. 'anime_id' => $anime_id,
  4531. 'sequence' => 0,
  4532. 'role' => 'assistant',
  4533. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4534. 'created_at' => $now,
  4535. 'updated_at' => $now
  4536. ]
  4537. ];
  4538. DB::table('mp_anime_records')->insert($records);
  4539. } catch (\Exception $e) {
  4540. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4541. }
  4542. yield [
  4543. 'type' => 'done',
  4544. 'script' => [],
  4545. 'episode' => [],
  4546. 'answer' => $fullContent,
  4547. 'reasoning' => $fullReasoningContent,
  4548. 'usage' => $usage,
  4549. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4550. ];
  4551. return;
  4552. }
  4553. // 替换美术风格
  4554. if ($mappedArtStyle !== '') {
  4555. $script_arr['art_style'] = $mappedArtStyle;
  4556. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4557. }
  4558. if ($user_anime_name != '新剧本策划') {
  4559. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4560. // 确认对话名称唯一性
  4561. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4562. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4563. }
  4564. }else {
  4565. $anime_name = $user_anime_name;
  4566. }
  4567. $table_data = [
  4568. 'user_id' => $uid,
  4569. 'model' => $model,
  4570. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4571. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4572. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4573. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4574. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4575. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4576. 'art_style_type' => $input_art_style,
  4577. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4578. 'status' => '解析完成',
  4579. 'generate_status' => '待执行',
  4580. 'updated_at' => date('Y-m-d H:i:s')
  4581. ];
  4582. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4583. // 如果是修改集数,则将content内容更新(会改变原文)
  4584. if (isset($episode_count) && $episode_count > 0) {
  4585. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4586. $table_data['start_episode_sequence'] = 1;
  4587. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4588. }else {
  4589. // 如果需要生成原文内容,从script_arr中提取
  4590. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4591. $table_data['content'] = $script_arr['content'];
  4592. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4593. if (!$table_data['content']) {
  4594. yield [
  4595. 'type' => 'done',
  4596. 'script' => [],
  4597. 'episode' => [],
  4598. 'answer' => $fullContent,
  4599. 'reasoning' => $fullReasoningContent,
  4600. 'usage' => $usage,
  4601. 'error' => '未生成剧本内容,请调整提示词再试'
  4602. ];
  4603. return;
  4604. }
  4605. }
  4606. if (isset($table_data['content']) && $table_data['content']) {
  4607. $chapters = splitContent($table_data['content']);
  4608. $chapter_count = count($chapters);
  4609. if ($chapter_count > 0) {
  4610. $table_data['start_episode_sequence'] = 1;
  4611. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4612. }
  4613. }
  4614. }
  4615. $single_episode = [];
  4616. try {
  4617. DB::beginTransaction();
  4618. $now = date('Y-m-d H:i:s');
  4619. // 更新动漫大纲
  4620. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4621. if (!$boolen) {
  4622. dLog('deepseek')->info('对话修改失败', $table_data);
  4623. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4624. Utils::throwError('20003:对话修改失败');
  4625. }
  4626. // 保存对话记录
  4627. $records = [
  4628. [
  4629. 'uid' => $uid,
  4630. 'anime_id' => $anime_id,
  4631. 'sequence' => 0,
  4632. 'role' => 'user',
  4633. 'content' => $prompt,
  4634. 'created_at' => $now,
  4635. 'updated_at' => $now
  4636. ],
  4637. [
  4638. 'uid' => $uid,
  4639. 'anime_id' => $anime_id,
  4640. 'sequence' => 0,
  4641. 'role' => 'assistant',
  4642. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4643. 'content' => $fullContent,
  4644. 'created_at' => $now,
  4645. 'updated_at' => $now
  4646. ]
  4647. ];
  4648. // 保存对话记录
  4649. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4650. if (!$boolen3) {
  4651. Utils::throwError('20003:对话记录保存失败');
  4652. }
  4653. // 单剧集模式:生成并保存剧集信息
  4654. if ($is_single) {
  4655. $anime_name = getProp($anime, 'anime_name', '未命名');
  4656. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4657. if (empty($episode_arr['acts'])) {
  4658. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4659. }
  4660. $saveResult = $this->saveEpisodeVersionData(
  4661. $anime_id,
  4662. 1,
  4663. $episode_arr,
  4664. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4665. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4666. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4667. null,
  4668. null,
  4669. false,
  4670. $content,
  4671. $now
  4672. );
  4673. $single_episode = $saveResult['episode'];
  4674. $episode_id = $saveResult['episode_id'];
  4675. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4676. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4677. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4678. 'props' => json_encode($saveResult['merged_props'], 256),
  4679. 'updated_at' => $now
  4680. ]);
  4681. if ($boolen5 === false) {
  4682. Utils::throwError('20003:单剧集主表资源同步失败');
  4683. }
  4684. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4685. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4686. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4687. $episode_record_content = '确认分镜大纲';
  4688. if ($content !== '') {
  4689. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4690. }
  4691. $episode_records = [
  4692. [
  4693. 'uid' => $uid,
  4694. 'anime_id' => $anime_id,
  4695. 'role' => 'user',
  4696. 'content' => $episode_record_content,
  4697. 'sequence' => 1,
  4698. 'episode_id' => $episode_id,
  4699. 'created_at' => $now,
  4700. 'updated_at' => $now
  4701. ],
  4702. [
  4703. 'uid' => $uid,
  4704. 'anime_id' => $anime_id,
  4705. 'role' => 'assistant',
  4706. 'content' => $fullContent,
  4707. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4708. 'sequence' => 1,
  4709. 'episode_id' => $episode_id,
  4710. 'created_at' => $now,
  4711. 'updated_at' => $now
  4712. ]
  4713. ];
  4714. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4715. if (!$boolen4) {
  4716. Utils::throwError('20003:单剧集分镜记录保存失败');
  4717. }
  4718. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  4719. if ($is_single && !empty($single_episode)) {
  4720. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4721. 'anime_id' => $anime_id,
  4722. 'episode_id' => $episode_id ?? 0,
  4723. ]);
  4724. }
  4725. }
  4726. }catch (\Exception $e) {
  4727. DB::rollBack();
  4728. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4729. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4730. yield [
  4731. 'type' => 'done',
  4732. 'answer' => $fullContent,
  4733. 'reasoning' => $fullReasoningContent,
  4734. 'usage' => $usage,
  4735. 'error' => $e->getMessage(),
  4736. ];
  4737. return;
  4738. }
  4739. DB::commit();
  4740. dLog('deepseek')->info('保存完毕');
  4741. if ($is_single && !empty($single_episode)) {
  4742. // $this->batchSetGlobalRoleImg([
  4743. // 'anime_id' => $anime_id,
  4744. // ]);
  4745. // $this->batchSetGlobalSceneImg([
  4746. // 'anime_id' => $anime_id,
  4747. // ]);
  4748. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4749. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4750. }
  4751. $table_data['anime_id'] = $anime_id;
  4752. $table_data['roles'] = json_decode($table_data['roles'], true);
  4753. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4754. unset($table_data['updated_at']);
  4755. unset($table_data['status']);
  4756. yield [
  4757. 'type' => 'done',
  4758. 'script' => $table_data,
  4759. 'episode' => $single_episode,
  4760. 'answer' => $fullContent,
  4761. 'reasoning' => $fullReasoningContent,
  4762. 'usage' => $usage
  4763. ];
  4764. }
  4765. public function chat($data) {
  4766. $uid = Site::getUid();
  4767. // 积分余额预检(不足直接报错)
  4768. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4769. $anime_id = getProp($data, 'anime_id');
  4770. $file = getProp($data, 'file');
  4771. $content = getProp($data, 'content', '');
  4772. $bid = getProp($data, 'bid', 0);
  4773. $script_id = getProp($data, 'script_id', 0);
  4774. $episode_number = getProp($data, 'episode_number', 1);
  4775. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4776. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4777. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4778. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4779. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4780. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4781. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4782. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4783. $roles = is_array($roles) ? $roles : [];
  4784. $scenes = is_array($scenes) ? $scenes : [];
  4785. // 获取最后一集序号
  4786. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4787. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4788. // 转换主体列表和场景列表的格式
  4789. // 获取参考主体或场景
  4790. if ((int)$episode_number === 1) {
  4791. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4792. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4793. }else {
  4794. $prev_episode_number = $episode_number - 1;
  4795. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4796. }
  4797. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4798. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4799. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4800. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4801. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4802. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4803. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4804. 中年女:邻居阿姨
  4805. 老年男:幽默大爷
  4806. 老年女:婆婆
  4807. 萌娃:奶气萌娃";
  4808. if ($roles_content) {
  4809. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4810. 主体范围:\n {$roles_content}\n
  4811. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4812. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4813. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4814. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4815. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4816. }else {
  4817. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4818. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4819. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4820. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4821. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4822. }
  4823. if ($scenes_content) {
  4824. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4825. 场景范围:\n {$scenes_content}\n
  4826. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4827. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4828. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4829. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4830. }else {
  4831. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4832. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4833. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4834. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4835. }
  4836. // 提取文件内容
  4837. if ($file) {
  4838. $uploaded_content = $this->extractFileContent($file);
  4839. if (!$uploaded_content) {
  4840. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4841. }
  4842. } elseif ($script_id) {
  4843. $uploaded_content = $this->getContentByScriptId($script_id);
  4844. if (!$uploaded_content) {
  4845. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4846. }
  4847. } elseif ($bid) {
  4848. $uploaded_content = $this->getContentByBid($bid);
  4849. if (!$uploaded_content) {
  4850. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4851. }
  4852. } elseif ($content) {
  4853. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4854. }
  4855. // elseif ($prompt) {
  4856. // $uploaded_content = filterContent($prompt);
  4857. // }
  4858. else {
  4859. $uploaded_content = '';
  4860. }
  4861. $input_art_style = getProp($anime, 'art_style');
  4862. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4863. // 美术风格
  4864. if (!$mappedArtStyle) {
  4865. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4866. }else {
  4867. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4868. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4869. }else {
  4870. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4871. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4872. }
  4873. }
  4874. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4875. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4876. // 强制要求:
  4877. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4878. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4879. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4880. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4881. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4882. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4883. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4884. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4885. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4886. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4887. // - 分镜要和场景列表、人物主体保持一致\n
  4888. // 普通要求:
  4889. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4890. // {$role_demo}
  4891. // {$scene_demo}
  4892. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4893. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4894. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4895. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4896. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4897. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4898. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4899. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4900. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4901. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4902. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4903. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4904. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4905. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4906. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4907. // 5.$mappedArtStyle_prompt\n\n
  4908. // 示例格式:\n
  4909. // 第1集:隐形的守护者
  4910. // ###故事梗概
  4911. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4912. // ###美术风格
  4913. // 基础画风风格词:韩漫二次元
  4914. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4915. // ###主体列表
  4916. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4917. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4918. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4919. // ###场景列表
  4920. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4921. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4922. // 无人物。}
  4923. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4924. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4925. // 无人物。}
  4926. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4927. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4928. // 无人物。}
  4929. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4930. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4931. // 无人物。}
  4932. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4933. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4934. // 无人物。}
  4935. // ###分镜剧本
  4936. // ##第1幕:徐家老旧厨房 白天 室内
  4937. // 分镜1
  4938. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4939. // 场景:徐家老旧厨房
  4940. // 构图设计:全景,低角度仰视
  4941. // 运镜调度:手持拍摄
  4942. // 配音角色:旁白
  4943. // 出镜角色:许芸-校服装、徐母
  4944. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4945. // 画面类型:普通画面
  4946. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4947. // 分镜2
  4948. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4949. // 场景:徐家老旧厨房
  4950. // 构图设计:近景,徐母面部特写
  4951. // 运镜调度:固定镜头
  4952. // 配音角色:徐母
  4953. // 出镜角色:徐母
  4954. // 台词内容:问我夜不归宿死哪儿去了。
  4955. // 画面类型:对口型
  4956. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4957. // ##第2幕:徐家简陋客厅 黄昏 室内
  4958. // 分镜3
  4959. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4960. // 场景:徐家简陋客厅
  4961. // 构图设计:全景,景深虚化
  4962. // 运镜调度:固定镜头
  4963. // 配音角色:旁白
  4964. // 出镜角色:无
  4965. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4966. // 画面类型:普通画面
  4967. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4968. // 分镜4
  4969. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4970. // 场景:徐家简陋客厅
  4971. // 构图设计:特写,火车票
  4972. // 运镜调度:固定镜头
  4973. // 配音角色:旁白
  4974. // 出镜角色:无
  4975. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4976. // 画面类型:普通画面
  4977. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4978. // \n\n";
  4979. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4980. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4981. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4982. 普通要求:
  4983. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4984. {$role_demo}
  4985. {$scene_demo}
  4986. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4987. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4988. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4989. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4990. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4991. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4992. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4993. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4994. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4995. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4996. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4997. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4998. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4999. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5000. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5001. 5.$mappedArtStyle_prompt
  5002. 6.《情绪-视听语言映射表》:
  5003. 6.1 场景空间与时间心理学 (Scene & Temporality)
  5004. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5005. -----|---------|------------|----------------
  5006. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  5007. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  5008. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  5009. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  5010. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  5011. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5012. -----|---------|------------|----------------
  5013. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  5014. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  5015. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  5016. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  5017. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  5018. --------|---------|--------------|-------------
  5019. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  5020. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  5021. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  5022. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  5023. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5024. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5025. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5026. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5027. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  5028. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  5029. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5030. -----|---------|------------|------------
  5031. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5032. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5033. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5034. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5035. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5036. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5037. --------|---------|--------------|----------
  5038. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5039. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5040. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5041. 6.6 声音设计与潜意识影响 (Soundscape)
  5042. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5043. -----|---------|------------|------------------
  5044. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5045. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5046. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5047. 理论基石:
  5048. - The Five C's of Cinematography by Joseph V. Mascelli
  5049. - Film Art: An Introduction by David Bordwell
  5050. - Sight, Sound, Motion by Herbert Zettl
  5051. - Notes on the Cinematograph by Robert Bresson
  5052. \n\n
  5053. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5054. 示例格式:\n
  5055. 第1集:隐形的守护者
  5056. ###故事梗概
  5057. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5058. ###美术风格
  5059. 基础画风风格词:韩漫二次元
  5060. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5061. ###主体列表
  5062. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5063. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5064. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5065. ###场景列表
  5066. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5067. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5068. 无人物。}
  5069. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5070. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5071. 无人物。}
  5072. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5073. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5074. 无人物。}
  5075. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5076. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5077. 无人物。}
  5078. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5079. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5080. 无人物。}
  5081. ###分镜剧本
  5082. ##第1幕:徐家老旧厨房 白天 室内
  5083. 分镜1
  5084. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5085. 场景:徐家老旧厨房
  5086. 构图设计:全景,低角度仰视
  5087. 运镜调度:手持拍摄
  5088. 配音角色:旁白
  5089. 出镜角色:许芸-校服装、徐母
  5090. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5091. 画面类型:普通画面
  5092. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5093. 分镜2
  5094. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5095. 场景:徐家老旧厨房
  5096. 构图设计:近景,徐母面部特写
  5097. 运镜调度:固定镜头
  5098. 配音角色:徐母
  5099. 出镜角色:徐母
  5100. 台词内容:问我夜不归宿死哪儿去了。
  5101. 画面类型:对口型
  5102. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5103. ##第2幕:徐家简陋客厅 黄昏 室内
  5104. 分镜3
  5105. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5106. 场景:徐家简陋客厅
  5107. 构图设计:全景,景深虚化
  5108. 运镜调度:固定镜头
  5109. 配音角色:旁白
  5110. 出镜角色:无
  5111. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5112. 画面类型:普通画面
  5113. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5114. 分镜4
  5115. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5116. 场景:徐家简陋客厅
  5117. 构图设计:特写,火车票
  5118. 运镜调度:固定镜头
  5119. 配音角色:旁白
  5120. 出镜角色:无
  5121. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5122. 画面类型:普通画面
  5123. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5124. \n\n";
  5125. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5126. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5127. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5128. $prompt = $origin_prompt;
  5129. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5130. // 获取章节内容
  5131. $full_content = getProp($anime, 'content');
  5132. if ($uploaded_content) {
  5133. $full_content = $uploaded_content;
  5134. }
  5135. // 根据章节内容拆分章节
  5136. $chapters = splitContent($full_content);
  5137. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5138. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5139. $messages = [];
  5140. if ($prompt == '确认分镜大纲') {
  5141. // 暂时保留
  5142. $content = $chapter_content;
  5143. if ($is_single) $content = $full_content; // 单剧集使用全文
  5144. if (!$content) {
  5145. Utils::throwError('20003:章节内容无法获取,请确认');
  5146. }
  5147. $question = $is_single
  5148. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5149. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5150. // 构建消息
  5151. $messages[] =
  5152. [
  5153. 'role' => 'user',
  5154. 'content' => $question
  5155. ];
  5156. }else if ($prompt == '继续策划下一集') {
  5157. if ($is_single) {
  5158. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5159. }
  5160. $content = $chapter_content;
  5161. if (!$content) {
  5162. Utils::throwError('20003:章节内容无法获取,请确认');
  5163. }
  5164. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5165. // 获取上一集最后记录
  5166. $prev_sequence = $episode_number - 1;
  5167. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5168. // 构建消息
  5169. $messages[] =
  5170. [
  5171. 'role' => 'user',
  5172. 'content' => $question
  5173. ];
  5174. }else {
  5175. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5176. if (!$content) {
  5177. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5178. }
  5179. if (!$content) {
  5180. Utils::throwError('20003:章节内容无法获取,请确认');
  5181. }
  5182. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5183. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5184. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5185. if ($origin_prompt) {
  5186. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5187. }
  5188. $messages[] =
  5189. [
  5190. 'role' => 'user',
  5191. 'content' => $question
  5192. ];
  5193. }
  5194. // 处理文本模型
  5195. $model = getProp($data, 'model');
  5196. if (!$model) {
  5197. // 用户没有输入,从anime表获取
  5198. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5199. $model = getProp($anime, 'model');
  5200. if (!$model) {
  5201. // anime表也没有,使用默认值
  5202. $model = 'doubao-seed-2-0-mini-260215';
  5203. }
  5204. }
  5205. // 验证模型是否在可用模型表中
  5206. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5207. $model = 'doubao-seed-2-0-mini-260215';
  5208. }
  5209. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5210. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5211. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5212. if ($model === 'deepseek-chat') {
  5213. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5214. $model = 'deepseek-v4-flash';
  5215. $thinkingMode = 'disabled';
  5216. } elseif ($model === 'deepseek-reasoner') {
  5217. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5218. $model = 'deepseek-v4-flash';
  5219. $thinkingMode = 'enabled';
  5220. }
  5221. $post_data = [
  5222. 'model' => $model,
  5223. 'messages' => $messages,
  5224. // 'max_tokens' => 8192,
  5225. 'temperature' => 0.2,
  5226. 'frequency_penalty' => 0,
  5227. 'presence_penalty' => 0,
  5228. 'response_format' => ['type' => 'text'],
  5229. 'thinking' => ['type' => $thinkingMode],
  5230. 'stream' => true // 启用流式输出
  5231. ];
  5232. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5233. // 根据模型类型选择调用方法
  5234. $fullContent = '';
  5235. $fullReasoningContent = '';
  5236. $usage = [];
  5237. try {
  5238. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5239. // DeepSeek 官方模型使用 DeepSeek API
  5240. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5241. } else if (in_array($model, $this->gpt_text_models)) {
  5242. // GPT-5.4 模型使用 TokenRouter API
  5243. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5244. } else {
  5245. // 其他模型使用火山引擎API
  5246. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5247. }
  5248. // 验证返回值类型
  5249. if (!is_iterable($streamGenerator)) {
  5250. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5251. dLog('deepseek')->error('chat流式生成器无效', [
  5252. 'generator_type' => $errorType,
  5253. 'model' => $model,
  5254. 'anime_id' => $anime_id,
  5255. 'episode_number' => $episode_number
  5256. ]);
  5257. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5258. 'type' => $errorType,
  5259. 'model' => $model
  5260. ]);
  5261. yield [
  5262. 'type' => 'error',
  5263. 'episode' => [],
  5264. 'answer' => '',
  5265. 'reasoning' => '',
  5266. 'usage' => [],
  5267. 'error' => '接口返回数据异常,请重新请求'
  5268. ];
  5269. return;
  5270. }
  5271. // 处理流式输出
  5272. foreach ($streamGenerator as $chunk) {
  5273. if (isset($chunk['type'])) {
  5274. if ($chunk['type'] === 'done') {
  5275. // 最终结果
  5276. $fullContent = $chunk['full_content'];
  5277. $fullReasoningContent = $chunk['full_reasoning'];
  5278. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5279. } else {
  5280. // 逐块yield数据
  5281. yield $chunk;
  5282. }
  5283. }
  5284. }
  5285. } catch (\Exception $e) {
  5286. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5287. 'model' => $model,
  5288. 'anime_id' => $anime_id,
  5289. 'episode_number' => $episode_number,
  5290. 'trace' => $e->getTraceAsString()
  5291. ]);
  5292. logDB('deepseek', 'error', 'chat流式处理失败', [
  5293. 'error' => $e->getMessage(),
  5294. 'model' => $model
  5295. ]);
  5296. yield [
  5297. 'type' => 'error',
  5298. 'episode' => [],
  5299. 'answer' => '',
  5300. 'reasoning' => '',
  5301. 'usage' => [],
  5302. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5303. ];
  5304. return;
  5305. }
  5306. dLog('deepseek')->info('完整内容: '.$fullContent);
  5307. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5308. // 处理完整内容并返回最终结果
  5309. $episode_arr = handleEpisodeContent($fullContent);
  5310. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5311. if (empty($episode_arr['acts'])) {
  5312. // 未生成剧本相关内容,保存对话记录并返回提示
  5313. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5314. try {
  5315. $now = date('Y-m-d H:i:s');
  5316. // 保存对话记录
  5317. $records = [
  5318. [
  5319. 'uid' => $uid,
  5320. 'anime_id' => $anime_id,
  5321. 'sequence' => $episode_number,
  5322. 'role' => 'user',
  5323. 'content' => $prompt,
  5324. 'created_at' => $now,
  5325. 'updated_at' => $now
  5326. ],
  5327. [
  5328. 'uid' => $uid,
  5329. 'anime_id' => $anime_id,
  5330. 'sequence' => $episode_number,
  5331. 'role' => 'assistant',
  5332. 'content' => $fullContent,
  5333. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5334. 'created_at' => $now,
  5335. 'updated_at' => $now
  5336. ]
  5337. ];
  5338. DB::table('mp_anime_records')->insert($records);
  5339. } catch (\Exception $e) {
  5340. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5341. }
  5342. yield [
  5343. 'type' => 'done',
  5344. 'episode' => [],
  5345. 'answer' => $fullContent,
  5346. 'reasoning' => $fullReasoningContent,
  5347. 'usage' => $usage,
  5348. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5349. ];
  5350. return;
  5351. }
  5352. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5353. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5354. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5355. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5356. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5357. $existing_props = is_array($existing_props) ? $existing_props : [];
  5358. $now = date('Y-m-d H:i:s');
  5359. try {
  5360. DB::beginTransaction();
  5361. $saveResult = $this->saveEpisodeVersionData(
  5362. $anime_id,
  5363. $episode_number,
  5364. $episode_arr,
  5365. $existing_roles,
  5366. $existing_scenes,
  5367. $existing_props,
  5368. $current_episode,
  5369. $base_episode,
  5370. $is_regenerate_version,
  5371. $content,
  5372. $now
  5373. );
  5374. $episode = $saveResult['episode'];
  5375. $episode_id = $saveResult['episode_id'];
  5376. $merged_roles = $saveResult['merged_roles'];
  5377. $merged_scenes = $saveResult['merged_scenes'];
  5378. $merged_props = $saveResult['merged_props'];
  5379. $record_content = $origin_prompt;
  5380. if ($uploaded_content !== '') {
  5381. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5382. }
  5383. $records = [
  5384. [
  5385. 'uid' => $uid,
  5386. 'anime_id' => $anime_id,
  5387. 'role' => 'user',
  5388. 'content' => $record_content,
  5389. 'sequence' => $episode_number,
  5390. 'episode_id' => $episode_id,
  5391. 'created_at' => $now,
  5392. 'updated_at' => $now
  5393. ],
  5394. [
  5395. 'uid' => $uid,
  5396. 'anime_id' => $anime_id,
  5397. 'role' => 'assistant',
  5398. 'content' => $fullContent,
  5399. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5400. 'sequence' => $episode_number,
  5401. 'episode_id' => $episode_id,
  5402. 'created_at' => $now,
  5403. 'updated_at' => $now
  5404. ]
  5405. ];
  5406. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5407. if (!$boolen4) {
  5408. Utils::throwError('20003:对话记录保存失败');
  5409. }
  5410. // 保存模型和内容到anime表
  5411. $update_anime_data = [
  5412. 'model' => $model,
  5413. 'updated_at' => $now
  5414. ];
  5415. if ($uploaded_content) {
  5416. $update_anime_data['content'] = $uploaded_content;
  5417. }
  5418. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5419. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5420. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5421. 'anime_id' => $anime_id,
  5422. 'episode_number' => $episode_number,
  5423. 'model' => $model,
  5424. ]);
  5425. }catch (\Exception $e) {
  5426. DB::rollBack();
  5427. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5428. yield [
  5429. 'type' => 'done',
  5430. 'answer' => $fullContent,
  5431. 'reasoning' => $fullReasoningContent,
  5432. 'usage' => $usage,
  5433. 'error' => $e->getMessage(),
  5434. ];
  5435. return;
  5436. }
  5437. DB::commit();
  5438. if ($is_global_generate_pics) {
  5439. // // 批量生成全局角色图片
  5440. // $this->batchSetGlobalRoleImg([
  5441. // 'anime_id' => $anime_id,
  5442. // ], true);
  5443. // // 批量生成全局场景图片
  5444. // $this->batchSetGlobalSceneImg([
  5445. // 'anime_id' => $anime_id,
  5446. // ], true);
  5447. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5448. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5449. }
  5450. $episode['episode_id'] = $episode_id;
  5451. $episode['roles'] = $merged_roles;
  5452. $episode['scenes'] = $merged_scenes;
  5453. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5454. yield [
  5455. 'type' => 'done',
  5456. 'episode' => $episode,
  5457. 'answer' => $fullContent,
  5458. 'reasoning' => $fullReasoningContent,
  5459. 'usage' => $usage
  5460. ];
  5461. }
  5462. public function addChatForAce($data) {
  5463. $uid = Site::getUid();
  5464. $anime_id = getProp($data, 'anime_id');
  5465. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5466. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5467. if (!$anime) Utils::throwError('20003:对话不存在');
  5468. $file = getProp($data, 'file');
  5469. $content = getProp($data, 'content', '');
  5470. $bid = getProp($data, 'bid', 0);
  5471. $script_id = getProp($data, 'script_id', 0);
  5472. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5473. $prompt = getProp($data, 'prompt');
  5474. $is_multi = getProp($anime, 'is_multi');
  5475. $is_single = (int)$is_multi !== 1;
  5476. // 积分余额预检(仅单剧集模式收费)
  5477. if ($is_single) {
  5478. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5479. }
  5480. $extra_products = getProp($data, 'products', []);
  5481. if (!$extra_products) {
  5482. $extra_products = getProp($anime, 'extra_products');
  5483. if ($extra_products) {
  5484. $extra_products = json_decode($extra_products, true);
  5485. }else {
  5486. $extra_products = [];
  5487. }
  5488. }else {
  5489. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5490. }
  5491. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5492. $anime_script_id = getProp($anime, 'script_id');
  5493. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5494. $cpid = Site::getCpid();
  5495. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5496. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5497. ->where('mapping.script_id', $anime_script_id)
  5498. ->where('product.cpid', $cpid)
  5499. ->where('product.is_deleted', 0);
  5500. $mappings = $script_products_mappings->select(
  5501. 'mapping.product_id',
  5502. 'mapping.episode_number',
  5503. 'product.product_name',
  5504. 'product.type',
  5505. 'product.product',
  5506. 'product.pic_prompt',
  5507. 'product.url',
  5508. 'product.pic_task_id',
  5509. 'product.pic_task_status',
  5510. 'product.three_view_image_url'
  5511. )
  5512. ->get();
  5513. // 按 product_id 分组,合并 episode_number
  5514. $productMap = [];
  5515. foreach ($mappings as $item) {
  5516. $product_id = $item->product_id;
  5517. $product_name = $item->product_name;
  5518. // 处理product_name两边的符号
  5519. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5520. if (!isset($productMap[$product_id])) {
  5521. $productMap[$product_id] = [
  5522. 'product_id' => $product_id,
  5523. 'product_name' => $product_name,
  5524. 'type' => (int)$item->type,
  5525. 'product' => (int)$item->product,
  5526. 'pic_prompt' => $item->pic_prompt,
  5527. 'url' => $item->url,
  5528. 'pic_task_id' => $item->pic_task_id,
  5529. 'pic_task_status' => $item->pic_task_status,
  5530. 'episode_numbers' => [],
  5531. ];
  5532. }
  5533. // 添加 episode_number(去重)
  5534. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5535. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5536. }
  5537. }
  5538. // 将查询到的剧本资产合并到extra_products中
  5539. // 先构建extra_products的索引(以product_id为key,用于去重)
  5540. $extraProductsMap = [];
  5541. foreach ($extra_products as $item) {
  5542. $key = getProp($item, 'product_id');
  5543. if ($key) {
  5544. $extraProductsMap[$key] = $item;
  5545. }
  5546. }
  5547. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5548. foreach ($productMap as $product) {
  5549. $product_id = $product['product_id'];
  5550. // 如果不存在则添加(不带episode_number信息)
  5551. if (!isset($extraProductsMap[$product_id])) {
  5552. $extraProductsMap[$product_id] = [
  5553. 'product_id' => $product['product_id'],
  5554. 'product_name' => $product['product_name'],
  5555. 'type' => $product['type'],
  5556. 'product' => $product['product'],
  5557. 'pic_prompt' => $product['pic_prompt'],
  5558. 'url' => $product['url'],
  5559. 'pic_task_id' => $product['pic_task_id'],
  5560. 'pic_task_status' => $product['pic_task_status'],
  5561. ];
  5562. }
  5563. }
  5564. // 重新赋值给extra_products
  5565. $extra_products = array_values($extraProductsMap);
  5566. }
  5567. $user_anime_name = getProp($anime, 'anime_name');
  5568. // 处理提示词
  5569. if ($prompt && $extra_products) {
  5570. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5571. foreach($extra_products as $item) {
  5572. $product_name = getProp($item, 'product_name');
  5573. if ($product_name) {
  5574. // 替换 {product_name} 为 product_name
  5575. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5576. }
  5577. }
  5578. }
  5579. // 处理文本模型
  5580. $model = getProp($data, 'model');
  5581. if (!$model) {
  5582. // 用户没有输入,从anime表获取
  5583. $model = getProp($anime, 'model');
  5584. if (!$model) {
  5585. // anime表也没有,使用默认值
  5586. $model = 'deepseek-v4-pro';
  5587. }
  5588. }
  5589. // 验证模型是否在可用模型表中
  5590. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5591. $model = 'deepseek-v4-pro';
  5592. }
  5593. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5594. if ($prompt) {
  5595. $question .= "本次修改要求如下:\n{$prompt}";
  5596. }
  5597. // if (!$file && !$content && !$bid) {
  5598. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5599. // }
  5600. // 提取文件内容
  5601. if ($file) {
  5602. $content = $this->extractFileContent($file);
  5603. if (!$content) {
  5604. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5605. }
  5606. } elseif ($script_id) {
  5607. $content = $this->getContentByScriptId($script_id);
  5608. if (!$content) {
  5609. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5610. }
  5611. } elseif ($bid) {
  5612. $content = $this->getContentByBid($bid);
  5613. if (!$content) {
  5614. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5615. }
  5616. } elseif ($content) {
  5617. $content = filterContent($content);
  5618. } else {
  5619. $content = getProp($anime, 'content');
  5620. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5621. $need_generate_content = true;
  5622. }
  5623. }
  5624. // 美术风格
  5625. $input_art_style = getProp($data, 'art_style');
  5626. if (!$input_art_style) {
  5627. $mappedArtStyle = getProp($anime, 'art_style');
  5628. }else {
  5629. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5630. }
  5631. // 判断是否需要生成原文内容
  5632. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5633. // 如果需要生成原文内容,添加额外的要求
  5634. $content_generation_requirement = $need_generate_content
  5635. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5636. : "";
  5637. // 美术风格
  5638. if (!$mappedArtStyle) {
  5639. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5640. }else {
  5641. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5642. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5643. }else {
  5644. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5645. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5646. }
  5647. }
  5648. // 构建主体、场景和道具提示词
  5649. $extra_role_prompt = "\n";
  5650. $extra_scene_prompt = "\n";
  5651. $extra_prop_prompt = "\n";
  5652. $ref_products = []; // 参考资产
  5653. if ($extra_products) {
  5654. foreach($extra_products as $item) {
  5655. $product = getProp($item, 'product');
  5656. $product_name = getProp($item, 'product_name');
  5657. if ($product_name == '旁白') continue;
  5658. $ref_products[$product_name] = $item;
  5659. $pic_prompt = getProp($item, 'pic_prompt');
  5660. if ((int)$product === 1) {
  5661. // 拼接角色信息
  5662. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5663. } elseif ((int)$product === 2) {
  5664. // 拼接场景信息
  5665. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5666. } elseif ((int)$product === 3) {
  5667. // 拼接道具信息
  5668. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5669. }
  5670. }
  5671. // 优化提示词,融入剧本
  5672. if (!empty(trim($extra_role_prompt))) {
  5673. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5674. }
  5675. if (!empty(trim($extra_scene_prompt))) {
  5676. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5677. }
  5678. if (!empty(trim($extra_prop_prompt))) {
  5679. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5680. }
  5681. }
  5682. if ($anime_script_id && $is_single) {
  5683. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5684. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5685. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5686. }else {
  5687. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5688. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5689. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5690. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5691. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5692. {$extra_role_prompt}";
  5693. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5694. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5695. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5696. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5697. {$extra_scene_prompt}";
  5698. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5699. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5700. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5701. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5702. {$extra_prop_prompt}";
  5703. }
  5704. $systemPrompt = $is_single
  5705. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5706. 强制要求:
  5707. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5708. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5709. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5710. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5711. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5712. 普通要求:
  5713. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5714. $role_demo
  5715. $scene_demo
  5716. $prop_demo
  5717. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5718. 5.1片段分割逻辑(优先级从高到低):
  5719. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5720. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5721. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5722. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5723. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5724. - 片段数量格式为: 片段数量:8
  5725. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5726. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5727. 5.3分镜结构:每个分镜包含以下字段:
  5728. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5729. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5730. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5731. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5732. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5733. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5734. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5735. - 运镜:场景+画面描述+运镜
  5736. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5737. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5738. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5739. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5740. 6.{$mappedArtStyle_prompt}\n\n
  5741. 示例如下:\n
  5742. ###剧本名:西昆仑
  5743. ###故事梗概
  5744. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5745. ###剧本亮点
  5746. 亮点1:绝境奇药,生死一线
  5747. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5748. 亮点2:结拜兄妹,化解尴尬
  5749. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5750. 亮点3:纤发夺命,情愫暗涌
  5751. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5752. ###人物关系
  5753. 阿雪与梁萧之间存在兄妹之情。
  5754. ###核心矛盾
  5755. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5756. ###主体列表
  5757. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5758. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5759. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5760. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5761. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5762. 全景,正面拍摄,青年女性,亚洲人。
  5763. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5764. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5765. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5766. ###美术风格
  5767. 基础画风风格词:厚涂古风
  5768. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5769. ###场景列表
  5770. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5771. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5772. 无人物。}
  5773. ###分段剧本
  5774. 片段数量:8
  5775. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5776. ##片段1
  5777. 时长:12s
  5778. 分镜1
  5779. 出场角色:刀疤脸
  5780. 场景:边境小镇街道
  5781. 出场道具:酒杯-高脚杯
  5782. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5783. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5784. 配音台词:
  5785. 背景音效:
  5786. 分镜2
  5787. 出场角色:刀疤脸
  5788. 场景:悦来酒馆
  5789. 出场道具:酒杯-高脚杯
  5790. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5791. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5792. 配音台词:
  5793. 背景音效:
  5794. 分镜3
  5795. 出场角色:刀疤脸
  5796. 场景:悦来酒馆
  5797. 出场道具:酒杯-高脚杯
  5798. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5799. 运镜:从中景推向令牌特写。
  5800. 配音台词:
  5801. 背景音效:
  5802. 分镜4
  5803. 出场角色:刀疤脸
  5804. 场景:悦来酒馆
  5805. 出场道具:酒杯-高脚杯
  5806. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5807. 运镜:极速推向酒水溅起的瞬间。
  5808. 配音台词:
  5809. 背景音效:
  5810. 分镜5
  5811. 出场角色:刀疤脸
  5812. 场景:悦来酒馆
  5813. 出场道具:酒杯-高脚杯
  5814. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5815. 运镜:固定机位,利用倾斜构图制造压迫感。
  5816. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5817. 背景音效:
  5818. \n\n"
  5819. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5820. 强制要求:\n
  5821. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5822. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5823. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5824. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5825. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5826. 普通要求:\n
  5827. 1.剧本名(必须生成)必须与文档内容高度相关
  5828. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5829. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5830. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5831. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5832. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5833. {$extra_role_prompt}
  5834. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5835. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5836. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5837. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5838. {$extra_scene_prompt}
  5839. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5840. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5841. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5842. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5843. {$extra_prop_prompt}
  5844. 5.{$mappedArtStyle_prompt}\n\n
  5845. 示例如下:\n
  5846. ###剧本名:西昆仑
  5847. ###故事梗概
  5848. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5849. ###剧本亮点
  5850. 亮点1:绝境奇药,生死一线
  5851. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5852. 亮点2:结拜兄妹,化解尴尬
  5853. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5854. 亮点3:纤发夺命,情愫暗涌
  5855. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5856. ###人物关系
  5857. 阿雪与梁萧之间存在兄妹之情。
  5858. ###核心矛盾
  5859. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5860. ###主体列表
  5861. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5862. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5863. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5864. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5865. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5866. 全景,正面拍摄,青年女性,亚洲人。
  5867. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5868. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5869. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5870. ###美术风格
  5871. 基础画风风格词:厚涂古风
  5872. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5873. ###场景列表
  5874. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5875. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5876. 无人物。}
  5877. ###道具列表
  5878. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5879. // 构建消息
  5880. $messages = [
  5881. [
  5882. 'role' => 'system',
  5883. 'content' => $systemPrompt
  5884. ],
  5885. [
  5886. 'role' => 'user',
  5887. 'content' => "以下是文档内容:
  5888. {$content}
  5889. 用户问题:
  5890. {$question}"
  5891. ]
  5892. ];
  5893. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5894. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5895. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5896. if ($model === 'deepseek-chat') {
  5897. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5898. $model = 'deepseek-v4-flash';
  5899. $thinkingMode = 'disabled';
  5900. } elseif ($model === 'deepseek-reasoner') {
  5901. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5902. $model = 'deepseek-v4-flash';
  5903. $thinkingMode = 'enabled';
  5904. }
  5905. $post_data = [
  5906. 'model' => $model,
  5907. 'messages' => $messages,
  5908. // 'max_tokens' => 8192,
  5909. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5910. 'frequency_penalty' => 0,
  5911. 'presence_penalty' => 0,
  5912. 'response_format' => ['type' => 'text'],
  5913. 'thinking' => ['type'=>$thinkingMode],
  5914. 'stream' => true // 启用流式输出
  5915. ];
  5916. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5917. // 根据模型类型选择调用方法
  5918. $fullContent = '';
  5919. $fullReasoningContent = '';
  5920. $usage = [];
  5921. try {
  5922. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5923. // DeepSeek 官方模型使用 DeepSeek API
  5924. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5925. } else if (in_array($model, $this->gpt_text_models)) {
  5926. // GPT-5.4 模型使用 TokenRouter API
  5927. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5928. } else {
  5929. // 其他模型使用火山引擎API
  5930. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5931. }
  5932. // 验证返回值类型
  5933. if (!is_iterable($streamGenerator)) {
  5934. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5935. dLog('deepseek')->error('addChat流式生成器无效', [
  5936. 'generator_type' => $errorType,
  5937. 'model' => $model,
  5938. 'anime_id' => $anime_id
  5939. ]);
  5940. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5941. 'type' => $errorType,
  5942. 'model' => $model
  5943. ]);
  5944. yield [
  5945. 'type' => 'error',
  5946. 'script' => [],
  5947. 'episode' => [],
  5948. 'answer' => '',
  5949. 'reasoning' => '',
  5950. 'usage' => [],
  5951. 'error' => '接口返回数据异常,请重新请求'
  5952. ];
  5953. return;
  5954. }
  5955. // 处理流式输出
  5956. foreach ($streamGenerator as $chunk) {
  5957. if (isset($chunk['type'])) {
  5958. if ($chunk['type'] === 'done') {
  5959. // 最终结果
  5960. $fullContent = $chunk['full_content'];
  5961. $fullReasoningContent = $chunk['full_reasoning'];
  5962. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5963. } else {
  5964. // 逐块yield数据
  5965. yield $chunk;
  5966. }
  5967. }
  5968. }
  5969. } catch (\Exception $e) {
  5970. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5971. 'model' => $model,
  5972. 'anime_id' => $anime_id,
  5973. 'trace' => $e->getTraceAsString()
  5974. ]);
  5975. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5976. 'error' => $e->getMessage(),
  5977. 'model' => $model
  5978. ]);
  5979. yield [
  5980. 'type' => 'error',
  5981. 'script' => [],
  5982. 'episode' => [],
  5983. 'answer' => '',
  5984. 'reasoning' => '',
  5985. 'usage' => [],
  5986. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5987. ];
  5988. return;
  5989. }
  5990. dLog('deepseek')->info('完整内容: '.$fullContent);
  5991. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5992. // 处理完整内容并返回最终结果
  5993. $script_arr = [];
  5994. if ($fullContent) {
  5995. $script_arr = handleScriptContentForAce($fullContent);
  5996. dLog('deepseek')->info('解析内容', $script_arr);
  5997. logDB('deepseek', 'info', '解析内容', $script_arr);
  5998. }
  5999. if (empty($script_arr['roles'])) {
  6000. // 未生成剧本相关内容,保存对话记录并返回提示
  6001. dLog('deepseek')->info('未生成剧本相关的内容');
  6002. try {
  6003. DB::beginTransaction();
  6004. $now = date('Y-m-d H:i:s');
  6005. // 保存对话记录
  6006. $records = [
  6007. [
  6008. 'uid' => $uid,
  6009. 'anime_id' => $anime_id,
  6010. 'sequence' => 0,
  6011. 'role' => 'user',
  6012. 'content' => $prompt,
  6013. 'created_at' => $now,
  6014. 'updated_at' => $now
  6015. ],
  6016. [
  6017. 'uid' => $uid,
  6018. 'anime_id' => $anime_id,
  6019. 'sequence' => 0,
  6020. 'role' => 'assistant',
  6021. // 'content' => $fullContent,
  6022. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6023. 'created_at' => $now,
  6024. 'updated_at' => $now
  6025. ]
  6026. ];
  6027. DB::table('mp_anime_records')->insert($records);
  6028. DB::commit();
  6029. } catch (\Exception $e) {
  6030. DB::rollBack();
  6031. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6032. }
  6033. yield [
  6034. 'type' => 'done',
  6035. 'script' => [],
  6036. 'episode' => [],
  6037. 'answer' => $fullContent,
  6038. 'reasoning' => $fullReasoningContent,
  6039. 'usage' => $usage,
  6040. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6041. ];
  6042. return;
  6043. }
  6044. // 如果需要生成原文内容,从script_arr中提取
  6045. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6046. $content = $script_arr['content'];
  6047. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6048. if (!$content) {
  6049. yield [
  6050. 'type' => 'done',
  6051. 'script' => [],
  6052. 'episode' => [],
  6053. 'answer' => $fullContent,
  6054. 'reasoning' => $fullReasoningContent,
  6055. 'usage' => $usage,
  6056. 'error' => '未生成剧本内容,请调整提示词再试'
  6057. ];
  6058. return;
  6059. }
  6060. }
  6061. // 替换美术风格
  6062. if ($mappedArtStyle !== '') {
  6063. $script_arr['art_style'] = $mappedArtStyle;
  6064. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6065. }
  6066. // 新建动漫
  6067. if ($user_anime_name == '新剧本策划') {
  6068. $anime_name = getProp($script_arr, 'script_name');
  6069. // if (!$anime_name) {
  6070. // // 未识别到剧本名,保存对话记录并返回提示
  6071. // dLog('deepseek')->info('未能识别到剧本名称');
  6072. // try {
  6073. // DB::beginTransaction();
  6074. // $now = date('Y-m-d H:i:s');
  6075. // // 保存对话记录
  6076. // $records = [
  6077. // [
  6078. // 'uid' => $uid,
  6079. // 'anime_id' => $anime_id,
  6080. // 'sequence' => 0,
  6081. // 'role' => 'user',
  6082. // 'content' => $prompt,
  6083. // 'created_at' => $now,
  6084. // 'updated_at' => $now
  6085. // ],
  6086. // [
  6087. // 'uid' => $uid,
  6088. // 'anime_id' => $anime_id,
  6089. // 'sequence' => 0,
  6090. // 'role' => 'assistant',
  6091. // 'content' => '未能生成剧本名称,请重试',
  6092. // 'created_at' => $now,
  6093. // 'updated_at' => $now
  6094. // ]
  6095. // ];
  6096. // DB::table('mp_anime_records')->insert($records);
  6097. // DB::commit();
  6098. // } catch (\Exception $e) {
  6099. // DB::rollBack();
  6100. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6101. // }
  6102. // yield [
  6103. // 'type' => 'done',
  6104. // 'script' => [],
  6105. // 'episode' => [],
  6106. // 'answer' => $fullContent,
  6107. // 'reasoning' => $fullReasoningContent,
  6108. // 'usage' => $usage,
  6109. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6110. // ];
  6111. // return;
  6112. // }
  6113. // 确认对话名称唯一性
  6114. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6115. $anime_name = $anime_name . '_' . date('YmdHis');
  6116. }
  6117. }else {
  6118. $anime_name = $user_anime_name;
  6119. }
  6120. $table_data = [
  6121. 'user_id' => $uid,
  6122. 'anime_name' => $anime_name,
  6123. 'model' => $model,
  6124. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6125. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6126. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6127. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6128. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6129. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6130. 'art_style_type' => $input_art_style,
  6131. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6132. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6133. 'status' => '解析完成',
  6134. 'content' => $content,
  6135. 'is_multi' => $is_multi,
  6136. 'ace_mode' => $ace_mode,
  6137. 'generate_status' => '待执行',
  6138. 'updated_at' => date('Y-m-d H:i:s')
  6139. ];
  6140. if ($table_data['content']) {
  6141. $chapters = splitContent($table_data['content']);
  6142. $chapter_count = count($chapters);
  6143. if ($chapter_count > 0) {
  6144. $table_data['start_episode_sequence'] = 1;
  6145. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6146. }
  6147. }
  6148. if ($extra_products) {
  6149. $table_data['extra_products'] = json_encode($extra_products, 256);
  6150. }
  6151. // 如果有剧本ID则进行绑定
  6152. if ($script_id) {
  6153. $table_data['script_id'] = $script_id;
  6154. }
  6155. $single_episode = [];
  6156. try {
  6157. DB::beginTransaction();
  6158. $now = date('Y-m-d H:i:s');
  6159. // 更新动漫大纲
  6160. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6161. if (!$boolen) {
  6162. dLog('deepseek')->info('动漫保存失败', $table_data);
  6163. Utils::throwError('20003:动漫保存失败');
  6164. }
  6165. // 保存对话记录
  6166. $records = [
  6167. [
  6168. 'uid' => $uid,
  6169. 'anime_id' => $anime_id,
  6170. 'sequence' => 0,
  6171. 'role' => 'user',
  6172. 'content' => $prompt,
  6173. 'created_at' => date('Y-m-d H:i:s'),
  6174. 'updated_at' => date('Y-m-d H:i:s')
  6175. ],
  6176. [
  6177. 'uid' => $uid,
  6178. 'anime_id' => $anime_id,
  6179. 'sequence' => 0,
  6180. 'role' => 'assistant',
  6181. 'content' => $fullContent,
  6182. 'created_at' => date('Y-m-d H:i:s'),
  6183. 'updated_at' => date('Y-m-d H:i:s')
  6184. ]
  6185. ];
  6186. // 保存对话记录
  6187. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6188. if (!$boolen3) {
  6189. Utils::throwError('20003:对话记录保存失败');
  6190. }
  6191. if ($is_single) {
  6192. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6193. if (empty($episode_arr['acts'])) {
  6194. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6195. }
  6196. $saveResult = $this->saveEpisodeVersionData(
  6197. $anime_id,
  6198. 1,
  6199. $episode_arr,
  6200. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6201. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6202. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6203. null,
  6204. null,
  6205. false,
  6206. $content,
  6207. $now,
  6208. $ref_products
  6209. );
  6210. $single_episode = $saveResult['episode'];
  6211. $episode_id = $saveResult['episode_id'];
  6212. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6213. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6214. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6215. 'props' => json_encode($saveResult['merged_props'], 256),
  6216. 'updated_at' => $now
  6217. ]);
  6218. if ($boolen5 === false) {
  6219. Utils::throwError('20003:单剧集主表资源同步失败');
  6220. }
  6221. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6222. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6223. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6224. $episode_record_content = '确认分镜大纲';
  6225. if ($content !== '') {
  6226. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6227. }
  6228. $episode_records = [
  6229. [
  6230. 'uid' => $uid,
  6231. 'anime_id' => $anime_id,
  6232. 'role' => 'user',
  6233. 'content' => $episode_record_content,
  6234. 'sequence' => 1,
  6235. 'episode_id' => $episode_id,
  6236. 'created_at' => $now,
  6237. 'updated_at' => $now
  6238. ],
  6239. [
  6240. 'uid' => $uid,
  6241. 'anime_id' => $anime_id,
  6242. 'role' => 'assistant',
  6243. 'content' => $fullContent,
  6244. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6245. 'sequence' => 1,
  6246. 'episode_id' => $episode_id,
  6247. 'created_at' => $now,
  6248. 'updated_at' => $now
  6249. ]
  6250. ];
  6251. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6252. if (!$boolen4) {
  6253. Utils::throwError('20003:单剧集分镜记录保存失败');
  6254. }
  6255. }
  6256. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6257. if ($is_single && !empty($single_episode)) {
  6258. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6259. 'anime_id' => $anime_id,
  6260. 'episode_id' => $episode_id ?? 0,
  6261. ]);
  6262. }
  6263. }catch (\Exception $e) {
  6264. DB::rollBack();
  6265. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6266. yield [
  6267. 'type' => 'done',
  6268. 'answer' => $fullContent,
  6269. 'reasoning' => $fullReasoningContent,
  6270. 'usage' => $usage,
  6271. 'error' => $e->getMessage(),
  6272. ];
  6273. return;
  6274. }
  6275. DB::commit();
  6276. dLog('deepseek')->info('保存完毕');
  6277. if ($is_single && !empty($single_episode)) {
  6278. // $this->batchSetGlobalRoleImg([
  6279. // 'anime_id' => $anime_id,
  6280. // ]);
  6281. // $this->batchSetGlobalSceneImg([
  6282. // 'anime_id' => $anime_id,
  6283. // ]);
  6284. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6285. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6286. }
  6287. $table_data['anime_id'] = $anime_id;
  6288. $table_data['roles'] = json_decode($table_data['roles'], true);
  6289. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6290. // $table_data['episodes'] = $script_arr['episodes'];
  6291. unset($table_data['created_at']);
  6292. unset($table_data['updated_at']);
  6293. unset($table_data['status']);
  6294. dLog('deepseek')->info('开始返回');
  6295. yield [
  6296. 'type' => 'done',
  6297. 'script' => $table_data,
  6298. 'episode' => $single_episode,
  6299. 'answer' => $fullContent,
  6300. 'reasoning' => $fullReasoningContent,
  6301. 'usage' => $usage
  6302. ];
  6303. }
  6304. public function reGenerateAnimeForAce($data) {
  6305. $uid = Site::getUid();
  6306. $file = getProp($data, 'file');
  6307. $content = getProp($data, 'content', '');
  6308. $bid = getProp($data, 'bid', 0);
  6309. $script_id = getProp($data, 'script_id', 0);
  6310. $anime_id = getProp($data, 'anime_id');
  6311. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6312. if (!$anime) {
  6313. Utils::throwError('20003:该对话不存在');
  6314. }
  6315. $is_multi = getProp($anime, 'is_multi', 1);
  6316. $is_single = (int)$is_multi !== 1;
  6317. // 积分余额预检(仅单剧集模式收费)
  6318. if ($is_single) {
  6319. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6320. }
  6321. $extra_products = getProp($data, 'products', []);
  6322. if (!$extra_products) {
  6323. $extra_products = getProp($anime, 'extra_products');
  6324. if ($extra_products) {
  6325. $extra_products = json_decode($extra_products, true);
  6326. }else {
  6327. $extra_products = [];
  6328. }
  6329. }else {
  6330. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6331. }
  6332. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6333. $anime_script_id = getProp($anime, 'script_id');
  6334. if ($anime_script_id && $is_single) {
  6335. $cpid = Site::getCpid();
  6336. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6337. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6338. ->where('mapping.script_id', $anime_script_id)
  6339. ->where('product.cpid', $cpid)
  6340. ->where('product.is_deleted', 0);
  6341. $mappings = $script_products_mappings->select(
  6342. 'mapping.product_id',
  6343. 'mapping.episode_number',
  6344. 'product.product_name',
  6345. 'product.type',
  6346. 'product.product',
  6347. 'product.pic_prompt',
  6348. 'product.url',
  6349. 'product.pic_task_id',
  6350. 'product.pic_task_status',
  6351. 'product.three_view_image_url'
  6352. )
  6353. ->get();
  6354. // 按 product_id 分组,合并 episode_number
  6355. $productMap = [];
  6356. foreach ($mappings as $item) {
  6357. $product_id = $item->product_id;
  6358. $product_name = $item->product_name;
  6359. // 处理product_name两边的符号
  6360. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6361. if (!isset($productMap[$product_id])) {
  6362. $productMap[$product_id] = [
  6363. 'product_id' => $product_id,
  6364. 'product_name' => $product_name,
  6365. 'type' => (int)$item->type,
  6366. 'product' => (int)$item->product,
  6367. 'pic_prompt' => $item->pic_prompt,
  6368. 'url' => $item->url,
  6369. 'pic_task_id' => $item->pic_task_id,
  6370. 'pic_task_status' => $item->pic_task_status,
  6371. 'episode_numbers' => [],
  6372. ];
  6373. }
  6374. // 添加 episode_number(去重)
  6375. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6376. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6377. }
  6378. }
  6379. // 将查询到的剧本资产合并到extra_products中
  6380. // 先构建extra_products的索引(以product_id为key,用于去重)
  6381. $extraProductsMap = [];
  6382. foreach ($extra_products as $item) {
  6383. $key = getProp($item, 'product_id');
  6384. if ($key) {
  6385. $extraProductsMap[$key] = $item;
  6386. }
  6387. }
  6388. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6389. foreach ($productMap as $product) {
  6390. $product_id = $product['product_id'];
  6391. // 如果不存在则添加(不带episode_number信息)
  6392. if (!isset($extraProductsMap[$product_id])) {
  6393. $extraProductsMap[$product_id] = [
  6394. 'product_id' => $product['product_id'],
  6395. 'product_name' => $product['product_name'],
  6396. 'type' => $product['type'],
  6397. 'product' => $product['product'],
  6398. 'pic_prompt' => $product['pic_prompt'],
  6399. 'url' => $product['url'],
  6400. 'pic_task_id' => $product['pic_task_id'],
  6401. 'pic_task_status' => $product['pic_task_status'],
  6402. ];
  6403. }
  6404. }
  6405. // 重新赋值给extra_products
  6406. $extra_products = array_values($extraProductsMap);
  6407. }
  6408. $user_anime_name = getProp($anime, 'anime_name');
  6409. $prompt = getProp($data, 'prompt');
  6410. // 处理提示词
  6411. if ($prompt && $extra_products) {
  6412. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6413. foreach($extra_products as $item) {
  6414. $product_name = getProp($item, 'product_name');
  6415. if ($product_name) {
  6416. // 替换 {product_name} 为 product_name
  6417. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6418. }
  6419. }
  6420. }
  6421. // 处理文本模型
  6422. $model = getProp($data, 'model');
  6423. if (!$model) {
  6424. // 用户没有输入,从anime表获取
  6425. $model = getProp($anime, 'model');
  6426. if (!$model) {
  6427. // anime表也没有,使用默认值
  6428. $model = 'deepseek-v4-pro';
  6429. }
  6430. }
  6431. // 验证模型是否在可用模型表中
  6432. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6433. $model = 'deepseek-v4-pro';
  6434. }
  6435. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6436. if ($is_single) {
  6437. $episode_exists = DB::table('mp_anime_episodes')
  6438. ->where('anime_id', $anime_id)
  6439. ->where('sequence', 1)
  6440. ->exists();
  6441. if ($episode_exists) {
  6442. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6443. }
  6444. }
  6445. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6446. if ($prompt) {
  6447. $question .= "本次修改要求如下:\n{$prompt}";
  6448. }
  6449. // 提取文件内容
  6450. if ($file) {
  6451. $content = $this->extractFileContent($file);
  6452. if (!$content) {
  6453. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6454. }
  6455. } elseif ($script_id) {
  6456. $content = $this->getContentByScriptId($script_id);
  6457. if (!$content) {
  6458. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6459. }
  6460. } elseif ($bid) {
  6461. $content = $this->getContentByBid($bid);
  6462. if (!$content) {
  6463. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6464. }
  6465. } elseif ($content) {
  6466. $content = filterContent($content);
  6467. }else {
  6468. $content = filterContent(getProp($anime, 'content'));
  6469. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6470. $need_generate_content = true;
  6471. }
  6472. }
  6473. // 判断是否需要生成原文内容
  6474. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6475. // 如果需要生成原文内容,添加额外的要求
  6476. $content_generation_requirement = $need_generate_content
  6477. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6478. : "";
  6479. // 美术风格
  6480. $input_art_style = getProp($data, 'art_style');
  6481. if (!$input_art_style) {
  6482. $mappedArtStyle = getProp($anime, 'art_style');
  6483. }else {
  6484. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6485. }
  6486. if (!$mappedArtStyle) {
  6487. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6488. }else {
  6489. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6490. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6491. }else {
  6492. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6493. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6494. }
  6495. }
  6496. // 构建主体、场景和道具提示词
  6497. $extra_role_prompt = "\n";
  6498. $extra_scene_prompt = "\n";
  6499. $extra_prop_prompt = "\n";
  6500. $ref_products = []; // 参考资产
  6501. if ($extra_products) {
  6502. foreach($extra_products as $item) {
  6503. $product = getProp($item, 'product');
  6504. $product_name = getProp($item, 'product_name');
  6505. if ($product_name == '旁白') continue;
  6506. $ref_products[$product_name] = $item;
  6507. $pic_prompt = getProp($item, 'pic_prompt');
  6508. if ((int)$product === 1) {
  6509. // 拼接角色信息
  6510. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6511. } elseif ((int)$product === 2) {
  6512. // 拼接场景信息
  6513. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6514. } elseif ((int)$product === 3) {
  6515. // 拼接道具信息
  6516. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6517. }
  6518. }
  6519. // 优化提示词,融入剧本
  6520. if (!empty(trim($extra_role_prompt))) {
  6521. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6522. }
  6523. if (!empty(trim($extra_scene_prompt))) {
  6524. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6525. }
  6526. if (!empty(trim($extra_prop_prompt))) {
  6527. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6528. }
  6529. }
  6530. if ($anime_script_id && $is_single) {
  6531. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6532. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6533. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6534. }else {
  6535. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6536. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6537. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6538. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6539. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6540. {$extra_role_prompt}";
  6541. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6542. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6543. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6544. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6545. {$extra_scene_prompt}";
  6546. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6547. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6548. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6549. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6550. {$extra_prop_prompt}";
  6551. }
  6552. $system_message = ['role'=>'system', 'content'=>$is_single
  6553. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6554. 强制要求:
  6555. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6556. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6557. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6558. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6559. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6560. 普通要求:
  6561. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6562. $role_demo
  6563. $scene_demo
  6564. $prop_demo
  6565. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6566. 5.1片段分割逻辑(优先级从高到低):
  6567. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6568. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6569. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6570. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6571. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6572. - 片段数量格式为: 片段数量:8
  6573. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6574. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6575. 5.3分镜结构:每个分镜包含以下字段:
  6576. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6577. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6578. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6579. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6580. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6581. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6582. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6583. - 运镜:场景+画面描述+运镜
  6584. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6585. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6586. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6587. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6588. 6.{$mappedArtStyle_prompt}\n\n
  6589. 示例如下:\n
  6590. ###剧本名:西昆仑
  6591. ###故事梗概
  6592. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6593. ###剧本亮点
  6594. 亮点1:绝境奇药,生死一线
  6595. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6596. 亮点2:结拜兄妹,化解尴尬
  6597. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6598. 亮点3:纤发夺命,情愫暗涌
  6599. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6600. ###人物关系
  6601. 阿雪与梁萧之间存在兄妹之情。
  6602. ###核心矛盾
  6603. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6604. ###主体列表
  6605. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6606. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6607. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6608. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6609. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6610. 全景,正面拍摄,青年女性,亚洲人。
  6611. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6612. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6613. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6614. ###美术风格
  6615. 基础画风风格词:厚涂古风
  6616. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6617. ###场景列表
  6618. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6619. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6620. 无人物。}
  6621. ###分段剧本
  6622. 片段数量:8
  6623. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6624. ##片段1
  6625. 时长:12s
  6626. 分镜1
  6627. 出场角色:刀疤脸
  6628. 场景:边境小镇街道
  6629. 出场道具:酒杯-高脚杯
  6630. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6631. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6632. 配音台词:
  6633. 背景音效:
  6634. 分镜2
  6635. 出场角色:刀疤脸
  6636. 场景:悦来酒馆
  6637. 出场道具:酒杯-高脚杯
  6638. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6639. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6640. 配音台词:
  6641. 背景音效:
  6642. 分镜3
  6643. 出场角色:刀疤脸
  6644. 场景:悦来酒馆
  6645. 出场道具:酒杯-高脚杯
  6646. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6647. 运镜:从中景推向令牌特写。
  6648. 配音台词:
  6649. 背景音效:
  6650. 分镜4
  6651. 出场角色:刀疤脸
  6652. 场景:悦来酒馆
  6653. 出场道具:酒杯-高脚杯
  6654. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6655. 运镜:极速推向酒水溅起的瞬间。
  6656. 配音台词:
  6657. 背景音效:
  6658. 分镜5
  6659. 出场角色:刀疤脸
  6660. 场景:悦来酒馆
  6661. 出场道具:酒杯-高脚杯
  6662. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6663. 运镜:固定机位,利用倾斜构图制造压迫感。
  6664. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6665. 背景音效:
  6666. \n\n"
  6667. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6668. 强制要求:\n
  6669. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6670. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6671. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6672. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6673. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6674. 普通要求:\n
  6675. 1.剧本名(必须生成)必须与文档内容高度相关
  6676. $role_demo
  6677. $scene_demo
  6678. $prop_demo
  6679. 5.{$mappedArtStyle_prompt}\n\n
  6680. 示例如下:\n
  6681. ###剧本名:西昆仑
  6682. ###故事梗概
  6683. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6684. ###剧本亮点
  6685. 亮点1:绝境奇药,生死一线
  6686. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6687. 亮点2:结拜兄妹,化解尴尬
  6688. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6689. 亮点3:纤发夺命,情愫暗涌
  6690. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6691. ###人物关系
  6692. 阿雪与梁萧之间存在兄妹之情。
  6693. ###核心矛盾
  6694. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6695. ###主体列表
  6696. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6697. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6698. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6699. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6700. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6701. 全景,正面拍摄,青年女性,亚洲人。
  6702. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6703. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6704. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6705. ###美术风格
  6706. 基础画风风格词:厚涂古风
  6707. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6708. ###场景列表
  6709. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6710. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6711. 无人物。}
  6712. ###道具列表
  6713. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6714. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6715. $episode_count = $this->extractEpisodeNumber($prompt);
  6716. if ((int)getProp($anime, 'is_multi') !== 1) {
  6717. yield [
  6718. 'type' => 'done',
  6719. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6720. 'reasoning' => '',
  6721. 'usage' => []
  6722. ];
  6723. return;
  6724. }
  6725. if ($episode_count) {
  6726. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6727. $system_message = [
  6728. 'role' => 'system',
  6729. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6730. 强制要求:\n
  6731. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6732. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6733. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6734. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6735. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6736. 普通要求:\n
  6737. 1.<故事梗概>控制在200-300字左右
  6738. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6739. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6740. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6741. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6742. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6743. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6744. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6745. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6746. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6747. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6748. 示例如下:\n
  6749. ###剧本名:西昆仑
  6750. ###故事梗概
  6751. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6752. ###剧本亮点
  6753. 亮点1:绝境奇药,生死一线
  6754. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6755. 亮点2:结拜兄妹,化解尴尬
  6756. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6757. 亮点3:纤发夺命,情愫暗涌
  6758. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6759. ###人物关系
  6760. 阿雪与梁萧之间存在兄妹之情。
  6761. ###核心矛盾
  6762. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6763. ###主体列表
  6764. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6765. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6766. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6767. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6768. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6769. 全景,正面拍摄,青年女性,亚洲人。
  6770. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6771. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6772. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6773. ###美术风格
  6774. 基础画风风格词:厚涂古风
  6775. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6776. ###场景列表
  6777. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6778. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6779. 无人物。}
  6780. ###分集详细内容
  6781. ##第1章 重生
  6782. 我重生了。
  6783. 源于一个男人偏执的暗恋。
  6784. ##第2章 相救
  6785. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6786. 我眼睛扫向站在锅炉后的卞大伟。"
  6787. ];
  6788. // 构建消息
  6789. $messages = [
  6790. $system_message,
  6791. [
  6792. 'role' => 'user',
  6793. 'content' => "以下是文档内容:
  6794. {$content}
  6795. 用户问题:
  6796. {$question}"
  6797. ]
  6798. ];
  6799. }else {
  6800. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6801. // 构建消息
  6802. $messages = [
  6803. $system_message,
  6804. [
  6805. 'role' => 'user',
  6806. 'content' => "以下是文档内容:
  6807. {$content}
  6808. 用户问题:
  6809. {$question}"
  6810. ]
  6811. ];
  6812. }else {
  6813. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6814. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6815. return (array)$value;
  6816. })->toArray();
  6817. array_unshift($messages, $system_message);
  6818. $messages[] = [
  6819. 'role' => 'user',
  6820. 'content' => $prompt
  6821. ];
  6822. }
  6823. }
  6824. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6825. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6826. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6827. if ($model === 'deepseek-chat') {
  6828. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6829. $model = 'deepseek-v4-flash';
  6830. $thinkingMode = 'disabled';
  6831. } elseif ($model === 'deepseek-reasoner') {
  6832. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6833. $model = 'deepseek-v4-flash';
  6834. $thinkingMode = 'enabled';
  6835. }
  6836. $post_data = [
  6837. 'model' => $model,
  6838. 'messages' => $messages,
  6839. // 'max_tokens' => 8192,
  6840. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6841. 'frequency_penalty' => 0,
  6842. 'presence_penalty' => 0,
  6843. 'response_format' => ['type' => 'text'],
  6844. 'thinking' => ['type' => $thinkingMode],
  6845. 'stream' => true // 启用流式输出
  6846. ];
  6847. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6848. // 根据模型类型选择调用方法
  6849. $fullContent = '';
  6850. $fullReasoningContent = '';
  6851. $usage = [];
  6852. // dd($post_data);
  6853. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6854. try {
  6855. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6856. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6857. } else if (in_array($model, $this->gpt_text_models)) {
  6858. // GPT-5.4 模型使用 TokenRouter API
  6859. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6860. } else {
  6861. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6862. }
  6863. // 验证返回值类型
  6864. if (!is_iterable($streamGenerator)) {
  6865. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6866. dLog('deepseek')->error('方法名流式生成器无效', [
  6867. 'generator_type' => $errorType,
  6868. 'model' => $model,
  6869. // 添加其他上下文信息
  6870. ]);
  6871. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6872. 'type' => $errorType,
  6873. 'model' => $model
  6874. ]);
  6875. yield [
  6876. 'type' => 'error',
  6877. // 根据方法返回相应的空数据结构
  6878. 'answer' => '',
  6879. 'reasoning' => '',
  6880. 'usage' => [],
  6881. 'error' => '接口返回数据异常,请重新请求'
  6882. ];
  6883. return;
  6884. }
  6885. // 处理流式输出
  6886. foreach ($streamGenerator as $chunk) {
  6887. if (isset($chunk['type'])) {
  6888. if ($chunk['type'] === 'done') {
  6889. $fullContent = $chunk['full_content'];
  6890. $fullReasoningContent = $chunk['full_reasoning'];
  6891. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6892. } else {
  6893. yield $chunk;
  6894. }
  6895. }
  6896. }
  6897. } catch (\Exception $e) {
  6898. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6899. 'model' => $model,
  6900. 'trace' => $e->getTraceAsString()
  6901. ]);
  6902. logDB('deepseek', 'error', '方法名流式处理失败', [
  6903. 'error' => $e->getMessage(),
  6904. 'model' => $model
  6905. ]);
  6906. yield [
  6907. 'type' => 'error',
  6908. // 根据方法返回相应的空数据结构
  6909. 'answer' => '',
  6910. 'reasoning' => '',
  6911. 'usage' => [],
  6912. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6913. ];
  6914. return;
  6915. }
  6916. dLog('deepseek')->info('完整内容: '.$fullContent);
  6917. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6918. // 处理完整内容并返回最终结果
  6919. $script_arr = [];
  6920. if ($fullContent) {
  6921. $script_arr = handleScriptContentForAce($fullContent);
  6922. dLog('deepseek')->info('解析内容', $script_arr);
  6923. logDB('deepseek', 'info', '解析内容', $script_arr);
  6924. }
  6925. if (empty($script_arr['roles'])) {
  6926. // 未生成剧本相关内容,保存对话记录并返回提示
  6927. dLog('deepseek')->info('未生成剧本相关的内容');
  6928. try {
  6929. $now = date('Y-m-d H:i:s');
  6930. // 保存对话记录
  6931. $records = [
  6932. [
  6933. 'uid' => $uid,
  6934. 'anime_id' => $anime_id,
  6935. 'sequence' => 0,
  6936. 'role' => 'user',
  6937. 'content' => $prompt,
  6938. 'created_at' => $now,
  6939. 'updated_at' => $now
  6940. ],
  6941. [
  6942. 'uid' => $uid,
  6943. 'anime_id' => $anime_id,
  6944. 'sequence' => 0,
  6945. 'role' => 'assistant',
  6946. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6947. 'created_at' => $now,
  6948. 'updated_at' => $now
  6949. ]
  6950. ];
  6951. DB::table('mp_anime_records')->insert($records);
  6952. } catch (\Exception $e) {
  6953. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6954. }
  6955. yield [
  6956. 'type' => 'done',
  6957. 'script' => [],
  6958. 'episode' => [],
  6959. 'answer' => $fullContent,
  6960. 'reasoning' => $fullReasoningContent,
  6961. 'usage' => $usage,
  6962. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6963. ];
  6964. return;
  6965. }
  6966. // 替换美术风格
  6967. if ($mappedArtStyle !== '') {
  6968. $script_arr['art_style'] = $mappedArtStyle;
  6969. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6970. }
  6971. if ($user_anime_name != '新剧本策划') {
  6972. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6973. // 确认对话名称唯一性
  6974. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6975. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6976. }
  6977. }else {
  6978. $anime_name = $user_anime_name;
  6979. }
  6980. $table_data = [
  6981. 'user_id' => $uid,
  6982. 'model' => $model,
  6983. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6984. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6985. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6986. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6987. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6988. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6989. 'art_style_type' => $input_art_style,
  6990. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6991. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6992. 'status' => '解析完成',
  6993. 'generate_status' => '待执行',
  6994. 'updated_at' => date('Y-m-d H:i:s')
  6995. ];
  6996. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6997. // 如果是修改集数,则将content内容更新(会改变原文)
  6998. if (isset($episode_count) && $episode_count > 0) {
  6999. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  7000. $table_data['start_episode_sequence'] = 1;
  7001. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  7002. }else {
  7003. // 如果需要生成原文内容,从script_arr中提取
  7004. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7005. $table_data['content'] = $script_arr['content'];
  7006. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  7007. if (!$table_data['content']) {
  7008. yield [
  7009. 'type' => 'done',
  7010. 'script' => [],
  7011. 'episode' => [],
  7012. 'answer' => $fullContent,
  7013. 'reasoning' => $fullReasoningContent,
  7014. 'usage' => $usage,
  7015. 'error' => '未生成剧本内容,请调整提示词再试'
  7016. ];
  7017. return;
  7018. }
  7019. }
  7020. if (isset($table_data['content']) && $table_data['content']) {
  7021. $chapters = splitContent($table_data['content']);
  7022. $chapter_count = count($chapters);
  7023. if ($chapter_count > 0) {
  7024. $table_data['start_episode_sequence'] = 1;
  7025. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7026. }
  7027. }
  7028. }
  7029. if ($extra_products) {
  7030. $table_data['extra_products'] = json_encode($extra_products, 256);
  7031. }
  7032. $single_episode = [];
  7033. try {
  7034. DB::beginTransaction();
  7035. $now = date('Y-m-d H:i:s');
  7036. // 更新动漫大纲
  7037. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7038. if (!$boolen) {
  7039. dLog('deepseek')->info('对话修改失败', $table_data);
  7040. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7041. Utils::throwError('20003:对话修改失败');
  7042. }
  7043. // 保存对话记录
  7044. $records = [
  7045. [
  7046. 'uid' => $uid,
  7047. 'anime_id' => $anime_id,
  7048. 'sequence' => 0,
  7049. 'role' => 'user',
  7050. 'content' => $prompt,
  7051. 'created_at' => $now,
  7052. 'updated_at' => $now
  7053. ],
  7054. [
  7055. 'uid' => $uid,
  7056. 'anime_id' => $anime_id,
  7057. 'sequence' => 0,
  7058. 'role' => 'assistant',
  7059. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7060. 'content' => $fullContent,
  7061. 'created_at' => $now,
  7062. 'updated_at' => $now
  7063. ]
  7064. ];
  7065. // 保存对话记录
  7066. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7067. if (!$boolen3) {
  7068. Utils::throwError('20003:对话记录保存失败');
  7069. }
  7070. // 单剧集模式:生成并保存剧集信息
  7071. if ($is_single) {
  7072. $anime_name = getProp($anime, 'anime_name', '未命名');
  7073. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7074. if (empty($episode_arr['acts'])) {
  7075. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7076. }
  7077. $saveResult = $this->saveEpisodeVersionData(
  7078. $anime_id,
  7079. 1,
  7080. $episode_arr,
  7081. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7082. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7083. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7084. null,
  7085. null,
  7086. false,
  7087. $content,
  7088. $now,
  7089. $ref_products
  7090. );
  7091. $single_episode = $saveResult['episode'];
  7092. $episode_id = $saveResult['episode_id'];
  7093. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7094. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7095. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7096. 'props' => json_encode($saveResult['merged_props'], 256),
  7097. 'updated_at' => $now
  7098. ]);
  7099. if ($boolen5 === false) {
  7100. Utils::throwError('20003:单剧集主表资源同步失败');
  7101. }
  7102. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7103. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7104. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7105. $episode_record_content = '确认分镜大纲';
  7106. if ($content !== '') {
  7107. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7108. }
  7109. $episode_records = [
  7110. [
  7111. 'uid' => $uid,
  7112. 'anime_id' => $anime_id,
  7113. 'role' => 'user',
  7114. 'content' => $episode_record_content,
  7115. 'sequence' => 1,
  7116. 'episode_id' => $episode_id,
  7117. 'created_at' => $now,
  7118. 'updated_at' => $now
  7119. ],
  7120. [
  7121. 'uid' => $uid,
  7122. 'anime_id' => $anime_id,
  7123. 'role' => 'assistant',
  7124. 'content' => $fullContent,
  7125. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7126. 'sequence' => 1,
  7127. 'episode_id' => $episode_id,
  7128. 'created_at' => $now,
  7129. 'updated_at' => $now
  7130. ]
  7131. ];
  7132. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7133. if (!$boolen4) {
  7134. Utils::throwError('20003:单剧集分镜记录保存失败');
  7135. }
  7136. }
  7137. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7138. if ($is_single && !empty($single_episode)) {
  7139. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7140. 'anime_id' => $anime_id,
  7141. 'episode_id' => $episode_id ?? 0,
  7142. ]);
  7143. }
  7144. }catch (\Exception $e) {
  7145. DB::rollBack();
  7146. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7147. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7148. yield [
  7149. 'type' => 'done',
  7150. 'answer' => $fullContent,
  7151. 'reasoning' => $fullReasoningContent,
  7152. 'usage' => $usage,
  7153. 'error' => $e->getMessage(),
  7154. ];
  7155. return;
  7156. }
  7157. DB::commit();
  7158. dLog('deepseek')->info('保存完毕');
  7159. if ($is_single && !empty($single_episode)) {
  7160. // $this->batchSetGlobalRoleImg([
  7161. // 'anime_id' => $anime_id,
  7162. // ]);
  7163. // $this->batchSetGlobalSceneImg([
  7164. // 'anime_id' => $anime_id,
  7165. // ]);
  7166. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7167. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7168. }
  7169. $table_data['anime_id'] = $anime_id;
  7170. $table_data['roles'] = json_decode($table_data['roles'], true);
  7171. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7172. $table_data['props'] = json_decode($table_data['props'], true);
  7173. unset($table_data['updated_at']);
  7174. unset($table_data['status']);
  7175. yield [
  7176. 'type' => 'done',
  7177. 'script' => $table_data,
  7178. 'episode' => $single_episode,
  7179. 'answer' => $fullContent,
  7180. 'reasoning' => $fullReasoningContent,
  7181. 'usage' => $usage
  7182. ];
  7183. }
  7184. public function chatForAce($data) {
  7185. $uid = Site::getUid();
  7186. // 积分余额预检(不足直接报错)
  7187. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  7188. $anime_id = getProp($data, 'anime_id');
  7189. $file = getProp($data, 'file');
  7190. $content = getProp($data, 'content', '');
  7191. $bid = getProp($data, 'bid', 0);
  7192. $script_id = getProp($data, 'script_id', 0);
  7193. $episode_number = getProp($data, 'episode_number', 1);
  7194. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7195. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7196. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7197. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7198. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7199. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7200. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7201. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7202. $roles = is_array($roles) ? $roles : [];
  7203. $scenes = is_array($scenes) ? $scenes : [];
  7204. $extra_products = getProp($data, 'products', []);
  7205. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7206. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7207. $anime_script_id = getProp($anime, 'script_id');
  7208. if ($anime_script_id) {
  7209. $cpid = Site::getCpid();
  7210. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7211. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7212. ->where('mapping.script_id', $anime_script_id)
  7213. ->where('product.cpid', $cpid)
  7214. ->where('product.is_deleted', 0);
  7215. // 如果提供了 episode_number,则过滤指定集数
  7216. if ($episode_number !== null && $episode_number !== '') {
  7217. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7218. }
  7219. $mappings = $script_products_mappings->select(
  7220. 'mapping.product_id',
  7221. 'mapping.episode_number',
  7222. 'product.product_name',
  7223. 'product.type',
  7224. 'product.product',
  7225. 'product.pic_prompt',
  7226. 'product.url',
  7227. 'product.pic_task_id',
  7228. 'product.pic_task_status',
  7229. 'product.three_view_image_url'
  7230. )
  7231. ->get();
  7232. // 按 product_id 分组,合并 episode_number
  7233. $productMap = [];
  7234. foreach ($mappings as $item) {
  7235. $product_id = $item->product_id;
  7236. $product_name = $item->product_name;
  7237. // 处理product_name两边的符号
  7238. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7239. if (!isset($productMap[$product_id])) {
  7240. $productMap[$product_id] = [
  7241. 'product_id' => $product_id,
  7242. 'product_name' => $product_name,
  7243. 'type' => (int)$item->type,
  7244. 'product' => (int)$item->product,
  7245. 'pic_prompt' => $item->pic_prompt,
  7246. 'url' => $item->url,
  7247. 'pic_task_id' => $item->pic_task_id,
  7248. 'pic_task_status' => $item->pic_task_status,
  7249. 'episode_numbers' => [],
  7250. ];
  7251. }
  7252. // 添加 episode_number(去重)
  7253. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7254. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7255. }
  7256. }
  7257. // 将查询到的剧本资产合并到extra_products中
  7258. // 先构建extra_products的索引(以product_id+episode_number为key)
  7259. $extraProductsMap = [];
  7260. foreach ($extra_products as $item) {
  7261. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7262. $extraProductsMap[$key] = $item;
  7263. }
  7264. // 合并剧本资产(去重:product_id+episode_number)
  7265. foreach ($productMap as $product) {
  7266. foreach ($product['episode_numbers'] as $ep_num) {
  7267. $key = $product['product_id'] . '_' . $ep_num;
  7268. // 如果不存在则添加
  7269. if (!isset($extraProductsMap[$key])) {
  7270. $extraProductsMap[$key] = [
  7271. 'product_id' => $product['product_id'],
  7272. 'product_name' => $product['product_name'],
  7273. 'type' => $product['type'],
  7274. 'product' => $product['product'],
  7275. 'pic_prompt' => $product['pic_prompt'],
  7276. 'url' => $product['url'],
  7277. 'pic_task_id' => $product['pic_task_id'],
  7278. 'pic_task_status' => $product['pic_task_status'],
  7279. 'episode_number' => $ep_num,
  7280. ];
  7281. }
  7282. }
  7283. }
  7284. // 重新赋值给extra_products
  7285. $extra_products = array_values($extraProductsMap);
  7286. }
  7287. // 处理提示词
  7288. if ($prompt && $extra_products) {
  7289. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7290. foreach($extra_products as $item) {
  7291. $product_name = getProp($item, 'product_name');
  7292. if ($product_name) {
  7293. // 替换 {product_name} 为 product_name
  7294. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7295. }
  7296. }
  7297. }
  7298. // 获取最后一集序号
  7299. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7300. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7301. // 转换主体列表和场景列表的格式
  7302. // 获取参考主体或场景
  7303. if ((int)$episode_number === 1) {
  7304. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7305. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7306. }else {
  7307. $prev_episode_number = $episode_number - 1;
  7308. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7309. }
  7310. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7311. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7312. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7313. // 合并anime_products和extra_products(extra_products优先,去重)
  7314. $anime_products = getProp($anime, 'extra_products');
  7315. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7316. $ref_products = [];
  7317. foreach($anime_products as $item) {
  7318. $product_name = getProp($item, 'product_name');
  7319. $ref_products[$product_name] = $item;
  7320. }
  7321. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7322. $extra_roles = []; // 从extra_products中提取的角色
  7323. $extra_scenes = []; // 从extra_products中提取的场景
  7324. $extra_props = []; // 从extra_products中提取的道具
  7325. if ($extra_products && is_array($extra_products)) {
  7326. foreach($extra_products as $item) {
  7327. $product = (int)getProp($item, 'product');
  7328. $product_name = getProp($item, 'product_name');
  7329. if ($product_name == '旁白') continue;
  7330. $pic_prompt = getProp($item, 'pic_prompt');
  7331. $ref_products[$product_name] = $item;
  7332. if ($product === 1) {
  7333. // 角色
  7334. $extra_roles[$product_name] = [
  7335. 'role' => $product_name,
  7336. 'pic_prompt' => $pic_prompt,
  7337. 'url' => getProp($item, 'url', ''),
  7338. ];
  7339. } elseif ($product === 2) {
  7340. // 场景
  7341. $extra_scenes[$product_name] = [
  7342. 'scene' => $product_name,
  7343. 'pic_prompt' => $pic_prompt,
  7344. 'url' => getProp($item, 'url', ''),
  7345. ];
  7346. } elseif ($product === 3) {
  7347. // 道具
  7348. $extra_props[$product_name] = [
  7349. 'prop' => $product_name,
  7350. 'pic_prompt' => $pic_prompt,
  7351. 'url' => getProp($item, 'url', ''),
  7352. ];
  7353. }
  7354. }
  7355. }
  7356. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7357. $merged_roles = [];
  7358. foreach($ref_roles as $role) {
  7359. $role_name = getProp($role, 'role');
  7360. if (!isset($extra_roles[$role_name])) {
  7361. $merged_roles[$role_name] = $role;
  7362. }
  7363. }
  7364. // 添加extra_roles
  7365. foreach($extra_roles as $role_name => $role) {
  7366. $merged_roles[$role_name] = $role;
  7367. }
  7368. $ref_roles = array_values($merged_roles);
  7369. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7370. $merged_scenes = [];
  7371. foreach($ref_scenes as $scene) {
  7372. $scene_name = getProp($scene, 'scene');
  7373. if (!isset($extra_scenes[$scene_name])) {
  7374. $merged_scenes[$scene_name] = $scene;
  7375. }
  7376. }
  7377. // 添加extra_scenes
  7378. foreach($extra_scenes as $scene_name => $scene) {
  7379. $merged_scenes[$scene_name] = $scene;
  7380. }
  7381. $ref_scenes = array_values($merged_scenes);
  7382. // 合并ref_props和extra_props(extra_props优先,去重)
  7383. $merged_props = [];
  7384. foreach($ref_props as $prop) {
  7385. $prop_name = getProp($prop, 'prop');
  7386. if (!isset($extra_props[$prop_name])) {
  7387. $merged_props[$prop_name] = $prop;
  7388. }
  7389. }
  7390. // 添加extra_props
  7391. foreach($extra_props as $prop_name => $prop) {
  7392. $merged_props[$prop_name] = $prop;
  7393. }
  7394. $ref_props = array_values($merged_props);
  7395. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7396. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7397. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7398. // 构建强制主体、场景和道具提示词
  7399. $forced_roles_prompt = "";
  7400. $forced_scenes_prompt = "";
  7401. $forced_props_prompt = "";
  7402. if (!empty($extra_roles)) {
  7403. $forced_roles_list = "";
  7404. foreach($extra_roles as $role_name => $role) {
  7405. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7406. }
  7407. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7408. }
  7409. if (!empty($extra_scenes)) {
  7410. $forced_scenes_list = "";
  7411. foreach($extra_scenes as $scene_name => $scene) {
  7412. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7413. }
  7414. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7415. }
  7416. if (!empty($extra_props)) {
  7417. $forced_props_list = "";
  7418. foreach($extra_props as $prop_name => $prop) {
  7419. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7420. }
  7421. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7422. }
  7423. if ($anime_script_id) {
  7424. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7425. }else if ($roles_content) {
  7426. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7427. 主体范围:\n {$roles_content}\n
  7428. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7429. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7430. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7431. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7432. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7433. }else {
  7434. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7435. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7436. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7437. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7438. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7439. }
  7440. if ($anime_script_id) {
  7441. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7442. }else if ($scenes_content) {
  7443. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7444. 场景范围:\n {$scenes_content}\n
  7445. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7446. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7447. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7448. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7449. }else {
  7450. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7451. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7452. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7453. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7454. }
  7455. if ($anime_script_id) {
  7456. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7457. }else if ($props_content) {
  7458. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7459. 道具范围:\n {$props_content}\n
  7460. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7461. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7462. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7463. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7464. }else {
  7465. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7466. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7467. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7468. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7469. }
  7470. // 提取文件内容
  7471. if ($file) {
  7472. $uploaded_content = $this->extractFileContent($file);
  7473. if (!$uploaded_content) {
  7474. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7475. }
  7476. } elseif ($script_id) {
  7477. $uploaded_content = $this->getContentByScriptId($script_id);
  7478. if (!$uploaded_content) {
  7479. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7480. }
  7481. } elseif ($bid) {
  7482. $uploaded_content = $this->getContentByBid($bid);
  7483. if (!$uploaded_content) {
  7484. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7485. }
  7486. } elseif ($content) {
  7487. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7488. }
  7489. // elseif ($prompt) {
  7490. // $uploaded_content = filterContent($prompt);
  7491. // }
  7492. else {
  7493. $uploaded_content = '';
  7494. }
  7495. // 美术风格
  7496. $input_art_style = getProp($data, 'art_style');
  7497. if (!$input_art_style) {
  7498. $mappedArtStyle = getProp($anime, 'art_style');
  7499. }else {
  7500. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7501. }
  7502. if (!$mappedArtStyle) {
  7503. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7504. }else {
  7505. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7506. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7507. }else {
  7508. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7509. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7510. }
  7511. }
  7512. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7513. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7514. // 强制要求:
  7515. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7516. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7517. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7518. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7519. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7520. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7521. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7522. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7523. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7524. // 10.分镜要和场景列表、人物主体保持一致\n
  7525. // 普通要求:
  7526. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7527. // {$role_demo}
  7528. // {$scene_demo}
  7529. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7530. // 4.1片段分割逻辑(优先级从高到低):
  7531. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7532. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7533. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7534. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7535. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7536. // - 片段数量格式为: 片段数量:8
  7537. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7538. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7539. // 4.3分镜结构:每个分镜包含以下字段:
  7540. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7541. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7542. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7543. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7544. // - 运镜:场景+画面描述+运镜
  7545. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7546. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7547. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7548. // 5.$mappedArtStyle_prompt\n\n
  7549. // 示例格式:\n
  7550. // 第1集:隐形的守护者
  7551. // ###故事梗概
  7552. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7553. // ###美术风格
  7554. // 基础画风风格词:胡金铨武侠
  7555. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7556. // ###主体列表
  7557. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7558. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7559. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7560. // ###场景列表
  7561. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7562. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7563. // ###分段剧本
  7564. // 片段数量:8
  7565. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7566. // ##片段1
  7567. // 时长:12s
  7568. // 分镜1
  7569. // 场景:边境小镇街道
  7570. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7571. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7572. // 配音台词:
  7573. // 背景音效:
  7574. // 分镜2
  7575. // 场景:悦来酒馆
  7576. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7577. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7578. // 配音台词:
  7579. // 背景音效:
  7580. // 分镜3
  7581. // 场景:悦来酒馆
  7582. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7583. // 运镜:从中景推向令牌特写。
  7584. // 配音台词:
  7585. // 背景音效:
  7586. // 分镜4
  7587. // 场景:悦来酒馆
  7588. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7589. // 运镜:极速推向酒水溅起的瞬间。
  7590. // 配音台词:
  7591. // 背景音效:
  7592. // 分镜5
  7593. // 镜头描述
  7594. // 场景:悦来酒馆
  7595. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7596. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7597. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7598. // 背景音效:
  7599. // \n\n";
  7600. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7601. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7602. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7603. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7604. 普通要求:
  7605. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7606. {$role_demo}
  7607. {$scene_demo}
  7608. {$prop_demo}
  7609. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7610. 5.1片段分割逻辑(优先级从高到低):
  7611. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7612. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7613. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7614. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7615. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7616. - 片段数量格式为: 片段数量:8
  7617. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7618. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7619. 5.3分镜结构:每个分镜包含以下字段:
  7620. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7621. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7622. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7623. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7624. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7625. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7626. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7627. - 运镜:场景+画面描述+运镜
  7628. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7629. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7630. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7631. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7632. 6.《情绪-视听语言映射表》:
  7633. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7634. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7635. -----|---------|------------|----------------
  7636. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7637. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7638. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7639. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7640. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7641. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7642. -----|---------|------------|----------------
  7643. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7644. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7645. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7646. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7647. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7648. --------|---------|--------------|-------------
  7649. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7650. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7651. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7652. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7653. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7654. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7655. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7656. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7657. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7658. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7659. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7660. -----|---------|------------|------------
  7661. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7662. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7663. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7664. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7665. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7666. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7667. --------|---------|--------------|----------
  7668. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7669. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7670. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7671. 6.6 声音设计与潜意识影响 (Soundscape)
  7672. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7673. -----|---------|------------|------------------
  7674. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7675. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7676. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7677. 理论基石:
  7678. - The Five C's of Cinematography by Joseph V. Mascelli
  7679. - Film Art: An Introduction by David Bordwell
  7680. - Sight, Sound, Motion by Herbert Zettl
  7681. - Notes on the Cinematograph by Robert Bresson
  7682. \n\n
  7683. 7.{$mappedArtStyle_prompt}
  7684. 示例格式:\n
  7685. 第1集:隐形的守护者
  7686. ###故事梗概
  7687. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7688. ###美术风格
  7689. 基础画风风格词:胡金铨武侠
  7690. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7691. ###主体列表
  7692. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7693. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7694. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7695. ###场景列表
  7696. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7697. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7698. ###道具列表
  7699. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7700. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7701. ###分段剧本
  7702. 片段数量:8
  7703. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7704. ##片段1
  7705. 时长:12s
  7706. 分镜1
  7707. 出场角色:刀疤脸
  7708. 场景:边境小镇街道
  7709. 出场道具:酒杯-高脚杯
  7710. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7711. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7712. 配音台词:
  7713. 背景音效:
  7714. 分镜2
  7715. 出场角色:刀疤脸
  7716. 场景:悦来酒馆
  7717. 出场道具:酒杯-高脚杯
  7718. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7719. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7720. 配音台词:
  7721. 背景音效:
  7722. 分镜3
  7723. 出场角色:刀疤脸
  7724. 场景:悦来酒馆
  7725. 出场道具:酒杯-高脚杯
  7726. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7727. 运镜:从中景推向令牌特写。
  7728. 配音台词:
  7729. 背景音效:
  7730. 分镜4
  7731. 出场角色:刀疤脸
  7732. 场景:悦来酒馆
  7733. 出场道具:酒杯-高脚杯
  7734. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7735. 运镜:极速推向酒水溅起的瞬间。
  7736. 配音台词:
  7737. 背景音效:
  7738. 分镜5
  7739. 出场角色:刀疤脸
  7740. 场景:悦来酒馆
  7741. 出场道具:酒杯-高脚杯
  7742. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7743. 运镜:固定机位,利用倾斜构图制造压迫感。
  7744. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7745. 背景音效:
  7746. \n\n";
  7747. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7748. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7749. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7750. $prompt = $origin_prompt;
  7751. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7752. // 获取章节内容
  7753. $full_content = getProp($anime, 'content');
  7754. if ($uploaded_content) {
  7755. $full_content = $uploaded_content;
  7756. }
  7757. // 根据章节内容拆分章节
  7758. $chapters = splitContent($full_content);
  7759. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7760. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7761. $messages = [];
  7762. if ($prompt == '确认分镜大纲') {
  7763. // 暂时保留
  7764. $content = $chapter_content;
  7765. if ($is_single) $content = $full_content; // 单剧集使用全文
  7766. if (!$content) {
  7767. Utils::throwError('20003:章节内容无法获取,请确认');
  7768. }
  7769. $question = $is_single
  7770. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7771. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7772. // 构建消息
  7773. $messages[] =
  7774. [
  7775. 'role' => 'user',
  7776. 'content' => $question
  7777. ];
  7778. }else if ($prompt == '继续策划下一集') {
  7779. if ($is_single) {
  7780. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7781. }
  7782. $content = $chapter_content;
  7783. if (!$content) {
  7784. Utils::throwError('20003:章节内容无法获取,请确认');
  7785. }
  7786. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7787. // 获取上一集最后记录
  7788. $prev_sequence = $episode_number - 1;
  7789. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7790. // 构建消息
  7791. $messages[] =
  7792. [
  7793. 'role' => 'user',
  7794. 'content' => $question
  7795. ];
  7796. // dd($messages);
  7797. }else {
  7798. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7799. if (!$content) {
  7800. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7801. }
  7802. if (!$content) {
  7803. Utils::throwError('20003:章节内容无法获取,请确认');
  7804. }
  7805. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7806. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7807. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7808. if ($origin_prompt) {
  7809. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7810. }
  7811. $messages[] =
  7812. [
  7813. 'role' => 'user',
  7814. 'content' => $question
  7815. ];
  7816. }
  7817. // 处理文本模型
  7818. $model = getProp($data, 'model');
  7819. if (!$model) {
  7820. // 用户没有输入,从anime表获取
  7821. $model = getProp($anime, 'model');
  7822. if (!$model) {
  7823. // anime表也没有,使用默认值
  7824. $model = 'deepseek-v4-pro';
  7825. }
  7826. }
  7827. // 验证模型是否在可用模型表中
  7828. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7829. $model = 'deepseek-v4-pro';
  7830. }
  7831. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7832. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7833. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7834. if ($model === 'deepseek-chat') {
  7835. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7836. $model = 'deepseek-v4-flash';
  7837. $thinkingMode = 'disabled';
  7838. } elseif ($model === 'deepseek-reasoner') {
  7839. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7840. $model = 'deepseek-v4-flash';
  7841. $thinkingMode = 'enabled';
  7842. }
  7843. $post_data = [
  7844. 'model' => $model,
  7845. 'messages' => $messages,
  7846. // 'max_tokens' => 8192,
  7847. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7848. 'frequency_penalty' => 0,
  7849. 'presence_penalty' => 0,
  7850. 'response_format' => ['type' => 'text'],
  7851. 'thinking' => ['type' => $thinkingMode],
  7852. 'stream' => true // 启用流式输出
  7853. ];
  7854. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7855. // 根据模型类型选择调用方法
  7856. $fullContent = '';
  7857. $fullReasoningContent = '';
  7858. $usage = [];
  7859. try {
  7860. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7861. // DeepSeek 官方模型使用 DeepSeek API
  7862. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7863. } else if (in_array($model, $this->gpt_text_models)) {
  7864. // GPT-5.4 模型使用 TokenRouter API
  7865. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7866. } else {
  7867. // 其他模型使用火山引擎API
  7868. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7869. }
  7870. // 验证返回值类型
  7871. if (!is_iterable($streamGenerator)) {
  7872. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7873. dLog('deepseek')->error('chat流式生成器无效', [
  7874. 'generator_type' => $errorType,
  7875. 'model' => $model,
  7876. 'anime_id' => $anime_id,
  7877. 'episode_number' => $episode_number
  7878. ]);
  7879. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7880. 'type' => $errorType,
  7881. 'model' => $model
  7882. ]);
  7883. yield [
  7884. 'type' => 'error',
  7885. 'episode' => [],
  7886. 'answer' => '',
  7887. 'reasoning' => '',
  7888. 'usage' => [],
  7889. 'error' => '接口返回数据异常,请重新请求'
  7890. ];
  7891. return;
  7892. }
  7893. // 处理流式输出
  7894. foreach ($streamGenerator as $chunk) {
  7895. if (isset($chunk['type'])) {
  7896. if ($chunk['type'] === 'done') {
  7897. // 最终结果
  7898. $fullContent = $chunk['full_content'];
  7899. $fullReasoningContent = $chunk['full_reasoning'];
  7900. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7901. } else {
  7902. // 逐块yield数据
  7903. yield $chunk;
  7904. }
  7905. }
  7906. }
  7907. } catch (\Exception $e) {
  7908. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7909. 'model' => $model,
  7910. 'anime_id' => $anime_id,
  7911. 'episode_number' => $episode_number,
  7912. 'trace' => $e->getTraceAsString()
  7913. ]);
  7914. logDB('deepseek', 'error', 'chat流式处理失败', [
  7915. 'error' => $e->getMessage(),
  7916. 'model' => $model
  7917. ]);
  7918. yield [
  7919. 'type' => 'error',
  7920. 'episode' => [],
  7921. 'answer' => '',
  7922. 'reasoning' => '',
  7923. 'usage' => [],
  7924. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7925. ];
  7926. return;
  7927. }
  7928. dLog('deepseek')->info('完整内容: '.$fullContent);
  7929. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7930. // 处理完整内容并返回最终结果
  7931. $episode_arr = handleEpisodeContentForAce($fullContent);
  7932. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7933. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7934. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7935. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7936. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7937. // }
  7938. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7939. $max_retries = 3;
  7940. $retry_count = 0;
  7941. $validation_failed = false;
  7942. $validation_error_msg = '';
  7943. // 验证生成的内容
  7944. if ($anime_script_id) {
  7945. // 检查是否有acts数据
  7946. if (empty($episode_arr['acts'])) {
  7947. $validation_failed = true;
  7948. $validation_error_msg = '未生成分镜剧本相关的内容';
  7949. } else {
  7950. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7951. $generated_roles = array_column($episode_arr['roles'], 'role');
  7952. // 过滤掉"旁白"角色
  7953. $generated_roles = array_filter($generated_roles, function($role) {
  7954. return $role !== '旁白';
  7955. });
  7956. $expected_roles = array_keys($extra_roles);
  7957. // 找出生成的主体中不在预期列表中的主体
  7958. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7959. if (!empty($invalid_roles)) {
  7960. $validation_failed = true;
  7961. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7962. }
  7963. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7964. if (!$validation_failed) {
  7965. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7966. $expected_scenes = array_keys($extra_scenes);
  7967. // 找出生成的场景中不在预期列表中的场景
  7968. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7969. if (!empty($invalid_scenes)) {
  7970. $validation_failed = true;
  7971. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7972. }
  7973. }
  7974. }
  7975. } else {
  7976. // 如果没有anime_script_id,只检查是否有acts数据
  7977. if (empty($episode_arr['acts'])) {
  7978. $validation_failed = true;
  7979. $validation_error_msg = '未生成分镜剧本相关的内容';
  7980. }
  7981. }
  7982. // 重试逻辑
  7983. while ($validation_failed && $retry_count < $max_retries) {
  7984. $retry_count++;
  7985. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7986. 'reason' => $validation_error_msg,
  7987. 'anime_id' => $anime_id,
  7988. 'episode_number' => $episode_number
  7989. ]);
  7990. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7991. 'reason' => $validation_error_msg,
  7992. 'anime_id' => $anime_id
  7993. ]);
  7994. // 发送流式重试提示
  7995. yield [
  7996. 'type' => 'retry',
  7997. 'retry_count' => $retry_count,
  7998. 'reason' => $validation_error_msg
  7999. ];
  8000. // 构建重试提示词
  8001. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8002. if ($anime_script_id) {
  8003. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8004. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8005. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  8006. } else {
  8007. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  8008. }
  8009. // 添加重试消息到messages
  8010. $messages[] = [
  8011. 'role' => 'assistant',
  8012. 'content' => $fullContent
  8013. ];
  8014. $messages[] = [
  8015. 'role' => 'user',
  8016. 'content' => $retry_prompt
  8017. ];
  8018. // 更新post_data的messages
  8019. $post_data['messages'] = $messages;
  8020. // 重新调用API
  8021. try {
  8022. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8023. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8024. } else if (in_array($model, $this->gpt_text_models)) {
  8025. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8026. } else {
  8027. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8028. }
  8029. // 处理流式输出
  8030. $fullContent = '';
  8031. $fullReasoningContent = '';
  8032. foreach ($streamGenerator as $chunk) {
  8033. if (isset($chunk['type'])) {
  8034. if ($chunk['type'] === 'done') {
  8035. $fullContent = $chunk['full_content'];
  8036. $fullReasoningContent = $chunk['full_reasoning'];
  8037. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8038. } else {
  8039. yield $chunk;
  8040. }
  8041. }
  8042. }
  8043. // 重新解析内容
  8044. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8045. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8046. $episode_arr = handleEpisodeContentForAce($fullContent);
  8047. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8048. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8049. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8050. // }
  8051. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  8052. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  8053. // 重新验证
  8054. $validation_failed = false;
  8055. $validation_error_msg = '';
  8056. if ($anime_script_id) {
  8057. if (empty($episode_arr['acts'])) {
  8058. $validation_failed = true;
  8059. $validation_error_msg = '未生成分镜剧本相关的内容';
  8060. } else {
  8061. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  8062. $generated_roles = array_column($episode_arr['roles'], 'role');
  8063. // 过滤掉"旁白"角色
  8064. $generated_roles = array_filter($generated_roles, function($role) {
  8065. return $role !== '旁白';
  8066. });
  8067. $expected_roles = array_keys($extra_roles);
  8068. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8069. if (!empty($invalid_roles)) {
  8070. $validation_failed = true;
  8071. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8072. }
  8073. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  8074. if (!$validation_failed) {
  8075. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8076. $expected_scenes = array_keys($extra_scenes);
  8077. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8078. if (!empty($invalid_scenes)) {
  8079. $validation_failed = true;
  8080. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8081. }
  8082. }
  8083. }
  8084. } else {
  8085. if (empty($episode_arr['acts'])) {
  8086. $validation_failed = true;
  8087. $validation_error_msg = '未生成分镜剧本相关的内容';
  8088. }
  8089. }
  8090. } catch (\Exception $e) {
  8091. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8092. 'trace' => $e->getTraceAsString()
  8093. ]);
  8094. break;
  8095. }
  8096. }
  8097. // 如果重试后仍然失败
  8098. if ($validation_failed) {
  8099. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8100. 'retry_count' => $retry_count,
  8101. 'last_error' => $validation_error_msg
  8102. ]);
  8103. try {
  8104. $now = date('Y-m-d H:i:s');
  8105. $records = [
  8106. [
  8107. 'uid' => $uid,
  8108. 'anime_id' => $anime_id,
  8109. 'sequence' => $episode_number,
  8110. 'role' => 'user',
  8111. 'content' => $prompt,
  8112. 'created_at' => $now,
  8113. 'updated_at' => $now
  8114. ],
  8115. [
  8116. 'uid' => $uid,
  8117. 'anime_id' => $anime_id,
  8118. 'sequence' => $episode_number,
  8119. 'role' => 'assistant',
  8120. 'content' => $fullContent,
  8121. 'created_at' => $now,
  8122. 'updated_at' => $now
  8123. ]
  8124. ];
  8125. DB::table('mp_anime_records')->insert($records);
  8126. } catch (\Exception $e) {
  8127. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8128. }
  8129. yield [
  8130. 'type' => 'done',
  8131. 'episode' => [],
  8132. 'answer' => $fullContent,
  8133. 'reasoning' => $fullReasoningContent,
  8134. 'usage' => $usage,
  8135. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8136. ];
  8137. return;
  8138. }
  8139. // 验证成功,记录日志
  8140. if ($retry_count > 0) {
  8141. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8142. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8143. }
  8144. // 老逻辑
  8145. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8146. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8147. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8148. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8149. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8150. $existing_props = is_array($existing_props) ? $existing_props : [];
  8151. $now = date('Y-m-d H:i:s');
  8152. try {
  8153. DB::beginTransaction();
  8154. $saveResult = $this->saveEpisodeVersionData(
  8155. $anime_id,
  8156. $episode_number,
  8157. $episode_arr,
  8158. $existing_roles,
  8159. $existing_scenes,
  8160. $existing_props,
  8161. $current_episode,
  8162. $base_episode,
  8163. $is_regenerate_version,
  8164. $content,
  8165. $now,
  8166. $ref_products
  8167. );
  8168. $episode = $saveResult['episode'];
  8169. $episode_id = $saveResult['episode_id'];
  8170. $merged_roles = $saveResult['merged_roles'];
  8171. $merged_scenes = $saveResult['merged_scenes'];
  8172. $merged_props = $saveResult['merged_props'];
  8173. $record_content = $origin_prompt;
  8174. if ($uploaded_content !== '') {
  8175. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8176. }
  8177. $records = [
  8178. [
  8179. 'uid' => $uid,
  8180. 'anime_id' => $anime_id,
  8181. 'role' => 'user',
  8182. 'content' => $record_content,
  8183. 'sequence' => $episode_number,
  8184. 'episode_id' => $episode_id,
  8185. 'created_at' => $now,
  8186. 'updated_at' => $now
  8187. ],
  8188. [
  8189. 'uid' => $uid,
  8190. 'anime_id' => $anime_id,
  8191. 'role' => 'assistant',
  8192. 'content' => $fullContent,
  8193. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8194. 'sequence' => $episode_number,
  8195. 'episode_id' => $episode_id,
  8196. 'created_at' => $now,
  8197. 'updated_at' => $now
  8198. ]
  8199. ];
  8200. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8201. if (!$boolen4) {
  8202. Utils::throwError('20003:对话记录保存失败');
  8203. }
  8204. // 保存模型到anime表
  8205. $update_anime_data = [
  8206. 'model' => $model,
  8207. 'updated_at' => $now
  8208. ];
  8209. if ($uploaded_content) {
  8210. $update_anime_data['content'] = $uploaded_content;
  8211. }
  8212. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8213. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8214. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8215. 'anime_id' => $anime_id,
  8216. 'episode_number' => $episode_number,
  8217. 'model' => $model,
  8218. ]);
  8219. }catch (\Exception $e) {
  8220. DB::rollBack();
  8221. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8222. yield [
  8223. 'type' => 'done',
  8224. 'answer' => $fullContent,
  8225. 'reasoning' => $fullReasoningContent,
  8226. 'usage' => $usage,
  8227. 'error' => $e->getMessage(),
  8228. ];
  8229. return;
  8230. }
  8231. DB::commit();
  8232. if ($is_global_generate_pics) {
  8233. // // 批量生成全局角色图片
  8234. // $this->batchSetGlobalRoleImg([
  8235. // 'anime_id' => $anime_id,
  8236. // ], true);
  8237. // // 批量生成全局场景图片
  8238. // $this->batchSetGlobalSceneImg([
  8239. // 'anime_id' => $anime_id,
  8240. // ], true);
  8241. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8242. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8243. }
  8244. $episode['episode_id'] = $episode_id;
  8245. $episode['roles'] = $merged_roles;
  8246. $episode['scenes'] = $merged_scenes;
  8247. $episode['props'] = $merged_props;
  8248. $episode['end_episode_sequence'] = $end_episode_sequence;
  8249. // 获取mp_animes表中的视频参数
  8250. $episode['video_params'] = [
  8251. 'video_model' => getProp($anime, 'video_model'),
  8252. 'video_resolution' => getProp($anime, 'video_resolution'),
  8253. 'ratio' => getProp($anime, 'video_ratio'),
  8254. ];
  8255. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8256. yield [
  8257. 'type' => 'done',
  8258. 'episode' => $episode,
  8259. 'answer' => $fullContent,
  8260. 'reasoning' => $fullReasoningContent,
  8261. 'usage' => $usage
  8262. ];
  8263. }
  8264. /**
  8265. * chatForAce的非流式版本 - 用于定时任务
  8266. * 只获取最终 type=done 的数据,并验证必要字段
  8267. *
  8268. * @param array $data 请求数据
  8269. * @return array 生成结果
  8270. */
  8271. public function chatForAceNonStream($data) {
  8272. $finalResult = null;
  8273. // 调用流式方法,只保存 type=done 的数据
  8274. foreach ($this->chatForAce($data) as $chunk) {
  8275. // 只关注最终结果
  8276. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8277. $finalResult = $chunk;
  8278. break; // 找到 done 就退出循环
  8279. }
  8280. }
  8281. // 验证最终结果
  8282. if (!$finalResult) {
  8283. return ['error' => '生成失败:未获取到最终结果'];
  8284. }
  8285. // 检查是否有错误
  8286. if (isset($finalResult['error']) && $finalResult['error']) {
  8287. return $finalResult;
  8288. }
  8289. // 验证必要字段
  8290. $episode = $finalResult['episode'] ?? [];
  8291. // 验证 roles
  8292. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8293. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8294. }
  8295. // 验证 scenes
  8296. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8297. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8298. }
  8299. // 验证 props(道具可以为空,但必须存在且为数组)
  8300. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8301. $episode['props'] = [];
  8302. }
  8303. // 验证 acts(分镜剧本)
  8304. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8305. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8306. }
  8307. // 更新验证后的 episode 数据
  8308. $finalResult['episode'] = $episode;
  8309. // 记录验证成功日志
  8310. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8311. 'roles_count' => count($episode['roles']),
  8312. 'scenes_count' => count($episode['scenes']),
  8313. 'props_count' => count($episode['props']),
  8314. 'acts_count' => count($episode['acts'])
  8315. ]);
  8316. return $finalResult;
  8317. }
  8318. /**
  8319. * 批量生成多个分集
  8320. *
  8321. * @param array $data 请求数据
  8322. * @return array 任务信息
  8323. */
  8324. public function batchGenerateEpisodes($data) {
  8325. $uid = Site::getUid();
  8326. $cpid = Site::getCpid();
  8327. $anime_id = getProp($data, 'anime_id');
  8328. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8329. if (!$anime_id) {
  8330. Utils::throwError('20003:anime_id参数缺失');
  8331. }
  8332. if ($generate_episode_number < 1) {
  8333. Utils::throwError('20003:生成集数必须大于0');
  8334. }
  8335. // 获取动漫信息
  8336. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8337. if (!$anime) {
  8338. Utils::throwError('20003:该剧集不存在');
  8339. }
  8340. // 检查是否是全能模式
  8341. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8342. Utils::throwError('20003:只有全能模式才支持批量生成');
  8343. }
  8344. // 检查是否是多剧集模式
  8345. if ((int)getProp($anime, 'is_multi') !== 1) {
  8346. Utils::throwError('20003:单剧集不支持批量生成');
  8347. }
  8348. // 获取当前已生成的最大集数
  8349. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8350. ->where('anime_id', $anime_id)
  8351. ->where('is_default', 1)
  8352. ->max('episode_number');
  8353. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8354. // 确定起始集数
  8355. $startEpisodeNumber = $currentMaxEpisode + 1;
  8356. // 计算结束集数
  8357. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8358. // 检查是否超过总集数限制
  8359. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8360. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8361. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8362. }
  8363. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  8364. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  8365. ->where('anime_id', $anime_id)
  8366. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  8367. ->whereIn('status', ['pending', 'processing', 'completed'])
  8368. ->count();
  8369. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  8370. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  8371. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  8372. if ($needEpisodeCount > 0) {
  8373. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  8374. }
  8375. $now = date('Y-m-d H:i:s');
  8376. $createdTasks = [];
  8377. $skippedTasks = [];
  8378. // 为每一集创建详情记录
  8379. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8380. // 检查是否已有该集的任务记录
  8381. $existingTask = DB::table('mp_batch_episode_generation_details')
  8382. ->where('anime_id', $anime_id)
  8383. ->where('episode_number', $episodeNumber)
  8384. ->first();
  8385. if ($existingTask) {
  8386. // 如果已存在且未完成,跳过
  8387. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8388. $skippedTasks[] = $episodeNumber;
  8389. continue;
  8390. }
  8391. // 如果是失败状态,可以重新创建(删除旧记录)
  8392. if ($existingTask->status === 'failed') {
  8393. DB::table('mp_batch_episode_generation_details')
  8394. ->where('id', $existingTask->id)
  8395. ->delete();
  8396. }
  8397. // 如果是已完成状态,也跳过
  8398. if ($existingTask->status === 'completed') {
  8399. $skippedTasks[] = $episodeNumber;
  8400. continue;
  8401. }
  8402. }
  8403. // 准备任务数据
  8404. $taskData = [
  8405. 'anime_id' => $anime_id,
  8406. 'uid' => $uid,
  8407. 'cpid' => $cpid,
  8408. 'episode_number' => $episodeNumber,
  8409. 'status' => 'pending',
  8410. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8411. 'retry_count' => 0,
  8412. 'created_at' => $now,
  8413. 'updated_at' => $now
  8414. ];
  8415. // 创建任务记录
  8416. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8417. if ($taskId) {
  8418. $createdTasks[] = $episodeNumber;
  8419. }
  8420. }
  8421. if (empty($createdTasks)) {
  8422. if (!empty($skippedTasks)) {
  8423. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8424. } else {
  8425. Utils::throwError('20003:创建批量生成任务失败');
  8426. }
  8427. }
  8428. return [
  8429. 'anime_id' => $anime_id,
  8430. 'start_episode' => $startEpisodeNumber,
  8431. 'end_episode' => $endEpisodeNumber,
  8432. 'total_episodes' => $generate_episode_number,
  8433. 'created_episodes' => $createdTasks,
  8434. 'skipped_episodes' => $skippedTasks,
  8435. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8436. "已创建: " . implode(',', $createdTasks) .
  8437. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8438. ];
  8439. }
  8440. /**
  8441. * 获取批量生成任务状态
  8442. *
  8443. * @param array $data 请求数据
  8444. * @return array 任务状态信息
  8445. */
  8446. public function getBatchGenerationTaskStatus($data) {
  8447. $anime_id = getProp($data, 'anime_id');
  8448. if (!$anime_id) {
  8449. Utils::throwError('20003:anime_id参数缺失');
  8450. }
  8451. // 获取该anime的所有任务
  8452. $tasks = DB::table('mp_batch_episode_generation_details')
  8453. ->where('anime_id', $anime_id)
  8454. ->orderBy('episode_number')
  8455. ->get()
  8456. ->map(function($item) {
  8457. return [
  8458. 'id' => $item->id,
  8459. 'episode_number' => $item->episode_number,
  8460. 'status' => $item->status,
  8461. 'error_message' => $item->error_message,
  8462. 'retry_count' => $item->retry_count,
  8463. 'created_at' => $item->created_at,
  8464. 'updated_at' => $item->updated_at,
  8465. 'completed_at' => $item->completed_at
  8466. ];
  8467. })
  8468. ->toArray();
  8469. if (empty($tasks)) {
  8470. Utils::throwError('20003:该剧集没有批量生成任务');
  8471. }
  8472. // 统计各状态数量
  8473. $totalCount = count($tasks);
  8474. $pendingCount = 0;
  8475. $processingCount = 0;
  8476. $completedCount = 0;
  8477. $failedCount = 0;
  8478. foreach ($tasks as $task) {
  8479. switch ($task['status']) {
  8480. case 'pending':
  8481. $pendingCount++;
  8482. break;
  8483. case 'processing':
  8484. $processingCount++;
  8485. break;
  8486. case 'completed':
  8487. $completedCount++;
  8488. break;
  8489. case 'failed':
  8490. $failedCount++;
  8491. break;
  8492. }
  8493. }
  8494. // 计算进度百分比
  8495. $progress = 0;
  8496. if ($totalCount > 0) {
  8497. $progress = round(($completedCount / $totalCount) * 100, 2);
  8498. }
  8499. // 判断整体状态
  8500. $overallStatus = 'processing';
  8501. if ($completedCount === $totalCount) {
  8502. $overallStatus = 'completed';
  8503. } elseif ($pendingCount === $totalCount) {
  8504. $overallStatus = 'pending';
  8505. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8506. $overallStatus = 'failed';
  8507. }
  8508. return [
  8509. 'anime_id' => $anime_id,
  8510. 'total_episodes' => $totalCount,
  8511. 'pending_count' => $pendingCount,
  8512. 'processing_count' => $processingCount,
  8513. 'completed_count' => $completedCount,
  8514. 'failed_count' => $failedCount,
  8515. 'progress' => $progress,
  8516. 'overall_status' => $overallStatus,
  8517. 'tasks' => $tasks
  8518. ];
  8519. }
  8520. /**
  8521. * 智能匹配并替换主体和场景名称
  8522. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8523. *
  8524. * @param array $episode_arr 解析后的剧集数据
  8525. * @param array $extra_roles 强制主体设定(key为主体名称)
  8526. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8527. * @return array 替换后的剧集数据
  8528. */
  8529. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8530. $replaced_count = 0;
  8531. // 1. 处理主体列表
  8532. if (!empty($episode_arr['roles'])) {
  8533. foreach ($episode_arr['roles'] as &$role) {
  8534. $generated_role_name = $role['role'] ?? '';
  8535. // 跳过旁白
  8536. if ($generated_role_name === '旁白') {
  8537. continue;
  8538. }
  8539. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8540. if (!isset($extra_roles[$generated_role_name])) {
  8541. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8542. if ($matched_role) {
  8543. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8544. $role['role'] = $matched_role;
  8545. $replaced_count++;
  8546. }
  8547. }
  8548. }
  8549. }
  8550. // 2. 处理场景列表
  8551. if (!empty($episode_arr['scenes'])) {
  8552. foreach ($episode_arr['scenes'] as &$scene) {
  8553. $generated_scene_name = $scene['scene'] ?? '';
  8554. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8555. if (!isset($extra_scenes[$generated_scene_name])) {
  8556. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8557. if ($matched_scene) {
  8558. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8559. $scene['scene'] = $matched_scene;
  8560. $replaced_count++;
  8561. }
  8562. }
  8563. }
  8564. }
  8565. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8566. if (!empty($episode_arr['acts'])) {
  8567. foreach ($episode_arr['acts'] as &$act) {
  8568. if (!empty($act['segments'])) {
  8569. foreach ($act['segments'] as &$segment) {
  8570. if (!empty($segment['segment_content'])) {
  8571. $original_content = $segment['segment_content'];
  8572. $replaced_content = $original_content;
  8573. // 替换场景名 - 在文本中查找并替换
  8574. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8575. // 尝试找到可能的短名称
  8576. $potential_short_names = [];
  8577. // 提取场景名的主要部分(冒号之前)
  8578. if (mb_strpos($full_scene_name, ':') !== false) {
  8579. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8580. $potential_short_names[] = $short_name;
  8581. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8582. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8583. $potential_short_names[] = $short_name;
  8584. }
  8585. // 替换场景字段中的短名称
  8586. foreach ($potential_short_names as $short_name) {
  8587. if ($short_name !== $full_scene_name) {
  8588. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8589. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8590. if ($new_content !== $replaced_content) {
  8591. $replaced_content = $new_content;
  8592. $replaced_count++;
  8593. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8594. }
  8595. }
  8596. }
  8597. }
  8598. // 替换配音角色名(跳过旁白)
  8599. foreach (array_keys($extra_roles) as $full_role_name) {
  8600. if ($full_role_name === '旁白') {
  8601. continue;
  8602. }
  8603. // 尝试找到可能的短名称
  8604. $potential_short_names = [];
  8605. // 提取角色名的主要部分(短横线之前)
  8606. if (mb_strpos($full_role_name, '-') !== false) {
  8607. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8608. $potential_short_names[] = $short_name;
  8609. }
  8610. // 替换配音台词中的短名称
  8611. foreach ($potential_short_names as $short_name) {
  8612. if ($short_name !== $full_role_name) {
  8613. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8614. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8615. if ($new_content !== $replaced_content) {
  8616. $replaced_content = $new_content;
  8617. $replaced_count++;
  8618. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8619. }
  8620. }
  8621. }
  8622. }
  8623. // 如果有替换,更新segment_content
  8624. if ($replaced_content !== $original_content) {
  8625. $segment['segment_content'] = $replaced_content;
  8626. }
  8627. }
  8628. }
  8629. }
  8630. }
  8631. }
  8632. if ($replaced_count > 0) {
  8633. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8634. 'replaced_count' => $replaced_count
  8635. ]);
  8636. }
  8637. return $episode_arr;
  8638. }
  8639. /**
  8640. * 查找匹配的名称
  8641. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8642. *
  8643. * @param string $generated_name 生成的名称
  8644. * @param array $expected_names 预期的名称列表
  8645. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8646. */
  8647. private function findMatchingName($generated_name, $expected_names) {
  8648. if (empty($generated_name)) {
  8649. return null;
  8650. }
  8651. // 尝试精确匹配
  8652. if (in_array($generated_name, $expected_names)) {
  8653. return $generated_name;
  8654. }
  8655. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8656. foreach ($expected_names as $expected_name) {
  8657. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8658. if (mb_strpos($expected_name, $generated_name) === 0) {
  8659. return $expected_name;
  8660. }
  8661. }
  8662. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8663. // 这样可以处理一些变体,但优先级较低
  8664. foreach ($expected_names as $expected_name) {
  8665. if (mb_strpos($expected_name, $generated_name) !== false) {
  8666. return $expected_name;
  8667. }
  8668. }
  8669. return null;
  8670. }
  8671. /**
  8672. * 重新生成分段剧本
  8673. * @param array $data 包含以下字段:
  8674. * - prompt: string|null 用户修改要求(可选)
  8675. * - template_id: int|null 提示词模板ID(可选)
  8676. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8677. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8678. * @return array 返回生成结果
  8679. */
  8680. public function regenerateSegmentScript($data) {
  8681. $uid = Site::getUid();
  8682. $prompt = trim((string)getProp($data, 'prompt', ''));
  8683. $template_id = getProp($data, 'template_id', 0);
  8684. $act_id = getProp($data, 'act_id', 0);
  8685. $episode_id = getProp($data, 'episode_id', 0);
  8686. // 验证:prompt和template_id至少提供一个
  8687. if (empty($prompt) && empty($template_id)) {
  8688. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8689. }
  8690. // 验证:act_id和episode_id二选一
  8691. if (empty($act_id) && empty($episode_id)) {
  8692. Utils::throwError('20003:请提供片段ID或剧集ID');
  8693. }
  8694. if (!empty($act_id) && !empty($episode_id)) {
  8695. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8696. }
  8697. // 积分余额预检(仅剧集ID模式收费)
  8698. if (!empty($episode_id)) {
  8699. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8700. }
  8701. // 如果提供了template_id,获取模板提示词
  8702. $template_prompt = '';
  8703. if ($template_id > 0) {
  8704. $template = DB::table('mp_prompt_templates')
  8705. ->where('id', $template_id)
  8706. ->where('is_deleted', 0)
  8707. ->first();
  8708. if (!$template) {
  8709. Utils::throwError('20003:提示词模板不存在或已删除');
  8710. }
  8711. $template_prompt = $template->template_prompt ?? '';
  8712. }
  8713. // 合并用户提示词和模板提示词
  8714. $final_prompt = '';
  8715. if (!empty($template_prompt)) {
  8716. $final_prompt = $template_prompt;
  8717. if (!empty($prompt)) {
  8718. $final_prompt .= "\n\n补充要求:" . $prompt;
  8719. }
  8720. } else {
  8721. $final_prompt = $prompt;
  8722. }
  8723. // 获取需要重新生成的内容参考
  8724. $reference_content = '';
  8725. $target_episode_id = 0;
  8726. $target_anime_id = 0;
  8727. $target_episode_number = 0;
  8728. if ($act_id > 0) {
  8729. // 单个片段模式:获取该片段的内容
  8730. $segment = DB::table('mp_episode_segments')
  8731. ->where('id', $act_id)
  8732. ->first();
  8733. if (!$segment) {
  8734. Utils::throwError('20003:片段不存在');
  8735. }
  8736. $target_episode_id = $segment->episode_id;
  8737. $target_anime_id = $segment->anime_id;
  8738. $target_episode_number = $segment->episode_number;
  8739. $reference_content = $segment->act_content ?? '';
  8740. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8741. } else {
  8742. // 整个剧集模式:获取所有片段的内容
  8743. $segments = DB::table('mp_episode_segments')
  8744. ->where('episode_id', $episode_id)
  8745. ->orderBy('act_number')
  8746. ->get();
  8747. if ($segments->isEmpty()) {
  8748. Utils::throwError('20003:该剧集没有片段数据');
  8749. }
  8750. $target_episode_id = $episode_id;
  8751. $target_anime_id = $segments[0]->anime_id;
  8752. $target_episode_number = $segments[0]->episode_number;
  8753. // 拼接所有片段内容,保留格式用于AI理解
  8754. $act_contents = [];
  8755. foreach ($segments as $seg) {
  8756. $act_number = $seg->act_number;
  8757. $act_content = $seg->act_content ?? '';
  8758. if (!empty($act_content)) {
  8759. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8760. }
  8761. }
  8762. $reference_content = implode("\n\n", $act_contents);
  8763. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8764. if ($episode_content) {
  8765. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8766. }else {
  8767. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8768. }
  8769. }
  8770. if (empty($reference_content)) {
  8771. Utils::throwError('20003:没有可参考的片段内容');
  8772. }
  8773. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8774. $episode = DB::table('mp_anime_episodes')
  8775. ->where('id', $target_episode_id)
  8776. ->first();
  8777. if (!$episode) {
  8778. Utils::throwError('20003:剧集不存在');
  8779. }
  8780. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8781. $anime_script_id = getProp($anime, 'script_id');
  8782. $intro = $episode->intro ?? '';
  8783. $art_style = $episode->art_style ?? '';
  8784. $roles = json_decode($episode->roles ?? '[]', true);
  8785. $scenes = json_decode($episode->scenes ?? '[]', true);
  8786. $props = json_decode($episode->props ?? '[]', true);
  8787. // 构建提示词中的主体列表和场景列表参考
  8788. $roles_ref = '';
  8789. if (!empty($roles) && is_array($roles)) {
  8790. $roles_list = [];
  8791. foreach ($roles as $role) {
  8792. $role_name = getProp($role, 'role', '');
  8793. $role_desc = getProp($role, 'description', '');
  8794. $pic_prompt = getProp($role, 'pic_prompt', '');
  8795. $voice_prompt = getProp($role, 'voice_prompt', '');
  8796. if (!empty($role_name)) {
  8797. $role_line = $role_name;
  8798. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8799. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8800. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8801. $roles_list[] = $role_line;
  8802. }
  8803. }
  8804. if (!empty($roles_list)) {
  8805. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8806. }
  8807. }
  8808. $scenes_ref = '';
  8809. if (!empty($scenes) && is_array($scenes)) {
  8810. $scenes_list = [];
  8811. foreach ($scenes as $scene) {
  8812. $scene_name = getProp($scene, 'scene', '');
  8813. $scene_desc = getProp($scene, 'description', '');
  8814. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8815. if (!empty($scene_name)) {
  8816. $scene_line = $scene_name;
  8817. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8818. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8819. $scenes_list[] = $scene_line;
  8820. }
  8821. }
  8822. if (!empty($scenes_list)) {
  8823. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8824. }
  8825. }
  8826. $props_ref = '';
  8827. if (!empty($props) && is_array($props)) {
  8828. $props_list = [];
  8829. foreach ($props as $prop) {
  8830. $prop_name = getProp($prop, 'prop', '');
  8831. $prop_desc = getProp($prop, 'description', '');
  8832. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8833. if (!empty($prop_name)) {
  8834. $prop_line = $prop_name;
  8835. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8836. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8837. $props_list[] = $prop_line;
  8838. }
  8839. }
  8840. if (!empty($props_list)) {
  8841. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8842. }
  8843. }
  8844. // 构建美术风格参考
  8845. $art_style_ref = '';
  8846. if (!empty($art_style)) {
  8847. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8848. }
  8849. // 构建内容简介参考
  8850. $intro_ref = '';
  8851. if (!empty($intro)) {
  8852. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8853. }
  8854. // 构建完整的AI提示词
  8855. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8856. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8857. $user_prompt .= $intro_ref;
  8858. $user_prompt .= $art_style_ref;
  8859. $user_prompt .= $reference_content;
  8860. // $user_prompt .= $roles_ref;
  8861. // $user_prompt .= $scenes_ref;
  8862. $system_prompt = "\n\n【强制要求】\n";
  8863. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8864. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8865. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8866. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8867. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8868. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8869. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8870. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8871. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8872. ###分段剧本
  8873. 片段数量:8
  8874. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8875. ##片段1
  8876. 时长:12s
  8877. 分镜1
  8878. 出场角色:刀疤脸
  8879. 场景:边境小镇街道
  8880. 出场道具:酒杯-高脚杯
  8881. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8882. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8883. 配音台词:
  8884. 背景音效:
  8885. 分镜2
  8886. 出场角色:刀疤脸
  8887. 场景:悦来酒馆
  8888. 出场道具:酒杯-高脚杯
  8889. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8890. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8891. 配音台词:
  8892. 背景音效:
  8893. 分镜3
  8894. 出场角色:刀疤脸
  8895. 场景:悦来酒馆
  8896. 出场道具:酒杯-高脚杯
  8897. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8898. 运镜:从中景推向令牌特写。
  8899. 配音台词:
  8900. 背景音效:
  8901. 分镜4
  8902. 出场角色:刀疤脸
  8903. 场景:悦来酒馆
  8904. 出场道具:酒杯-高脚杯
  8905. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8906. 运镜:极速推向酒水溅起的瞬间。
  8907. 配音台词:
  8908. 背景音效:
  8909. 分镜5
  8910. 出场角色:刀疤脸
  8911. 场景:悦来酒馆
  8912. 出场道具:酒杯-高脚杯
  8913. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8914. 运镜:固定机位,利用倾斜构图制造压迫感。
  8915. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8916. 背景音效:";
  8917. // 获取模型配置
  8918. $model = getProp($data, 'model');
  8919. if (!$model) {
  8920. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8921. }
  8922. // 验证模型是否在可用模型表中
  8923. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8924. $model = 'deepseek-v4-pro';
  8925. }
  8926. // 模型兼容性处理
  8927. $thinkingMode = 'disabled';
  8928. $reasoningEffort = 'high';
  8929. if ($model === 'deepseek-chat') {
  8930. $model = 'deepseek-v4-flash';
  8931. $thinkingMode = 'disabled';
  8932. } elseif ($model === 'deepseek-reasoner') {
  8933. $model = 'deepseek-v4-flash';
  8934. $thinkingMode = 'enabled';
  8935. }
  8936. // 构建消息
  8937. $messages = [
  8938. [
  8939. 'role' => 'system',
  8940. 'content' => $system_prompt
  8941. ],
  8942. [
  8943. 'role' => 'user',
  8944. 'content' => $user_prompt
  8945. ]
  8946. ];
  8947. // dd($messages);
  8948. // 构建请求参数
  8949. $post_data = [
  8950. 'model' => $model,
  8951. 'messages' => $messages,
  8952. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8953. 'frequency_penalty' => 0,
  8954. 'presence_penalty' => 0,
  8955. 'response_format' => ['type' => 'text'],
  8956. 'thinking' => ['type' => $thinkingMode],
  8957. 'stream' => false // 非流式输出
  8958. ];
  8959. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8960. // 调用AI生成新的分段剧本
  8961. try {
  8962. $fullContent = '';
  8963. $usage = [];
  8964. // 根据模型类型选择调用方法
  8965. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8966. // DeepSeek 官方模型使用 DeepSeek API
  8967. $chatResult = $this->chatOnly($post_data);
  8968. } else if (in_array($model, $this->gpt_text_models)) {
  8969. // GPT 模型使用 TokenRouter API
  8970. $chatResult = $this->gpt54ChatOnly($post_data);
  8971. } else {
  8972. // 其他模型使用火山引擎API
  8973. $chatResult = $this->volcEngineChatCompletion($post_data);
  8974. }
  8975. if (is_array($chatResult)) {
  8976. $fullContent = $chatResult['fullContent'] ?? '';
  8977. $usage = $chatResult['usage'] ?? [];
  8978. }
  8979. $generated_content = $fullContent;
  8980. if (empty($generated_content)) {
  8981. Utils::throwError('20003:AI生成内容为空,请重试');
  8982. }
  8983. // 解析生成的内容 - 按片段分割
  8984. $parsed_segments = [];
  8985. // 先在开头添加换行符,确保第1片段也能被正确分割
  8986. $normalizedText = "\n" . $generated_content;
  8987. $parts = preg_split('/\n\s*##/', $normalizedText);
  8988. foreach ($parts as $part) {
  8989. $part = trim($part);
  8990. if (empty($part)) continue;
  8991. // 匹配"片段X"格式
  8992. if (!preg_match('/^片段\d+/', $part)) {
  8993. continue;
  8994. }
  8995. // 分离标题和内容
  8996. $lines = explode("\n", $part, 2);
  8997. $actTitle = trim($lines[0]);
  8998. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8999. // 解析标题,提取序号
  9000. $actNumber = 0;
  9001. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  9002. $actNumber = intval($segmentTitleMatch[1]);
  9003. } else {
  9004. $actNumber = count($parsed_segments) + 1;
  9005. }
  9006. // 提取时长(仅保留数字)
  9007. $actDuration = 0;
  9008. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  9009. $actDurationStr = trim($actDurationMatch[1]);
  9010. // 提取数字部分(支持整数和小数)
  9011. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  9012. $actDuration = (float)$numMatch[1];
  9013. }
  9014. }
  9015. // 清理act_content:去除时长、旁白音色等非分镜内容行
  9016. // 只保留分镜内容,并确保分镜标记使用【】格式
  9017. $cleaned_content = '';
  9018. $content_lines = explode("\n", $actContent);
  9019. $is_capturing = false; // 标记是否开始捕获分镜内容
  9020. $count = 0;
  9021. foreach ($content_lines as $line) {
  9022. $trimmed_line = trim($line);
  9023. // 跳过时长和旁白音色行
  9024. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  9025. continue;
  9026. }
  9027. // 检测是否是分镜开始
  9028. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  9029. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  9030. $count++;
  9031. $is_capturing = true;
  9032. // 如果没有【】,则添加
  9033. if (!preg_match('/^【/u', $trimmed_line)) {
  9034. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  9035. }
  9036. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  9037. }
  9038. // 如果已经开始捕获,则添加该行
  9039. if ($is_capturing && !empty($trimmed_line)) {
  9040. $cleaned_content .= $trimmed_line."\n";
  9041. }
  9042. }
  9043. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  9044. $parsed_segments[] = [
  9045. 'act_number' => $actNumber,
  9046. 'act_title' => $actTitle,
  9047. 'act_duration' => $actDuration,
  9048. 'act_content' => $cleaned_content,
  9049. ];
  9050. }
  9051. if (empty($parsed_segments)) {
  9052. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  9053. }
  9054. // 收集所有资产名称(角色、场景、道具)
  9055. $product_names = [];
  9056. // 收集角色名称
  9057. if (!empty($roles) && is_array($roles)) {
  9058. foreach ($roles as $role) {
  9059. $role_name = getProp($role, 'role', '');
  9060. if (!empty($role_name)) {
  9061. $product_names[] = $role_name;
  9062. }
  9063. }
  9064. }
  9065. // 收集场景名称
  9066. if (!empty($scenes) && is_array($scenes)) {
  9067. foreach ($scenes as $scene) {
  9068. $scene_name = getProp($scene, 'scene', '');
  9069. if (!empty($scene_name)) {
  9070. $product_names[] = $scene_name;
  9071. }
  9072. }
  9073. }
  9074. // 收集道具名称
  9075. if (!empty($props) && is_array($props)) {
  9076. foreach ($props as $prop) {
  9077. $prop_name = getProp($prop, 'prop', '');
  9078. if (!empty($prop_name)) {
  9079. $product_names[] = $prop_name;
  9080. }
  9081. }
  9082. }
  9083. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9084. $product_names = array_unique($product_names);
  9085. usort($product_names, function($a, $b) {
  9086. return mb_strlen($b) - mb_strlen($a);
  9087. });
  9088. // 处理每个片段的 act_show_content
  9089. foreach ($parsed_segments as &$segment) {
  9090. $act_content = getProp($segment, 'act_content', '');
  9091. if (empty($act_content)) {
  9092. $segment['act_show_content'] = '';
  9093. continue;
  9094. }
  9095. $processed_content = $act_content;
  9096. // 统一替换所有资产名称为 {资产名} 格式
  9097. // 使用占位符避免嵌套替换问题
  9098. $placeholder_map = [];
  9099. $placeholder_index = 0;
  9100. foreach ($product_names as $product_name) {
  9101. // 转义特殊字符
  9102. $escaped_product = preg_quote($product_name, '/');
  9103. // 检查是否匹配且未被 {} 包裹
  9104. $processed_content = preg_replace_callback(
  9105. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9106. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9107. // 使用唯一占位符
  9108. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9109. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9110. $placeholder_index++;
  9111. return $placeholder;
  9112. },
  9113. $processed_content
  9114. );
  9115. }
  9116. // 将所有占位符替换回实际内容
  9117. foreach ($placeholder_map as $placeholder => $replacement) {
  9118. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9119. }
  9120. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9121. $shot_counter = 0;
  9122. $processed_content = preg_replace_callback(
  9123. '/【(?:镜头|分镜)(\d+)】/u',
  9124. function($matches) use (&$shot_counter) {
  9125. $shot_counter++;
  9126. return '【镜头' . $shot_counter . '】';
  9127. },
  9128. $processed_content
  9129. );
  9130. $segment['act_show_content'] = $processed_content;
  9131. }
  9132. unset($segment); // 解除引用
  9133. // 保存到数据库
  9134. $now = date('Y-m-d H:i:s');
  9135. $saved_acts = []; // 用于记录保存后的片段信息
  9136. if ($act_id > 0) {
  9137. // 单个片段模式:更新单条记录
  9138. if (count($parsed_segments) > 0) {
  9139. $new_segment = $parsed_segments[0];
  9140. $update_data = [
  9141. 'act_content' => getProp($new_segment, 'act_content', ''),
  9142. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9143. 'act_title' => getProp($new_segment, 'act_title', ''),
  9144. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9145. 'updated_at' => $now,
  9146. ];
  9147. DB::table('mp_episode_segments')
  9148. ->where('id', $act_id)
  9149. ->update($update_data);
  9150. // 获取更新后的记录
  9151. $updated_act = DB::table('mp_episode_segments')
  9152. ->where('id', $act_id)
  9153. ->first();
  9154. if ($updated_act) {
  9155. $saved_acts[] = [
  9156. 'act_id' => $updated_act->id,
  9157. 'act_number' => $updated_act->act_number,
  9158. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9159. 'act_content' => $updated_act->act_content,
  9160. 'act_show_content' => $updated_act->act_show_content,
  9161. 'video_url' => $updated_act->video_url ?? '',
  9162. 'video_duration' => $updated_act->video_duration ?? 0,
  9163. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9164. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9165. ];
  9166. }
  9167. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9168. }
  9169. } else {
  9170. // 整个剧集模式:删除原有记录并批量保存新记录
  9171. DB::beginTransaction();
  9172. try {
  9173. // 删除原有的所有片段记录
  9174. DB::table('mp_episode_segments')
  9175. ->where('episode_id', $target_episode_id)
  9176. ->delete();
  9177. // 批量插入新的片段记录
  9178. $segments_to_insert = [];
  9179. foreach ($parsed_segments as $index => $segment) {
  9180. $act_number = $index + 1;
  9181. $segments_to_insert[] = [
  9182. 'anime_id' => $target_anime_id,
  9183. 'episode_id' => $target_episode_id,
  9184. 'episode_number' => $target_episode_number,
  9185. 'act_number' => $act_number,
  9186. 'act_title' => getProp($segment, 'act_title', ''),
  9187. 'act_duration' => getProp($segment, 'act_duration', 0),
  9188. 'act_content' => getProp($segment, 'act_content', ''),
  9189. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9190. 'created_at' => $now,
  9191. 'updated_at' => $now,
  9192. ];
  9193. }
  9194. if (!empty($segments_to_insert)) {
  9195. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9196. }
  9197. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9198. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9199. 'anime_id' => $target_anime_id,
  9200. 'episode_id' => $target_episode_id,
  9201. ]);
  9202. DB::commit();
  9203. // 查询保存后的所有片段记录
  9204. $saved_segments = DB::table('mp_episode_segments')
  9205. ->where('episode_id', $target_episode_id)
  9206. ->orderBy('act_number')
  9207. ->get();
  9208. foreach ($saved_segments as $saved_segment) {
  9209. $saved_acts[] = [
  9210. 'act_id' => $saved_segment->id,
  9211. 'act_number' => $saved_segment->act_number,
  9212. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9213. 'act_content' => $saved_segment->act_content,
  9214. 'act_show_content' => $saved_segment->act_show_content,
  9215. 'video_url' => $saved_segment->video_url ?? '',
  9216. 'video_duration' => $saved_segment->video_duration ?? 0,
  9217. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9218. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9219. ];
  9220. }
  9221. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9222. 'episode_id' => $target_episode_id,
  9223. 'segments_count' => count($segments_to_insert)
  9224. ]);
  9225. } catch (\Exception $e) {
  9226. DB::rollBack();
  9227. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9228. Utils::throwError('20003:保存失败,请重试');
  9229. }
  9230. }
  9231. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9232. return [
  9233. 'anime_id' => $target_anime_id,
  9234. 'episode_id' => $target_episode_id,
  9235. 'title' => getProp($episode, 'title', ''),
  9236. 'episode_number' => $target_episode_number,
  9237. 'is_generated' => getProp($episode, 'is_generated', 0),
  9238. 'acts' => $saved_acts,
  9239. ];
  9240. } catch (\Exception $e) {
  9241. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9242. throw $e;
  9243. }
  9244. }
  9245. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9246. {
  9247. $episode_arr = [
  9248. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9249. 'intro' => getProp($script_arr, 'intro'),
  9250. 'art_style' => getProp($script_arr, 'art_style'),
  9251. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9252. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9253. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9254. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9255. ];
  9256. if (empty($episode_arr['acts'])) {
  9257. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9258. if (!empty($fallback_episode_arr['acts'])) {
  9259. $episode_arr = array_merge($fallback_episode_arr, [
  9260. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9261. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9262. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9263. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9264. ]);
  9265. }
  9266. }
  9267. // if (!getProp($episode_arr, 'episode_title')) {
  9268. // $episode_title = '';
  9269. // $episodes = getProp($script_arr, 'episodes', []);
  9270. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9271. // $episode_title = '第1集:' . $episodes[0]['title'];
  9272. // }
  9273. // if (!$episode_title) {
  9274. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9275. // }
  9276. // $episode_arr['episode_title'] = $episode_title;
  9277. // }
  9278. return $episode_arr;
  9279. }
  9280. private function saveEpisodeVersionData(
  9281. int $anime_id,
  9282. int $episode_number,
  9283. array $episode_arr,
  9284. array $existing_roles,
  9285. array $existing_scenes,
  9286. array $existing_props,
  9287. $current_episode,
  9288. $base_episode,
  9289. bool $is_regenerate_version,
  9290. string $content,
  9291. string $now,
  9292. array $ref_products = []
  9293. ): array {
  9294. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9295. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9296. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9297. // 过滤掉关键字段为空的条目
  9298. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9299. return !empty($item['role'] ?? null);
  9300. }));
  9301. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9302. return !empty($item['scene'] ?? null);
  9303. }));
  9304. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9305. return !empty($item['prop'] ?? null);
  9306. }));
  9307. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9308. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9309. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9310. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9311. $ace_mode = getProp($anime, 'ace_mode');
  9312. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9313. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9314. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9315. $global_roles = is_array($global_roles) ? $global_roles : [];
  9316. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9317. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9318. $art_style_type = getProp($anime, 'art_style_type');
  9319. // 检查并创建 roles 的图片生成任务
  9320. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9321. // 检查并创建 scenes 的图片生成任务
  9322. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9323. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9324. if ($arr && is_array($arr)) {
  9325. $merged_roles = $arr['roles'];
  9326. $merged_scenes = $arr['scenes'];
  9327. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9328. }
  9329. // 确保数据是数组类型
  9330. if (!is_array($merged_roles)) {
  9331. dLog('deepseek')->error('merged_roles不是数组类型', [
  9332. 'type' => gettype($merged_roles),
  9333. 'value' => $merged_roles
  9334. ]);
  9335. $merged_roles = [];
  9336. }
  9337. if (!is_array($merged_scenes)) {
  9338. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9339. 'type' => gettype($merged_scenes),
  9340. 'value' => $merged_scenes
  9341. ]);
  9342. $merged_scenes = [];
  9343. }
  9344. if (!is_array($merged_props)) {
  9345. dLog('deepseek')->error('merged_props不是数组类型', [
  9346. 'type' => gettype($merged_props),
  9347. 'value' => $merged_props
  9348. ]);
  9349. $merged_props = [];
  9350. }
  9351. // 同步新出现的主体和场景到全局
  9352. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9353. $role_arr = [];
  9354. foreach ($merged_roles as $item) {
  9355. $role_arr[$item['role']] = $item;
  9356. }
  9357. $version_count = DB::table('mp_anime_episodes')
  9358. ->where('anime_id', $anime_id)
  9359. ->where('episode_number', $episode_number)
  9360. ->count('id');
  9361. $episode = [
  9362. 'anime_id' => $anime_id,
  9363. 'episode_number' => $episode_number,
  9364. 'title' => getProp($episode_arr, 'episode_title'),
  9365. 'content' => $content,
  9366. 'intro' => getProp($episode_arr, 'intro'),
  9367. 'art_style' => getProp($episode_arr, 'art_style'),
  9368. 'roles' => json_encode($merged_roles, 256),
  9369. 'scenes' => json_encode($merged_scenes, 256),
  9370. 'props' => json_encode($merged_props, 256),
  9371. 'generate_status' => '待执行',
  9372. 'generate_at' => $now,
  9373. 'is_default' => 1,
  9374. 'updated_at' => $now,
  9375. ];
  9376. $del_flag = false;
  9377. if ($is_regenerate_version) {
  9378. DB::table('mp_anime_episodes')
  9379. ->where('anime_id', $anime_id)
  9380. ->where('episode_number', $episode_number)
  9381. ->update(['is_default' => 0, 'updated_at' => $now]);
  9382. $episode['sequence'] = $version_count + 1;
  9383. $episode['created_at'] = $now;
  9384. $episode['cpid'] = Site::getCpid();
  9385. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9386. if (!$episode_id) {
  9387. Utils::throwError('20003:创建剧集版本失败');
  9388. }
  9389. } else {
  9390. $target_episode = $current_episode ?: $base_episode;
  9391. if ($target_episode) {
  9392. $episode_id = getProp($target_episode, 'id');
  9393. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9394. DB::table('mp_anime_episodes')
  9395. ->where('anime_id', $anime_id)
  9396. ->where('episode_number', $episode_number)
  9397. ->where('id', '<>', $episode_id)
  9398. ->update(['is_default' => 0, 'updated_at' => $now]);
  9399. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9400. if ($boolen === false) {
  9401. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9402. Utils::throwError('20003:分集内容保存失败');
  9403. }
  9404. $del_flag = true;
  9405. } else {
  9406. DB::table('mp_anime_episodes')
  9407. ->where('anime_id', $anime_id)
  9408. ->where('episode_number', $episode_number)
  9409. ->update(['is_default' => 0, 'updated_at' => $now]);
  9410. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9411. $episode['created_at'] = $now;
  9412. $episode['cpid'] = Site::getCpid();
  9413. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9414. if (!$episode_id) {
  9415. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9416. Utils::throwError('20003:分集内容保存失败');
  9417. }
  9418. }
  9419. }
  9420. $segments = [];
  9421. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9422. // 如果是第2集及以后,获取上一集的主体音色数据
  9423. $previous_roles_voice = [];
  9424. if ($episode_number >= 2) {
  9425. $previous_episode = DB::table('mp_anime_episodes')
  9426. ->where('anime_id', $anime_id)
  9427. ->where('episode_number', $episode_number - 1)
  9428. ->where('is_default', 1)
  9429. ->first();
  9430. if ($previous_episode) {
  9431. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9432. if (is_array($previous_roles)) {
  9433. foreach ($previous_roles as $prev_role) {
  9434. $role_name = getProp($prev_role, 'role');
  9435. if ($role_name) {
  9436. $previous_roles_voice[$role_name] = [
  9437. 'voice_name' => getProp($prev_role, 'voice_name'),
  9438. 'voice_type' => getProp($prev_role, 'voice_type'),
  9439. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9440. ];
  9441. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9442. if ($voice_prompt) {
  9443. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9444. }
  9445. }
  9446. }
  9447. }
  9448. }
  9449. }
  9450. // 将继承的音色数据同步到当前集的主体列表
  9451. if (!empty($previous_roles_voice)) {
  9452. foreach ($merged_roles as &$role) {
  9453. $role_name = getProp($role, 'role');
  9454. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9455. // 强制继承上一集的音色数据
  9456. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9457. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9458. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9459. // 如果上一集有 voice_prompt 则继承,否则跳过
  9460. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9461. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9462. }
  9463. }
  9464. }
  9465. unset($role); // 解除引用
  9466. // 更新 role_arr 以便后续使用
  9467. $role_arr = [];
  9468. foreach ($merged_roles as $item) {
  9469. $role_arr[$item['role']] = $item;
  9470. }
  9471. }
  9472. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9473. $emotion_list = array_flip($emotion_list);
  9474. foreach ($acts as $act) {
  9475. $act_segments = getProp($act, 'segments', []);
  9476. if (!is_array($act_segments)) {
  9477. continue;
  9478. }
  9479. if ((int)$ace_mode === 1) {
  9480. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9481. $merged_parts = [];
  9482. foreach ($act_segments as $seg) {
  9483. $seg_num = getProp($seg, 'segment_number');
  9484. $seg_content = getProp($seg, 'segment_content');
  9485. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9486. }
  9487. $act_content = implode("\n", $merged_parts);
  9488. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9489. $segments[] = [
  9490. 'anime_id' => $anime_id,
  9491. 'episode_id' => $episode_id,
  9492. 'episode_number' => $episode_number,
  9493. 'act_number' => getProp($act, 'act_number'),
  9494. 'act_title' => getProp($act, 'act_title'),
  9495. 'act_duration' => getProp($act, 'act_duration'),
  9496. 'act_content' => $act_content,
  9497. 'created_at' => $now,
  9498. 'updated_at' => $now
  9499. ];
  9500. } else {
  9501. foreach ($act_segments as $segment) {
  9502. $voice_actor = getProp($segment, 'voice_actor');
  9503. // 优先从上一集继承音色数据
  9504. $timbre_info = [];
  9505. if (isset($previous_roles_voice[$voice_actor])) {
  9506. // 从上一集继承音色数据
  9507. $timbre_info = $previous_roles_voice[$voice_actor];
  9508. } elseif (isset($role_arr[$voice_actor])) {
  9509. // 使用当前集的主体音色数据
  9510. $timbre_info = $role_arr[$voice_actor];
  9511. }
  9512. $voice_type = getProp($timbre_info, 'voice_type');
  9513. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9514. if ($timbre_emotion) {
  9515. $timbre_emotion = explode(',', $timbre_emotion);
  9516. } else {
  9517. $timbre_emotion = [];
  9518. }
  9519. $emotion = getProp($segment, 'emotion', '中性');
  9520. if (!in_array($emotion, $timbre_emotion)) {
  9521. $emotion = '中性';
  9522. }
  9523. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9524. $segments[] = [
  9525. 'anime_id' => $anime_id,
  9526. 'episode_id' => $episode_id,
  9527. 'episode_number' => $episode_number,
  9528. 'act_number' => getProp($act, 'act_number'),
  9529. 'act_title' => getProp($act, 'act_title'),
  9530. 'act_duration' => getProp($act, 'act_duration'),
  9531. 'segment_id' => getProp($segment, 'segment_id'),
  9532. 'segment_number' => getProp($segment, 'segment_number'),
  9533. 'segment_content' => getProp($segment, 'segment_content'),
  9534. 'description' => getProp($segment, 'description'),
  9535. 'composition' => getProp($segment, 'composition'),
  9536. 'camera_movement' => getProp($segment, 'camera_movement'),
  9537. 'voice_actor' => $voice_actor,
  9538. 'dialogue' => getProp($segment, 'dialogue'),
  9539. 'frame_type' => getProp($segment, 'frame_type'),
  9540. 'scene' => getProp($segment, 'scene'),
  9541. 'characters' => getProp($segment, 'characters'),
  9542. 'tail_frame' => getProp($segment, 'tail_frame'),
  9543. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9544. 'voice_type' => $voice_type,
  9545. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9546. 'emotion' => $emotion,
  9547. 'emotion_type' => $emotion_type,
  9548. 'gender' => getProp($segment, 'gender', '0'),
  9549. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9550. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9551. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9552. 'pitch' => getProp($segment, 'pitch', 0),
  9553. 'created_at' => $now,
  9554. 'updated_at' => $now
  9555. ];
  9556. }
  9557. }
  9558. }
  9559. if ($segments) {
  9560. if ($del_flag) {
  9561. DB::table('mp_episode_segments')
  9562. ->where('anime_id', $anime_id)
  9563. ->where('episode_id', $episode_id)
  9564. ->delete();
  9565. }
  9566. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9567. if (!$boolen) {
  9568. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9569. Utils::throwError('20003:分镜内容保存失败');
  9570. }
  9571. }
  9572. dLog('deepseek')->info('segments', $segments);
  9573. // ace_mode=1: acts 返回值按合并格式调整
  9574. if ((int)$ace_mode === 1) {
  9575. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9576. $act_map = [];
  9577. foreach ($table_act_data as $item) {
  9578. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9579. }
  9580. $restructured_acts = [];
  9581. foreach ($acts as $act) {
  9582. $act_segments = getProp($act, 'segments', []);
  9583. if (!is_array($act_segments)) {
  9584. continue;
  9585. }
  9586. $merged_parts = [];
  9587. foreach ($act_segments as $seg) {
  9588. $seg_num = getProp($seg, 'segment_number');
  9589. $seg_content = getProp($seg, 'segment_content');
  9590. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9591. }
  9592. $act_content = implode("\n", $merged_parts);
  9593. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9594. $restructured_acts[] = [
  9595. 'anime_id' => $anime_id,
  9596. 'episode_id' => $episode_id,
  9597. 'episode_number' => $episode_number,
  9598. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9599. 'act_number' => getProp($act, 'act_number'),
  9600. 'act_title' => getProp($act, 'act_title'),
  9601. 'act_duration' => getProp($act, 'act_duration'),
  9602. 'act_content' => $act_content,
  9603. 'created_at' => $now,
  9604. 'updated_at' => $now,
  9605. ];
  9606. }
  9607. $acts = $restructured_acts;
  9608. }
  9609. $episode['episode_id'] = $episode_id;
  9610. $episode['roles'] = $merged_roles;
  9611. $episode['scenes'] = $merged_scenes;
  9612. $episode['props'] = $merged_props;
  9613. $episode['acts'] = $acts;
  9614. return [
  9615. 'episode' => $episode,
  9616. 'episode_id' => $episode_id,
  9617. 'merged_roles' => $merged_roles,
  9618. 'merged_scenes' => $merged_scenes,
  9619. 'merged_props' => $merged_props,
  9620. ];
  9621. }
  9622. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9623. {
  9624. $content = '';
  9625. foreach ($items as $item) {
  9626. $name = trim((string)getProp($item, $nameKey));
  9627. if ($name === '' || $name === '旁白') {
  9628. continue;
  9629. }
  9630. $description = trim((string)getProp($item, 'description'));
  9631. $content .= $name . ': ' . $description;
  9632. if ($nameKey == 'role') {
  9633. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9634. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9635. $voice_name = trim(getProp($item, 'voice_name'));
  9636. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9637. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9638. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9639. }else {
  9640. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9641. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9642. }
  9643. $content .= "\n";
  9644. }
  9645. return trim($content);
  9646. }
  9647. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9648. if ((int)$sequence <= 0) {
  9649. return [];
  9650. }
  9651. $origin_content = '';
  9652. if ($content) {
  9653. $origin_content = '本集剧情内容:'.$content;
  9654. }else {
  9655. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9656. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9657. }
  9658. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9659. // 获取分集信息
  9660. $episode = DB::table('mp_anime_episodes')
  9661. ->where('anime_id', $animeId)
  9662. ->where('episode_number', $sequence)
  9663. ->where('is_default', 1)
  9664. ->first();
  9665. if (!$episode) {
  9666. return [];
  9667. }
  9668. $episode_id = getProp($episode, 'id');
  9669. $episode_number = getProp($episode, 'episode_number');
  9670. $title = getProp($episode, 'title');
  9671. $intro = getProp($episode, 'intro');
  9672. $art_style = getProp($episode, 'art_style');
  9673. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9674. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9675. // 组装纯文本内容
  9676. $content = '';
  9677. // 添加分集标题和梗概
  9678. $content .= "###第{$episode_number}集:{$title}\n\n";
  9679. $content .= "###故事梗概\n";
  9680. $content .= trim($intro) . "\n\n";
  9681. // 添加美术风格
  9682. $content .= "###美术风格\n";
  9683. $content .= trim($art_style) . "\n\n";
  9684. // 添加主体列表
  9685. $content .= "###主体列表\n";
  9686. $pangbai_voice_prompt = "";
  9687. foreach ($roles as $role) {
  9688. $name = getProp($role, 'role');
  9689. $description = getProp($role, 'description');
  9690. $pic_prompt = getProp($role, 'pic_prompt');
  9691. $voice_prompt = getProp($role, 'voice_prompt');
  9692. $voice_name = getProp($role, 'voice_name');
  9693. $content .= "{$name}: {$description}";
  9694. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9695. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9696. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9697. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9698. $content .= "\n";
  9699. }
  9700. $content .= "\n";
  9701. // 添加场景列表
  9702. $content .= "###场景列表\n";
  9703. foreach ($scenes as $scene) {
  9704. $name = getProp($scene, 'scene');
  9705. $description = getProp($scene, 'description');
  9706. $pic_prompt = getProp($scene, 'pic_prompt');
  9707. $content .= "{$name}: {$description}";
  9708. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9709. $content .= "\n";
  9710. }
  9711. $content .= "\n";
  9712. // 获取分镜信息
  9713. $segments = DB::table('mp_episode_segments')
  9714. ->where('anime_id', $animeId)
  9715. ->where('episode_id', $episode_id)
  9716. ->orderBy('segment_number')
  9717. ->get();
  9718. if ($segments && count($segments) > 0) {
  9719. if ((int)$ace_mode === 1) {
  9720. $content .= "###分段剧本\n";
  9721. // 获取片段数量
  9722. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9723. $content .= "片段数量:{$act_count}\n";
  9724. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9725. $content .= "\n";
  9726. }else {
  9727. $content .= "###分镜剧本\n";
  9728. }
  9729. // 按幕分组
  9730. $currentAct = null;
  9731. foreach ($segments as $segment) {
  9732. $act_number = getProp($segment, 'act_number');
  9733. $act_title = getProp($segment, 'act_title');
  9734. $act_duration = getProp($segment, 'act_duration');
  9735. $segment_number = getProp($segment, 'segment_number');
  9736. $segment_content = getProp($segment, 'segment_content');
  9737. $scene_description = getProp($segment, 'scene_description');
  9738. $scene_name = getProp($segment, 'scene_name');
  9739. $composition = getProp($segment, 'composition');
  9740. $camera_movement = getProp($segment, 'camera_movement');
  9741. $voice_type = getProp($segment, 'voice_type');
  9742. $characters = getProp($segment, 'characters');
  9743. $dialogue = getProp($segment, 'dialogue');
  9744. $frame_type = getProp($segment, 'frame_type');
  9745. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9746. // 判断是否是全能模式
  9747. if ((int)$ace_mode === 1) { // 全能模式
  9748. // 如果是新的分段,添加分段标题
  9749. if ($act_number !== $currentAct) {
  9750. $currentAct = $act_number;
  9751. $content .= "##{$act_title}\n";
  9752. $content .= "时长:{$act_duration}s\n";
  9753. }
  9754. }else {
  9755. // 如果是新的幕,添加幕标题
  9756. if ($act_number !== $currentAct) {
  9757. $currentAct = $act_number;
  9758. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9759. }
  9760. }
  9761. // 添加分镜信息
  9762. $content .= "分镜{$segment_number}\n";
  9763. $content .= "分镜内容:\n{$segment_content}\n";
  9764. // $content .= "画面描述:{$scene_description}\n";
  9765. // $content .= "场景:{$scene_name}\n";
  9766. // $content .= "构图设计:{$composition}\n";
  9767. // $content .= "运镜调度:{$camera_movement}\n";
  9768. // if (!empty($voice_type)) {
  9769. // $content .= "配音角色:{$voice_type}\n";
  9770. // }
  9771. // if (!empty($characters)) {
  9772. // $content .= "出镜角色:{$characters}\n";
  9773. // }
  9774. // if (!empty($dialogue)) {
  9775. // $content .= "台词内容:\"{$dialogue}\"\n";
  9776. // }
  9777. // $content .= "画面类型:{$frame_type}\n";
  9778. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9779. $content .= "\n";
  9780. }
  9781. }
  9782. $content = trim($content);
  9783. if($content) $content = "上集剧本内容:\n{$content}";
  9784. return [
  9785. [
  9786. 'role' => 'user',
  9787. 'content' => $origin_content
  9788. ],
  9789. [
  9790. 'role' => 'assistant',
  9791. 'content' => $content
  9792. ]
  9793. ];
  9794. }
  9795. private function getEpisodeChatMessages($animeId, $sequence): array
  9796. {
  9797. if ((int)$sequence <= 0) {
  9798. return [];
  9799. }
  9800. return DB::table('mp_anime_records')
  9801. ->where('anime_id', $animeId)
  9802. ->where('sequence', $sequence)
  9803. ->where('episode_id', '>', 0)
  9804. ->select('role', 'content')
  9805. ->orderBy('created_at')
  9806. ->orderBy('id')
  9807. ->get()
  9808. ->map(function ($value) {
  9809. return (array)$value;
  9810. })
  9811. ->toArray();
  9812. }
  9813. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9814. {
  9815. $existingMap = [];
  9816. foreach ($existingItems as $item) {
  9817. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9818. if ($itemKey === '') {
  9819. continue;
  9820. }
  9821. $existingMap[$itemKey] = $item;
  9822. }
  9823. if (!$generatedItems) {
  9824. return array_values($existingItems);
  9825. }
  9826. $merged = [];
  9827. foreach ($generatedItems as $item) {
  9828. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9829. if ($itemKey === '') {
  9830. continue;
  9831. }
  9832. if (isset($existingMap[$itemKey])) {
  9833. if (trim((string)getProp($item, 'description')) === '') {
  9834. $merged[] = $existingMap[$itemKey];
  9835. continue;
  9836. }
  9837. // 检查内容是否发生变化
  9838. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9839. if (!$isChanged) {
  9840. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9841. $mergedItem = [
  9842. $nameKey => trim((string)getProp($item, $nameKey)),
  9843. 'description' => trim((string)getProp($item, 'description')),
  9844. ];
  9845. // 如果有 pic_prompt,添加到合并项中
  9846. $picPrompt = getProp($item, 'pic_prompt');
  9847. if (!empty($picPrompt)) {
  9848. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9849. }
  9850. // 继承现有项的 URL
  9851. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9852. if (!empty($existingUrl)) {
  9853. $mergedItem['url'] = $existingUrl;
  9854. }
  9855. // 继承现有项的 task_id
  9856. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9857. if (!empty($existingTaskId)) {
  9858. $mergedItem['task_id'] = $existingTaskId;
  9859. }
  9860. // 继承现有项的 task_status
  9861. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9862. if (!empty($existingTaskStatus)) {
  9863. $mergedItem['task_status'] = $existingTaskStatus;
  9864. }
  9865. // 保留生成项的音色字段
  9866. $voiceName = getProp($item, 'voice_name');
  9867. if (!empty($voiceName)) {
  9868. $mergedItem['voice_name'] = $voiceName;
  9869. }
  9870. $voiceType = getProp($item, 'voice_type');
  9871. if (!empty($voiceType)) {
  9872. $mergedItem['voice_type'] = $voiceType;
  9873. }
  9874. $audioUrl = getProp($item, 'voice_audio_url');
  9875. if (!empty($audioUrl)) {
  9876. $mergedItem['voice_audio_url'] = $audioUrl;
  9877. }
  9878. $merged[] = $mergedItem;
  9879. } else {
  9880. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9881. $mergedItem = [
  9882. $nameKey => trim((string)getProp($item, $nameKey)),
  9883. 'description' => trim((string)getProp($item, 'description')),
  9884. ];
  9885. // 如果有 pic_prompt,添加到合并项中
  9886. $picPrompt = getProp($item, 'pic_prompt');
  9887. if (!empty($picPrompt)) {
  9888. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9889. }
  9890. // 保留生成项的音色字段
  9891. $voiceName = getProp($item, 'voice_name');
  9892. if (!empty($voiceName)) {
  9893. $mergedItem['voice_name'] = $voiceName;
  9894. }
  9895. $voiceType = getProp($item, 'voice_type');
  9896. if (!empty($voiceType)) {
  9897. $mergedItem['voice_type'] = $voiceType;
  9898. }
  9899. $audioUrl = getProp($item, 'voice_audio_url');
  9900. if (!empty($audioUrl)) {
  9901. $mergedItem['voice_audio_url'] = $audioUrl;
  9902. }
  9903. // 不继承 URL、task_id 和 task_status(重置状态)
  9904. $merged[] = $mergedItem;
  9905. }
  9906. } else {
  9907. // 新增项,保留生成项的所有字段
  9908. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9909. }
  9910. }
  9911. return $merged ?: array_values($existingItems);
  9912. }
  9913. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9914. {
  9915. $resetItem = [
  9916. $nameKey => trim((string)getProp($item, $nameKey)),
  9917. 'description' => trim((string)getProp($item, 'description')),
  9918. ];
  9919. // 保留指定的字段
  9920. foreach ($preserveFields as $field) {
  9921. $value = getProp($item, $field);
  9922. if (!empty($value)) {
  9923. $resetItem[$field] = $value;
  9924. }
  9925. }
  9926. return $resetItem;
  9927. }
  9928. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9929. {
  9930. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9931. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9932. if ($existingKey !== $generatedKey) {
  9933. return true;
  9934. }
  9935. // 比较 description 是否变化
  9936. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9937. return true;
  9938. }
  9939. // 比较 pic_prompt 是否变化
  9940. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9941. }
  9942. private function normalizeEpisodeResourceKey($value): string
  9943. {
  9944. $value = trim((string)$value);
  9945. if ($value === '') {
  9946. return '';
  9947. }
  9948. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9949. }
  9950. // 生成全局角色图片
  9951. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9952. $anime_id = getProp($data, 'anime_id');
  9953. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9954. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9955. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9956. $art_style = getProp($anime, 'art_style');
  9957. $update_flag = false;
  9958. foreach ($roles as &$role) {
  9959. $role_name = getProp($role, 'role');
  9960. if ($role_name == '旁白') continue;
  9961. // 优先使用 pic_prompt,如果没有则使用 description
  9962. $pic_prompt = getProp($role, 'pic_prompt');
  9963. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9964. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9965. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9966. // 参考图地址
  9967. $ref_img_url = getProp($role, 'url');
  9968. if (!$is_force && $ref_img_url) continue;
  9969. $update_flag = true;
  9970. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9971. try {
  9972. $params = [
  9973. 'prompt' => $description,
  9974. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9975. 'ref_img_urls' => []
  9976. ];
  9977. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9978. $task_id = $task->id;
  9979. if (!$task_id) {
  9980. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9981. }
  9982. $role['task_id'] = $task_id;
  9983. $role['task_status'] = 'processing';
  9984. } catch (\Exception $e) {
  9985. Utils::throwError("20003:" . $e->getMessage());
  9986. }
  9987. }
  9988. if (!$update_flag) return true;
  9989. // 保存角色信息
  9990. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9991. 'roles' => json_encode($roles, 256),
  9992. 'generate_status' => '执行中',
  9993. 'generate_at' => date('Y-m-d H:i:s'),
  9994. 'updated_at' => date('Y-m-d H:i:s')
  9995. ]);
  9996. if (!$boolen) {
  9997. Utils::throwError('20003:保存角色信息失败');
  9998. }
  9999. return $boolen;
  10000. }
  10001. // 生成全局场景图片
  10002. private function batchSetGlobalSceneImg($data, $is_force=false) {
  10003. $anime_id = getProp($data, 'anime_id');
  10004. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10005. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10006. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10007. $art_style = getProp($anime, 'art_style');
  10008. $update_flag = false;
  10009. foreach ($scenes as &$scene) {
  10010. $scene_name = getProp($scene, 'scene');
  10011. // 优先使用 pic_prompt,如果没有则使用 description
  10012. $pic_prompt = getProp($scene, 'pic_prompt');
  10013. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10014. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  10015. // 参考图地址
  10016. $ref_img_url = getProp($scene, 'url');
  10017. if (!$is_force && $ref_img_url) continue;
  10018. $update_flag = true;
  10019. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10020. try {
  10021. $params = [
  10022. 'prompt' => $description,
  10023. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  10024. 'ref_img_urls' => []
  10025. ];
  10026. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10027. $task_id = $task->id;
  10028. if (!$task_id) {
  10029. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  10030. }
  10031. $scene['task_id'] = $task_id;
  10032. $scene['task_status'] = 'processing';
  10033. } catch (\Exception $e) {
  10034. Utils::throwError("20003:" . $e->getMessage());
  10035. }
  10036. }
  10037. if (!$update_flag) return true;
  10038. // 保存角色信息
  10039. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10040. 'scenes' => json_encode($scenes, 256),
  10041. 'generate_status' => '执行中',
  10042. 'generate_at' => date('Y-m-d H:i:s'),
  10043. 'updated_at' => date('Y-m-d H:i:s')
  10044. ]);
  10045. if (!$boolen) {
  10046. Utils::throwError('20003:保存角色信息失败');
  10047. }
  10048. return $boolen;
  10049. }
  10050. // 生成分镜主体、场景和道具图片
  10051. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  10052. $character_prefix = '';
  10053. $scene_prefix = '';
  10054. $prop_prefix = '';
  10055. if ($art_style_type) {
  10056. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  10057. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  10058. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  10059. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  10060. }
  10061. $update_flag = false;
  10062. // 获取上一集的roles、scenes和props数据
  10063. $prev_roles = [];
  10064. $prev_scenes = [];
  10065. $prev_props = [];
  10066. if ($episode_number > 1) {
  10067. $prev_episode = DB::table('mp_anime_episodes')
  10068. ->where('anime_id', $anime_id)
  10069. ->where('episode_number', $episode_number - 1)
  10070. ->where('is_default', 1)
  10071. ->first();
  10072. if ($prev_episode) {
  10073. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  10074. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  10075. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  10076. dLog('deepseek')->info("获取上一集数据成功", [
  10077. 'anime_id' => $anime_id,
  10078. 'prev_episode_number' => $episode_number - 1,
  10079. 'prev_roles_count' => count($prev_roles),
  10080. 'prev_scenes_count' => count($prev_scenes),
  10081. 'prev_props_count' => count($prev_props)
  10082. ]);
  10083. }
  10084. }
  10085. // 处理角色图片生成
  10086. foreach ($roles as &$role) {
  10087. $role_name = getProp($role, 'role');
  10088. if ($role_name == '旁白') continue;
  10089. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  10090. if (isset($ref_products[$role_name])) {
  10091. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  10092. if ($role['url']) continue;
  10093. }
  10094. $role_description = getProp($role, 'description');
  10095. $role_pic_prompt = getProp($role, 'pic_prompt');
  10096. $role_url = getProp($role, 'url');
  10097. // 检查是否可以从上一集继承
  10098. $inherited = false;
  10099. if (!$is_force && !empty($prev_roles)) {
  10100. foreach ($prev_roles as $prev_role) {
  10101. $prev_role_name = getProp($prev_role, 'role');
  10102. $prev_description = getProp($prev_role, 'description');
  10103. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  10104. $prev_url = getProp($prev_role, 'url');
  10105. $prev_task_id = getProp($prev_role, 'task_id');
  10106. $prev_task_status = getProp($prev_role, 'task_status');
  10107. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  10108. if ($role_name == $prev_role_name
  10109. && $role_description == $prev_description
  10110. && $role_pic_prompt == $prev_pic_prompt
  10111. && !empty($prev_url)) {
  10112. $role['task_id'] = $prev_task_id;
  10113. $role['task_status'] = $prev_task_status;
  10114. $role['url'] = $prev_url;
  10115. $inherited = true;
  10116. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  10117. 'anime_id' => $anime_id,
  10118. 'episode_number' => $episode_number,
  10119. 'task_id' => $prev_task_id,
  10120. 'url' => $prev_url
  10121. ]);
  10122. break;
  10123. }
  10124. }
  10125. }
  10126. // 如果已继承或已有url,跳过生成
  10127. if ($inherited || (!$is_force && $role_url)) {
  10128. continue;
  10129. }
  10130. // 优先使用 pic_prompt,如果没有则使用 description
  10131. $pic_prompt = getProp($role, 'pic_prompt');
  10132. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10133. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10134. $update_flag = true;
  10135. // 调用AIImageGenerationService的生成图片任务接口
  10136. try {
  10137. $params = [
  10138. 'prompt' => $description,
  10139. 'ref_img_urls' => []
  10140. ];
  10141. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10142. $task_id = $task->id;
  10143. if (!$task_id) {
  10144. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10145. continue; // 不中断,继续处理其他角色
  10146. }
  10147. $role['task_id'] = $task_id;
  10148. $role['task_status'] = 'processing';
  10149. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10150. 'anime_id' => $anime_id,
  10151. 'episode_number' => $episode_number,
  10152. 'task_id' => $task_id
  10153. ]);
  10154. } catch (\Exception $e) {
  10155. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10156. // 不抛出异常,继续处理其他角色
  10157. }
  10158. }
  10159. // 处理场景图片生成
  10160. foreach ($scenes as &$scene) {
  10161. $scene_name = getProp($scene, 'scene');
  10162. $scene_description = getProp($scene, 'description');
  10163. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10164. $scene_url = getProp($scene, 'url');
  10165. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10166. if (isset($ref_products[$scene_name])) {
  10167. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10168. if ($scene['url']) continue;
  10169. }
  10170. // 检查是否可以从上一集继承
  10171. $inherited = false;
  10172. if (!$is_force && !empty($prev_scenes)) {
  10173. foreach ($prev_scenes as $prev_scene) {
  10174. $prev_scene_name = getProp($prev_scene, 'scene');
  10175. $prev_description = getProp($prev_scene, 'description');
  10176. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10177. $prev_url = getProp($prev_scene, 'url');
  10178. $prev_task_id = getProp($prev_scene, 'task_id');
  10179. $prev_task_status = getProp($prev_scene, 'task_status');
  10180. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10181. if ($scene_name == $prev_scene_name
  10182. && $scene_description == $prev_description
  10183. && $scene_pic_prompt == $prev_pic_prompt
  10184. && !empty($prev_url)) {
  10185. $scene['task_id'] = $prev_task_id;
  10186. $scene['task_status'] = $prev_task_status;
  10187. $scene['url'] = $prev_url;
  10188. $inherited = true;
  10189. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10190. 'anime_id' => $anime_id,
  10191. 'episode_number' => $episode_number,
  10192. 'task_id' => $prev_task_id,
  10193. 'url' => $prev_url
  10194. ]);
  10195. break;
  10196. }
  10197. }
  10198. }
  10199. // 如果已继承或已有url,跳过生成
  10200. if ($inherited || (!$is_force && $scene_url)) {
  10201. continue;
  10202. }
  10203. // 优先使用 pic_prompt,如果没有则使用 description
  10204. $pic_prompt = getProp($scene, 'pic_prompt');
  10205. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10206. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10207. $update_flag = true;
  10208. // 调用AIImageGenerationService的生成图片任务接口
  10209. try {
  10210. $params = [
  10211. 'prompt' => $description,
  10212. 'ref_img_urls' => []
  10213. ];
  10214. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10215. $task_id = $task->id;
  10216. if (!$task_id) {
  10217. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10218. continue; // 不中断,继续处理其他场景
  10219. }
  10220. $scene['task_id'] = $task_id;
  10221. $scene['task_status'] = 'processing';
  10222. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10223. 'anime_id' => $anime_id,
  10224. 'episode_number' => $episode_number,
  10225. 'task_id' => $task_id
  10226. ]);
  10227. } catch (\Exception $e) {
  10228. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10229. // 不抛出异常,继续处理其他场景
  10230. }
  10231. }
  10232. // 处理道具图片生成(逻辑与场景一致)
  10233. foreach ($props as &$prop) {
  10234. $prop_name = getProp($prop, 'prop');
  10235. $prop_description = getProp($prop, 'description');
  10236. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10237. $prop_url = getProp($prop, 'url');
  10238. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10239. if (isset($ref_products[$prop_name])) {
  10240. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10241. if ($prop['url']) continue;
  10242. }
  10243. // 检查是否可以从上一集继承
  10244. $inherited = false;
  10245. if (!$is_force && !empty($prev_props)) {
  10246. foreach ($prev_props as $prev_prop) {
  10247. $prev_prop_name = getProp($prev_prop, 'prop');
  10248. $prev_description = getProp($prev_prop, 'description');
  10249. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10250. $prev_url = getProp($prev_prop, 'url');
  10251. $prev_task_id = getProp($prev_prop, 'task_id');
  10252. $prev_task_status = getProp($prev_prop, 'task_status');
  10253. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10254. if ($prop_name == $prev_prop_name
  10255. && $prop_description == $prev_description
  10256. && $prop_pic_prompt == $prev_pic_prompt
  10257. && !empty($prev_url)) {
  10258. $prop['task_id'] = $prev_task_id;
  10259. $prop['task_status'] = $prev_task_status;
  10260. $prop['url'] = $prev_url;
  10261. $inherited = true;
  10262. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10263. 'anime_id' => $anime_id,
  10264. 'episode_number' => $episode_number,
  10265. 'task_id' => $prev_task_id,
  10266. 'url' => $prev_url
  10267. ]);
  10268. break;
  10269. }
  10270. }
  10271. }
  10272. // 如果已继承或已有url,跳过生成
  10273. if ($inherited || (!$is_force && $prop_url)) {
  10274. continue;
  10275. }
  10276. // 优先使用 pic_prompt,如果没有则使用 description
  10277. $pic_prompt = getProp($prop, 'pic_prompt');
  10278. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10279. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10280. $update_flag = true;
  10281. // 调用AIImageGenerationService的生成图片任务接口
  10282. try {
  10283. $params = [
  10284. 'prompt' => $description,
  10285. 'ref_img_urls' => []
  10286. ];
  10287. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10288. $task_id = $task->id;
  10289. if (!$task_id) {
  10290. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10291. continue; // 不中断,继续处理其他道具
  10292. }
  10293. $prop['task_id'] = $task_id;
  10294. $prop['task_status'] = 'processing';
  10295. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10296. 'anime_id' => $anime_id,
  10297. 'episode_number' => $episode_number,
  10298. 'task_id' => $task_id
  10299. ]);
  10300. } catch (\Exception $e) {
  10301. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10302. // 不抛出异常,继续处理其他道具
  10303. }
  10304. }
  10305. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10306. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10307. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10308. // // 保存剧集的角色和场景信息
  10309. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10310. // 'roles' => json_encode($roles, 256),
  10311. // 'scenes' => json_encode($scenes, 256),
  10312. // 'generate_status' => '执行中',
  10313. // 'generate_at' => date('Y-m-d H:i:s'),
  10314. // 'updated_at' => date('Y-m-d H:i:s')
  10315. // ]);
  10316. // if (!$boolen) {
  10317. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10318. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10319. // }
  10320. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10321. // 'episode_id' => $episode_id,
  10322. 'roles_count' => count($roles),
  10323. 'scenes_count' => count($scenes),
  10324. 'props_count' => count($props)
  10325. ]);
  10326. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10327. }
  10328. /**
  10329. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10330. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10331. *
  10332. * @param int $anime_id 动漫对话ID
  10333. * @param array $episode_roles 剧集角色数据
  10334. * @param array $episode_scenes 剧集场景数据
  10335. * @param array $episode_props 剧集道具数据
  10336. * @return bool
  10337. */
  10338. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10339. // 获取全局数据
  10340. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10341. if (!$anime) {
  10342. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10343. return false;
  10344. }
  10345. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10346. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10347. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10348. $roles_added = false;
  10349. $roles_updated = false;
  10350. $scenes_added = false;
  10351. $props_added = false;
  10352. // 处理角色同步
  10353. foreach ($episode_roles as $episode_role) {
  10354. $episode_role_name = getProp($episode_role, 'role');
  10355. $episode_description = getProp($episode_role, 'description');
  10356. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10357. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10358. // 跳过旁白
  10359. if ($episode_role_name == '旁白') {
  10360. continue;
  10361. }
  10362. // 检查全局中是否已存在相同的角色
  10363. $exists = false;
  10364. $global_role_index = -1;
  10365. foreach ($global_roles as $index => $global_role) {
  10366. $global_role_name = getProp($global_role, 'role');
  10367. $global_description = getProp($global_role, 'description');
  10368. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10369. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10370. if ($episode_role_name == $global_role_name
  10371. && $episode_description == $global_description
  10372. && $episode_pic_prompt == $global_pic_prompt) {
  10373. $exists = true;
  10374. $global_role_index = $index;
  10375. break;
  10376. }
  10377. }
  10378. // 如果不存在,则添加到全局
  10379. if (!$exists) {
  10380. $global_roles[] = $episode_role;
  10381. $roles_added = true;
  10382. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10383. 'anime_id' => $anime_id,
  10384. 'role' => $episode_role_name
  10385. ]);
  10386. } else {
  10387. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10388. if (!empty($episode_voice_prompt)) {
  10389. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10390. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10391. if ($global_voice_prompt !== $episode_voice_prompt) {
  10392. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10393. $roles_updated = true;
  10394. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10395. 'anime_id' => $anime_id,
  10396. 'role' => $episode_role_name,
  10397. 'voice_prompt' => $episode_voice_prompt
  10398. ]);
  10399. }
  10400. }
  10401. }
  10402. }
  10403. // 处理场景同步
  10404. foreach ($episode_scenes as $episode_scene) {
  10405. $episode_scene_name = getProp($episode_scene, 'scene');
  10406. $episode_description = getProp($episode_scene, 'description');
  10407. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10408. // 检查全局中是否已存在相同的场景
  10409. $exists = false;
  10410. foreach ($global_scenes as $global_scene) {
  10411. $global_scene_name = getProp($global_scene, 'scene');
  10412. $global_description = getProp($global_scene, 'description');
  10413. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10414. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10415. if ($episode_scene_name == $global_scene_name
  10416. && $episode_description == $global_description
  10417. && $episode_pic_prompt == $global_pic_prompt) {
  10418. $exists = true;
  10419. break;
  10420. }
  10421. }
  10422. // 如果不存在,则添加到全局
  10423. if (!$exists) {
  10424. $global_scenes[] = $episode_scene;
  10425. $scenes_added = true;
  10426. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10427. 'anime_id' => $anime_id,
  10428. 'scene' => $episode_scene_name
  10429. ]);
  10430. }
  10431. }
  10432. // 处理道具同步(逻辑与场景一致)
  10433. foreach ($episode_props as $episode_prop) {
  10434. $episode_prop_name = getProp($episode_prop, 'prop');
  10435. $episode_description = getProp($episode_prop, 'description');
  10436. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10437. // 检查全局中是否已存在相同的道具
  10438. $exists = false;
  10439. foreach ($global_props as $global_prop) {
  10440. $global_prop_name = getProp($global_prop, 'prop');
  10441. $global_description = getProp($global_prop, 'description');
  10442. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10443. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10444. if ($episode_prop_name == $global_prop_name
  10445. && $episode_description == $global_description
  10446. && $episode_pic_prompt == $global_pic_prompt) {
  10447. $exists = true;
  10448. break;
  10449. }
  10450. }
  10451. // 如果不存在,则添加到全局
  10452. if (!$exists) {
  10453. $global_props[] = $episode_prop;
  10454. $props_added = true;
  10455. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10456. 'anime_id' => $anime_id,
  10457. 'prop' => $episode_prop_name
  10458. ]);
  10459. }
  10460. }
  10461. // 如果有新增或更新,则更新全局数据
  10462. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10463. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10464. if ($roles_added || $roles_updated) {
  10465. $update_data['roles'] = json_encode($global_roles, 256);
  10466. }
  10467. if ($scenes_added) {
  10468. $update_data['scenes'] = json_encode($global_scenes, 256);
  10469. }
  10470. if ($props_added) {
  10471. $update_data['props'] = json_encode($global_props, 256);
  10472. }
  10473. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10474. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10475. 'anime_id' => $anime_id,
  10476. 'roles_added' => $roles_added,
  10477. 'roles_updated' => $roles_updated,
  10478. 'scenes_added' => $scenes_added,
  10479. 'props_added' => $props_added,
  10480. 'global_roles_count' => count($global_roles),
  10481. 'global_scenes_count' => count($global_scenes),
  10482. 'global_props_count' => count($global_props)
  10483. ]);
  10484. }
  10485. return true;
  10486. }
  10487. /**
  10488. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10489. *
  10490. * @param int $anime_id 动漫对话ID
  10491. * @param int $episode_id 分集ID
  10492. * @return bool
  10493. */
  10494. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10495. // 获取全局角色和场景数据
  10496. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10497. if (!$anime) {
  10498. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10499. return false;
  10500. }
  10501. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10502. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10503. // 获取指定的分集
  10504. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10505. if (!$episode) {
  10506. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10507. return false;
  10508. }
  10509. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10510. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10511. $roles_updated = false;
  10512. $scenes_updated = false;
  10513. // 继承角色的task_id、task_status和url
  10514. foreach ($episode_roles as &$episode_role) {
  10515. $episode_role_name = getProp($episode_role, 'role');
  10516. $episode_description = getProp($episode_role, 'description');
  10517. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10518. $episode_url = getProp($episode_role, 'url');
  10519. // 跳过旁白角色
  10520. if ($episode_role_name == '旁白') {
  10521. continue;
  10522. }
  10523. // 如果剧集中已有URL,跳过
  10524. if (!empty($episode_url)) {
  10525. continue;
  10526. }
  10527. // 遍历全局角色数据,查找匹配的角色
  10528. foreach ($global_roles as $global_role) {
  10529. $global_role_name = getProp($global_role, 'role');
  10530. $global_description = getProp($global_role, 'description');
  10531. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10532. $global_url = getProp($global_role, 'url');
  10533. $global_task_id = getProp($global_role, 'task_id');
  10534. $global_task_status = getProp($global_role, 'task_status');
  10535. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10536. if ($episode_role_name == $global_role_name
  10537. && $episode_description == $global_description
  10538. && $episode_pic_prompt == $global_pic_prompt) {
  10539. // 继承 task_id、task_status 和 url
  10540. if (!empty($global_task_id)) {
  10541. $episode_role['task_id'] = $global_task_id;
  10542. $episode_role['task_status'] = $global_task_status;
  10543. $roles_updated = true;
  10544. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10545. 'episode_id' => $episode_id,
  10546. 'role' => $episode_role_name,
  10547. 'task_id' => $global_task_id,
  10548. 'task_status' => $global_task_status
  10549. ]);
  10550. }
  10551. if (!empty($global_url)) {
  10552. $episode_role['url'] = $global_url;
  10553. $roles_updated = true;
  10554. dLog('deepseek')->info('剧集角色继承全局url', [
  10555. 'episode_id' => $episode_id,
  10556. 'role' => $episode_role_name,
  10557. 'url' => $global_url
  10558. ]);
  10559. }
  10560. break;
  10561. }
  10562. }
  10563. }
  10564. // 继承场景的task_id、task_status和url
  10565. foreach ($episode_scenes as &$episode_scene) {
  10566. $episode_scene_name = getProp($episode_scene, 'scene');
  10567. $episode_description = getProp($episode_scene, 'description');
  10568. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10569. $episode_url = getProp($episode_scene, 'url');
  10570. // 如果剧集中已有URL,跳过
  10571. if (!empty($episode_url)) {
  10572. continue;
  10573. }
  10574. // 遍历全局场景数据,查找匹配的场景
  10575. foreach ($global_scenes as $global_scene) {
  10576. $global_scene_name = getProp($global_scene, 'scene');
  10577. $global_description = getProp($global_scene, 'description');
  10578. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10579. $global_url = getProp($global_scene, 'url');
  10580. $global_task_id = getProp($global_scene, 'task_id');
  10581. $global_task_status = getProp($global_scene, 'task_status');
  10582. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10583. if ($episode_scene_name == $global_scene_name
  10584. && $episode_description == $global_description
  10585. && $episode_pic_prompt == $global_pic_prompt) {
  10586. // 继承 task_id、task_status 和 url
  10587. if (!empty($global_task_id)) {
  10588. $episode_scene['task_id'] = $global_task_id;
  10589. $episode_scene['task_status'] = $global_task_status;
  10590. $scenes_updated = true;
  10591. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10592. 'episode_id' => $episode_id,
  10593. 'scene' => $episode_scene_name,
  10594. 'task_id' => $global_task_id,
  10595. 'task_status' => $global_task_status
  10596. ]);
  10597. }
  10598. if (!empty($global_url)) {
  10599. $episode_scene['url'] = $global_url;
  10600. $scenes_updated = true;
  10601. dLog('deepseek')->info('剧集场景继承全局url', [
  10602. 'episode_id' => $episode_id,
  10603. 'scene' => $episode_scene_name,
  10604. 'url' => $global_url
  10605. ]);
  10606. }
  10607. break;
  10608. }
  10609. }
  10610. }
  10611. // 如果有更新,则保存到数据库
  10612. if ($roles_updated || $scenes_updated) {
  10613. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10614. if ($roles_updated) {
  10615. $update_data['roles'] = json_encode($episode_roles, 256);
  10616. }
  10617. if ($scenes_updated) {
  10618. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10619. }
  10620. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10621. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10622. 'episode_id' => $episode_id,
  10623. 'roles_updated' => $roles_updated,
  10624. 'scenes_updated' => $scenes_updated
  10625. ]);
  10626. }
  10627. return true;
  10628. }
  10629. public function chatChangeImg($data) {
  10630. $segment = getProp($data, 'segment');
  10631. $segment_content = getProp($segment, 'segment_content');
  10632. $prompt = getProp($data, 'prompt');
  10633. $ref_img = getProp($data, 'ref_img');
  10634. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10635. // 处理文本模型
  10636. $model = getProp($data, 'model');
  10637. if (!$model) {
  10638. // 用户没有输入,从anime表获取
  10639. $segment_id = getProp($segment, 'segment_id');
  10640. if ($segment_id) {
  10641. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10642. if ($episode_id) {
  10643. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10644. if ($anime_id) {
  10645. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10646. }
  10647. }
  10648. }
  10649. if (!$model) {
  10650. // anime表也没有,使用默认值
  10651. $model = 'doubao-seed-2-0-mini-260215';
  10652. }
  10653. }
  10654. // 验证模型是否在可用模型表中
  10655. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10656. $model = 'doubao-seed-2-0-mini-260215';
  10657. }
  10658. $messages[] =
  10659. [
  10660. 'role' => 'user',
  10661. 'content' => $question
  10662. ];
  10663. $post_data = [
  10664. 'model' => $model,
  10665. 'messages' => $messages,
  10666. // 'max_tokens' => 8192,
  10667. 'temperature' => 0.7,
  10668. 'frequency_penalty' => 0,
  10669. 'presence_penalty' => 0,
  10670. 'response_format' => ['type' => 'text'],
  10671. 'stream' => false // 是否启用流式输出
  10672. ];
  10673. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10674. // DeepSeek 官方模型使用 DeepSeek API
  10675. $chatResult = $this->chatOnly($post_data);
  10676. } else if (in_array($model, $this->gpt_text_models)) {
  10677. // GPT-5.4 模型使用 TokenRouter API
  10678. $chatResult = $this->gpt54ChatOnly($post_data);
  10679. } else {
  10680. // 其他模型使用火山引擎API
  10681. $chatResult = $this->volcEngineChatCompletion($post_data);
  10682. }
  10683. if (is_array($chatResult)) {
  10684. extract($chatResult);
  10685. }else {
  10686. Utils::throwError('20003: 接口调用失败!');
  10687. }
  10688. return [
  10689. 'type' => 'done',
  10690. // 'episode' => $episode,
  10691. 'answer' => $fullContent,
  10692. 'reasoning' => $fullReasoningContent,
  10693. 'usage' => $usage
  10694. ];
  10695. }
  10696. // 仅调用deepseek对话接口
  10697. private function chatOnly($post_data) {
  10698. $post_data['max_tokens'] = 300000;
  10699. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10700. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10701. $response = $result->getBody()->getContents();
  10702. $response_arr = json_decode($response, true);
  10703. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10704. $fullContent = '';
  10705. $fullReasoningContent = [];
  10706. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10707. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10708. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10709. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10710. }
  10711. return [
  10712. 'fullContent' => $fullContent,
  10713. 'fullReasoningContent' => $fullReasoningContent,
  10714. 'usage' => $usage
  10715. ];
  10716. }
  10717. // 仅调用 GPT-5.4 对话接口(非流式)
  10718. private function gpt54ChatOnly($post_data) {
  10719. $apiKey = env('GPT_54_API_KEY');
  10720. if (empty($apiKey)) {
  10721. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10722. }
  10723. // 先探活,服务不可用时自动重试
  10724. $this->ensureGptServiceAvailable();
  10725. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10726. $headers = [
  10727. 'Authorization' => 'Bearer ' . $apiKey,
  10728. 'Content-Type' => 'application/json'
  10729. ];
  10730. // 移除 thinking 参数,GPT-5.4 不支持
  10731. if (isset($post_data['thinking'])) {
  10732. unset($post_data['thinking']);
  10733. }
  10734. if (isset($post_data['reasoning_effort'])) {
  10735. unset($post_data['reasoning_effort']);
  10736. }
  10737. $post_data['max_completion_tokens'] = 100000;
  10738. // 确保 stream 为 false
  10739. $post_data['stream'] = false;
  10740. $maxRetries = $this->gptRetryTimes();
  10741. $interval = $this->gptRetryInterval();
  10742. $attempt = 0;
  10743. while (true) {
  10744. try {
  10745. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10746. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10747. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10748. 'json' => $post_data,
  10749. 'headers' => $headers
  10750. ]);
  10751. $response = $result->getBody()->getContents();
  10752. $response_arr = json_decode($response, true);
  10753. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10754. $fullContent = '';
  10755. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10756. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10757. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10758. }
  10759. return [
  10760. 'fullContent' => $fullContent,
  10761. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10762. 'usage' => $usage
  10763. ];
  10764. } catch (\Exception $e) {
  10765. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  10766. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  10767. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  10768. throw $e;
  10769. }
  10770. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  10771. 'retry' => $attempt + 1,
  10772. 'max_retries' => $maxRetries,
  10773. 'error' => $e->getMessage()
  10774. ]);
  10775. sleep($interval);
  10776. $attempt++;
  10777. }
  10778. }
  10779. }
  10780. private function splitContent($content) {
  10781. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10782. $chapters = [];
  10783. // 匹配章节标题格式:
  10784. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10785. // 2. 格式支持:
  10786. // - **第一集**
  10787. // - 第一集:
  10788. // - ###第1章 重生
  10789. // - ##第2章 相救
  10790. // - 第三章 共处一室
  10791. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10792. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10793. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10794. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10795. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10796. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10797. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10798. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10799. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10800. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10801. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10802. // 用正则找出所有章节标题的位置
  10803. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10804. $titleCount = count($matches[0]);
  10805. for ($i = 0; $i < $titleCount; $i++) {
  10806. // 获取当前章节标题
  10807. $titleLine = trim($matches[0][$i][0]);
  10808. // 去除标题开头的特殊符号
  10809. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10810. // 去除标题结尾的冒号和特殊符号
  10811. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10812. $cleanTitle = trim($cleanTitle);
  10813. // 获取当前标题的结束位置
  10814. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10815. // 获取下一个章节标题的开始位置(如果存在)
  10816. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10817. // 提取章节内容(从标题结束到下一个标题开始)
  10818. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10819. // 清理内容:去除前后空白和分隔线
  10820. $chapterContent = trim($chapterContent);
  10821. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10822. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10823. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10824. $chapters[] = [
  10825. 'title' => $cleanTitle,
  10826. 'content' => $chapterContent
  10827. ];
  10828. }
  10829. }
  10830. } else {
  10831. // 如果没有匹配到章节,返回整个内容
  10832. $chapters[] = [
  10833. 'title' => '',
  10834. 'content' => $content
  10835. ];
  10836. }
  10837. return $chapters;
  10838. }
  10839. public function getContentByBid($bid) {
  10840. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10841. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10842. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10843. $content = '';
  10844. foreach ($chapters as $chapter) {
  10845. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10846. }
  10847. return $content;
  10848. }
  10849. public function getContentByScriptId($script_id) {
  10850. $content = '';
  10851. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10852. if ($contents) {
  10853. $content = implode(PHP_EOL, $contents);
  10854. }else {
  10855. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10856. }
  10857. return $content;
  10858. }
  10859. /**
  10860. * 根据文件类型提取文本内容
  10861. *
  10862. * @param mixed $file 文件对象或文件路径
  10863. * @return string
  10864. */
  10865. public function extractFileContent($file) {
  10866. // 获取文件路径和扩展名
  10867. if (is_string($file)) {
  10868. $filePath = $file;
  10869. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10870. } else {
  10871. // Laravel UploadedFile 对象
  10872. $filePath = $file->getRealPath();
  10873. $extension = strtolower($file->getClientOriginalExtension());
  10874. }
  10875. $content = '';
  10876. switch ($extension) {
  10877. case 'txt':
  10878. $content = $this->extractTxtContent($filePath);
  10879. break;
  10880. case 'pdf':
  10881. $content = $this->extractPdfContent($filePath);
  10882. break;
  10883. case 'doc':
  10884. case 'docx':
  10885. $content = $this->extractWordContent($filePath);
  10886. break;
  10887. // case 'jpg':
  10888. // case 'jpeg':
  10889. // case 'png':
  10890. // case 'gif':
  10891. // case 'bmp':
  10892. // case 'webp':
  10893. // $content = $this->extractImageContent($filePath);
  10894. // break;
  10895. default:
  10896. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10897. }
  10898. return $content;
  10899. }
  10900. /**
  10901. * 提取 TXT 文件内容
  10902. */
  10903. private function extractTxtContent($filePath) {
  10904. if (!file_exists($filePath)) {
  10905. Utils::throwError('20003:文件不存在');
  10906. }
  10907. $content = file_get_contents($filePath);
  10908. // 尝试检测并转换编码
  10909. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10910. if ($encoding && $encoding !== 'UTF-8') {
  10911. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10912. }
  10913. return trim($content);
  10914. }
  10915. /**
  10916. * 提取 PDF 文件内容
  10917. */
  10918. private function extractPdfContent($filePath) {
  10919. if (!file_exists($filePath)) {
  10920. Utils::throwError('20003:文件不存在');
  10921. }
  10922. try {
  10923. $parser = new PdfParser();
  10924. $pdf = $parser->parseFile($filePath);
  10925. $content = $pdf->getText();
  10926. return trim($content);
  10927. } catch (\Exception $e) {
  10928. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10929. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10930. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10931. }
  10932. }
  10933. /**
  10934. * 提取 Word 文件内容(支持 doc 和 docx)
  10935. */
  10936. private function extractWordContent($filePath) {
  10937. if (!file_exists($filePath)) {
  10938. Utils::throwError('20003:文件不存在');
  10939. }
  10940. try {
  10941. $phpWord = WordIOFactory::load($filePath);
  10942. $content = '';
  10943. foreach ($phpWord->getSections() as $section) {
  10944. foreach ($section->getElements() as $element) {
  10945. $content .= $this->extractWordElementText($element);
  10946. }
  10947. }
  10948. return trim($content);
  10949. } catch (\Exception $e) {
  10950. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10951. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10952. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10953. }
  10954. }
  10955. /**
  10956. * 递归提取 Word 元素中的文本
  10957. */
  10958. private function extractWordElementText($element) {
  10959. $text = '';
  10960. if (method_exists($element, 'getText')) {
  10961. $text .= $element->getText() . "\n";
  10962. } elseif (method_exists($element, 'getElements')) {
  10963. foreach ($element->getElements() as $childElement) {
  10964. $text .= $this->extractWordElementText($childElement);
  10965. }
  10966. }
  10967. return $text;
  10968. }
  10969. /**
  10970. * 提取图片内容(使用火山引擎 OCR)
  10971. */
  10972. private function extractImageContent($filePath) {
  10973. if (!file_exists($filePath)) {
  10974. Utils::throwError('20003:文件不存在');
  10975. }
  10976. try {
  10977. // 读取图片并转换为 base64
  10978. $imageData = file_get_contents($filePath);
  10979. $base64Image = base64_encode($imageData);
  10980. // 调用火山引擎 OCR 服务
  10981. $content = $this->callVolcEngineOCR($base64Image);
  10982. return trim($content);
  10983. } catch (\Exception $e) {
  10984. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10985. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10986. Utils::throwError('20003:图片识别失败');
  10987. }
  10988. }
  10989. /**
  10990. * 调用火山引擎 OCR 服务识别图片文字
  10991. *
  10992. * @param string $base64Image base64 编码的图片数据
  10993. * @return string 识别的文字内容
  10994. */
  10995. private function callVolcEngineOCR($base64Image) {
  10996. $method = 'POST';
  10997. $service = 'cv';
  10998. $host = 'visual.volcengineapi.com';
  10999. $region = env('VOLC_REGION', 'cn-north-1');
  11000. $access_key = env('VOLC_AK');
  11001. $secret_key = env('VOLC_SK');
  11002. $action = 'OCRNormal';
  11003. $version = '2020-08-26';
  11004. if (!$access_key || !$secret_key) {
  11005. Utils::throwError('20003:请配置火山引擎 AK/SK');
  11006. }
  11007. // 请求体
  11008. $body = json_encode([
  11009. 'image_base64' => $base64Image
  11010. ]);
  11011. // 生成签名
  11012. $headers = $this->getVolcEngineSignHeaders(
  11013. $method, $service, $host, $region,
  11014. "Action={$action}&Version={$version}",
  11015. $access_key, $secret_key, $body
  11016. );
  11017. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11018. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  11019. 'headers' => $headers,
  11020. 'body' => $body
  11021. ]);
  11022. $response_arr = json_decode($response->getBody()->getContents(), true);
  11023. // 提取识别的文字
  11024. $textLines = [];
  11025. if (isset($response_arr['data']['line_texts'])) {
  11026. $textLines = $response_arr['data']['line_texts'];
  11027. } elseif (isset($response_arr['data']['ocr_infos'])) {
  11028. foreach ($response_arr['data']['ocr_infos'] as $info) {
  11029. if (isset($info['text'])) {
  11030. $textLines[] = $info['text'];
  11031. }
  11032. }
  11033. }
  11034. if (empty($textLines)) {
  11035. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  11036. return '';
  11037. }
  11038. return implode("\n", $textLines);
  11039. }
  11040. /**
  11041. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  11042. */
  11043. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  11044. $contentType = 'application/json';
  11045. $accept = 'application/json';
  11046. // 获取当前UTC时间
  11047. $t = new DateTime('now', new DateTimeZone('UTC'));
  11048. $xDate = $t->format('Ymd\THis\Z');
  11049. $dateStamp = $t->format('Ymd');
  11050. // 计算 body 的 sha256 哈希
  11051. $payloadHash = hash('sha256', $body);
  11052. // 1. 拼接规范请求串
  11053. $canonicalUri = '/';
  11054. $canonicalQueryString = $queryString;
  11055. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  11056. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  11057. $canonicalRequest = implode("\n", [
  11058. $method,
  11059. $canonicalUri,
  11060. $canonicalQueryString,
  11061. $canonicalHeaders,
  11062. $signedHeaders,
  11063. $payloadHash
  11064. ]);
  11065. // 2. 拼接待签名字符串
  11066. $algorithm = 'HMAC-SHA256';
  11067. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  11068. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  11069. $stringToSign = implode("\n", [
  11070. $algorithm,
  11071. $xDate,
  11072. $credentialScope,
  11073. $hashedCanonicalRequest
  11074. ]);
  11075. // 3. 计算签名
  11076. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  11077. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  11078. // 4. 添加签名到请求头
  11079. $authorizationHeader = sprintf(
  11080. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  11081. $algorithm,
  11082. $access_key,
  11083. $credentialScope,
  11084. $signedHeaders,
  11085. $signature
  11086. );
  11087. return [
  11088. 'Accept' => $accept,
  11089. 'Content-Type' => $contentType,
  11090. 'Host' => $host,
  11091. 'X-Date' => $xDate,
  11092. 'X-Content-Sha256'=> $payloadHash,
  11093. 'Authorization' => $authorizationHeader
  11094. ];
  11095. }
  11096. public function generateScriptWords($cid, $model = 'r1') {
  11097. ini_set('max_execution_time', 0);
  11098. if (!$cid) Utils::throwError('20003: 请选择章节!');
  11099. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  11100. // 模型兼容性处理和思考模式设置
  11101. $thinkingMode = 'disabled';
  11102. $reasoningEffort = 'high';
  11103. if ($model == 'r1') {
  11104. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  11105. $thinkingMode = 'enabled';
  11106. } else {
  11107. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  11108. $thinkingMode = 'disabled';
  11109. }
  11110. $messages = [
  11111. [
  11112. 'role' => 'system',
  11113. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  11114. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  11115. 2.非对话部分请全部用旁白角色代替
  11116. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  11117. ],
  11118. [
  11119. 'role' => 'user',
  11120. 'content' => $content
  11121. ]
  11122. ];
  11123. $post_data = [
  11124. 'model' => $model,
  11125. 'messages' => $messages,
  11126. // 'max_tokens' => 8192,
  11127. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11128. 'frequency_penalty' => 0,
  11129. 'presence_penalty' => 0,
  11130. 'thinking' => ['type' => $thinkingMode],
  11131. 'response_format' => [
  11132. 'type' => 'text'
  11133. ],
  11134. 'stream' => false
  11135. ];
  11136. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11137. // 根据模型类型选择调用方法
  11138. $fullContent = '';
  11139. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11140. // DeepSeek 官方模型使用 DeepSeek API
  11141. $chatResult = $this->chatOnly($post_data);
  11142. } else if (in_array($model, $this->gpt_text_models)) {
  11143. // GPT-5.4 模型使用 TokenRouter API
  11144. $chatResult = $this->gpt54ChatOnly($post_data);
  11145. } else {
  11146. // 其他模型使用火山引擎API
  11147. $chatResult = $this->volcEngineChatCompletion($post_data);
  11148. }
  11149. if (is_array($chatResult)) {
  11150. $fullContent = $chatResult['fullContent'];
  11151. }
  11152. return $fullContent;
  11153. }
  11154. /**
  11155. * 智能化解析集数信息
  11156. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11157. *
  11158. * @param string $prompt 用户输入的提示词
  11159. * @return int|null 解析出的集数,如果没有找到则返回null
  11160. */
  11161. private function extractEpisodeNumber($prompt)
  11162. {
  11163. if (empty($prompt)) {
  11164. return null;
  11165. }
  11166. // 定义各种可能的表达模式
  11167. $patterns = [
  11168. // 基本模式:改成N集、调整成N集、修改成N集
  11169. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11170. // 扩展模式:分成N集、拆分成N集、分割成N集
  11171. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11172. // 数量模式:N集、共N集、总共N集
  11173. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11174. // 制作模式:制作N集、生成N集、创建N集
  11175. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11176. // 计划模式:计划N集、预计N集、打算N集
  11177. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11178. // 需要模式:需要N集、要N集
  11179. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11180. // 中文数字模式:改成三集、调整成五集等
  11181. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11182. // 英文数字模式
  11183. '/(?: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',
  11184. ];
  11185. // 中文数字转阿拉伯数字的映射
  11186. $chineseNumbers = [
  11187. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11188. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11189. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11190. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11191. ];
  11192. // 逐个尝试匹配模式
  11193. foreach ($patterns as $pattern) {
  11194. if (preg_match($pattern, $prompt, $matches)) {
  11195. $number = trim($matches[1]);
  11196. // 如果是中文数字,转换为阿拉伯数字
  11197. if (isset($chineseNumbers[$number])) {
  11198. return $chineseNumbers[$number];
  11199. }
  11200. // 如果是阿拉伯数字,直接返回
  11201. if (is_numeric($number)) {
  11202. $episodeNum = intval($number);
  11203. // 合理性检查:集数应该在1-100之间
  11204. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11205. return $episodeNum;
  11206. }
  11207. }
  11208. }
  11209. }
  11210. return null;
  11211. }
  11212. /**
  11213. * 调用火山引擎对话(Chat) API
  11214. *
  11215. * @param array $params 包含以下参数:
  11216. * - model: 模型ID(必填)
  11217. * - messages: 消息列表(必填)
  11218. * - stream: 是否流式输出(可选,默认false)
  11219. * - max_tokens: 最大输出token数(可选)
  11220. * - temperature: 采样温度(可选,默认1)
  11221. * - top_p: 核采样概率(可选,默认0.7)
  11222. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11223. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11224. * - stop: 停止词(可选)
  11225. * - tools: 工具列表(可选)
  11226. * @return array|Generator 非流式返回数组,流式返回生成器
  11227. */
  11228. public function volcEngineChatCompletion(array $params)
  11229. {
  11230. $apiKey = env('VOLC_AI_API_KEY');
  11231. if (empty($apiKey)) {
  11232. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11233. }
  11234. // 构建请求参数
  11235. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11236. $requestData = [
  11237. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11238. 'messages' => $params['messages'] ?? [],
  11239. ];
  11240. if (!in_array($originalModel, $this->valid_text_models)) {
  11241. Utils::throwError('20003:该模型不支持!');
  11242. }
  11243. // 添加可选参数
  11244. if (isset($params['stream'])) {
  11245. $requestData['stream'] = $params['stream'];
  11246. }
  11247. if (isset($params['stream_options'])) {
  11248. $requestData['stream_options'] = $params['stream_options'];
  11249. }
  11250. if (isset($params['max_tokens'])) {
  11251. $requestData['max_tokens'] = $params['max_tokens'];
  11252. }else if (isset($params['max_completion_tokens'])) {
  11253. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11254. }else {
  11255. $requestData['max_completion_tokens'] = 100000;
  11256. }
  11257. if (isset($params['temperature'])) {
  11258. $requestData['temperature'] = $params['temperature'];
  11259. }
  11260. if (isset($params['top_p'])) {
  11261. $requestData['top_p'] = $params['top_p'];
  11262. }
  11263. if (isset($params['frequency_penalty'])) {
  11264. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11265. }
  11266. if (isset($params['presence_penalty'])) {
  11267. $requestData['presence_penalty'] = $params['presence_penalty'];
  11268. }
  11269. if (isset($params['stop'])) {
  11270. $requestData['stop'] = $params['stop'];
  11271. }
  11272. if (isset($params['tools'])) {
  11273. $requestData['tools'] = $params['tools'];
  11274. }
  11275. if (isset($params['tool_choice'])) {
  11276. $requestData['tool_choice'] = $params['tool_choice'];
  11277. }
  11278. if (isset($params['response_format'])) {
  11279. $requestData['response_format'] = $params['response_format'];
  11280. }
  11281. if (isset($params['thinking'])) {
  11282. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11283. if (is_array($params['thinking'])) {
  11284. $requestData['thinking'] = $params['thinking'];
  11285. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11286. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11287. }
  11288. } else {
  11289. $requestData['thinking'] = ['type' => $params['thinking']];
  11290. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11291. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11292. }
  11293. }
  11294. } else {
  11295. $requestData['thinking'] = ['type' => 'disabled'];
  11296. }
  11297. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11298. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11299. try {
  11300. // 判断是否为流式输出
  11301. $isStream = isset($params['stream']) && $params['stream'] === true;
  11302. if ($isStream) {
  11303. // 流式输出
  11304. // 流式请求默认声明返回 usage(未显式传参时)
  11305. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  11306. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11307. } else {
  11308. // 非流式输出
  11309. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11310. 'headers' => [
  11311. 'Authorization' => 'Bearer ' . $apiKey,
  11312. 'Content-Type' => 'application/json',
  11313. ],
  11314. 'json' => $requestData
  11315. ]);
  11316. $responseData = json_decode($response->getBody(), true);
  11317. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11318. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11319. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11320. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11321. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11322. }
  11323. return [
  11324. 'fullContent' => $fullContent,
  11325. 'fullReasoningContent' => $fullReasoningContent,
  11326. 'usage' => $usage
  11327. ];
  11328. }
  11329. } catch (\Exception $e) {
  11330. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11331. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11332. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11333. }
  11334. }
  11335. /**
  11336. * 火山引擎对话API流式输出
  11337. *
  11338. * @param Client $client HTTP客户端
  11339. * @param string $apiKey API密钥
  11340. * @param array $requestData 请求数据
  11341. * @return Generator
  11342. */
  11343. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11344. {
  11345. try {
  11346. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11347. 'headers' => [
  11348. 'Authorization' => 'Bearer ' . $apiKey,
  11349. 'Content-Type' => 'application/json',
  11350. ],
  11351. 'json' => $requestData,
  11352. 'stream' => true
  11353. ]);
  11354. $body = $response->getBody();
  11355. $buffer = '';
  11356. $fullContent = '';
  11357. $fullReasoningContent = '';
  11358. $usage = [];
  11359. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11360. // 逐行读取流式响应
  11361. while (!$body->eof()) {
  11362. $chunk = $body->read(1024);
  11363. $buffer .= $chunk;
  11364. // 按行分割
  11365. $lines = explode("\n", $buffer);
  11366. $buffer = array_pop($lines);
  11367. foreach ($lines as $line) {
  11368. $line = trim($line);
  11369. if (empty($line)) {
  11370. continue;
  11371. }
  11372. // 检查是否是SSE数据行
  11373. if (strpos($line, 'data: ') !== 0) {
  11374. continue;
  11375. }
  11376. $data = substr($line, 6);
  11377. if ($data === '[DONE]') {
  11378. dLog('deepseek')->info('收到结束标记');
  11379. break 2;
  11380. }
  11381. try {
  11382. $json = json_decode($data, true);
  11383. if (json_last_error() !== JSON_ERROR_NONE) {
  11384. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11385. continue;
  11386. }
  11387. if (isset($json['choices'][0]['delta'])) {
  11388. $delta = $json['choices'][0]['delta'];
  11389. // 处理思维链内容
  11390. if (isset($delta['reasoning_content'])) {
  11391. $fullReasoningContent .= $delta['reasoning_content'];
  11392. yield [
  11393. 'type' => 'reasoning',
  11394. 'content' => $delta['reasoning_content'],
  11395. 'full_reasoning' => $fullReasoningContent
  11396. ];
  11397. }
  11398. // 处理回答内容
  11399. if (isset($delta['content'])) {
  11400. $fullContent .= $delta['content'];
  11401. yield [
  11402. 'type' => 'content',
  11403. 'content' => $delta['content'],
  11404. ];
  11405. }
  11406. }
  11407. // 获取使用统计信息
  11408. if (isset($json['usage'])) {
  11409. $usage = $json['usage'];
  11410. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11411. }
  11412. } catch (\Exception $e) {
  11413. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11414. continue;
  11415. }
  11416. }
  11417. }
  11418. dLog('deepseek')->info('流式读取完成', [
  11419. 'content_length' => strlen($fullContent),
  11420. 'reasoning_length' => strlen($fullReasoningContent)
  11421. ]);
  11422. yield [
  11423. 'type' => 'done',
  11424. 'full_content' => $fullContent,
  11425. 'full_reasoning' => $fullReasoningContent,
  11426. 'usage' => $usage
  11427. ];
  11428. } catch (\Exception $e) {
  11429. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11430. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11431. throw $e;
  11432. }
  11433. }
  11434. /**
  11435. * 检查并创建图片生成任务
  11436. *
  11437. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11438. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11439. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11440. * @param string $art_style 美术风格
  11441. * @return array 更新后的资源列表
  11442. */
  11443. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11444. {
  11445. // 确保参数为数组
  11446. $merged_items = is_array($merged_items) ? $merged_items : [];
  11447. $global_items = is_array($global_items) ? $global_items : [];
  11448. // 构建全局资源映射表,用于快速查找
  11449. $global_map = [];
  11450. foreach ($global_items as $item) {
  11451. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11452. if ($itemKey === '') {
  11453. continue;
  11454. }
  11455. $global_map[$itemKey] = $item;
  11456. }
  11457. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11458. foreach ($merged_items as &$item) {
  11459. $item_name = getProp($item, $nameKey);
  11460. $item_description = getProp($item, 'description');
  11461. // $item_url = getProp($item, 'url');
  11462. // // 如果已有图片URL,跳过
  11463. // if (!empty($item_url)) {
  11464. // continue;
  11465. // }
  11466. // 如果是旁白角色,跳过
  11467. if ($nameKey === 'role' && $item_name === '旁白') {
  11468. continue;
  11469. }
  11470. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11471. if ($itemKey === '') {
  11472. continue;
  11473. }
  11474. $need_create_task = false;
  11475. // 条件1:在全局资源中找不到匹配的名称
  11476. if (!isset($global_map[$itemKey])) {
  11477. $need_create_task = true;
  11478. } else {
  11479. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11480. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11481. $current_description = trim((string)$item_description);
  11482. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11483. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11484. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11485. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11486. $need_create_task = true;
  11487. }
  11488. }
  11489. // 如果需要创建任务,调用图片生成服务
  11490. if ($need_create_task) {
  11491. try {
  11492. // 优先使用 pic_prompt,如果没有则使用 description
  11493. $pic_prompt = getProp($item, 'pic_prompt');
  11494. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11495. // 添加美术风格前缀
  11496. if ($art_style) {
  11497. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11498. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11499. $description = "{$prefix}:{$description}";
  11500. }
  11501. $params = [
  11502. 'prompt' => $description,
  11503. 'ref_img_urls' => []
  11504. ];
  11505. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11506. $task_id = $task->id;
  11507. if ($task_id) {
  11508. $item['task_id'] = $task_id;
  11509. $item['task_status'] = 'processing';
  11510. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11511. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11512. }
  11513. } catch (\Exception $e) {
  11514. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11515. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11516. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11517. // 不抛出异常,继续处理其他资源
  11518. }
  11519. }
  11520. }
  11521. return $merged_items;
  11522. }
  11523. /**
  11524. * 同步新出现的主体和场景到全局
  11525. *
  11526. * @param int $anime_id 动漫ID
  11527. * @param array $merged_roles 合并后的角色列表
  11528. * @param array $merged_scenes 合并后的场景列表
  11529. * @param array $global_roles 全局角色列表
  11530. * @param array $global_scenes 全局场景列表
  11531. * @return void
  11532. */
  11533. private function syncNewResourcesToGlobal(
  11534. int $anime_id,
  11535. array $merged_roles,
  11536. array $merged_scenes,
  11537. array $global_roles,
  11538. array $global_scenes
  11539. ): void {
  11540. // 构建全局角色映射表
  11541. $global_role_map = [];
  11542. foreach ($global_roles as $role) {
  11543. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11544. if ($roleKey !== '') {
  11545. $global_role_map[$roleKey] = $role;
  11546. }
  11547. }
  11548. // 构建全局场景映射表
  11549. $global_scene_map = [];
  11550. foreach ($global_scenes as $scene) {
  11551. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11552. if ($sceneKey !== '') {
  11553. $global_scene_map[$sceneKey] = $scene;
  11554. }
  11555. }
  11556. $need_update = false;
  11557. $new_global_roles = $global_roles;
  11558. $new_global_scenes = $global_scenes;
  11559. // 检查并添加新角色到全局
  11560. foreach ($merged_roles as $role) {
  11561. $role_name = getProp($role, 'role');
  11562. // 跳过旁白
  11563. if ($role_name === '旁白') {
  11564. continue;
  11565. }
  11566. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11567. if ($roleKey === '') {
  11568. continue;
  11569. }
  11570. // 如果全局中不存在该角色,添加到全局
  11571. if (!isset($global_role_map[$roleKey])) {
  11572. $new_global_roles[] = [
  11573. 'role' => $role_name,
  11574. 'description' => getProp($role, 'description', ''),
  11575. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11576. 'voice_name' => getProp($role, 'voice_name', ''),
  11577. 'voice_type' => getProp($role, 'voice_type', ''),
  11578. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11579. 'url' => getProp($role, 'url', ''),
  11580. 'task_id' => getProp($role, 'task_id', ''),
  11581. 'task_status' => getProp($role, 'task_status', ''),
  11582. ];
  11583. $global_role_map[$roleKey] = true; // 标记已添加
  11584. $need_update = true;
  11585. dLog('deepseek')->info("新角色同步到全局", [
  11586. 'anime_id' => $anime_id,
  11587. 'role' => $role_name,
  11588. 'task_id' => getProp($role, 'task_id', ''),
  11589. ]);
  11590. }
  11591. // else {
  11592. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11593. // $global_role = $global_role_map[$roleKey];
  11594. // if (is_array($global_role)) {
  11595. // $updated = false;
  11596. // $update_fields = [];
  11597. // // 检查描述是否更新
  11598. // $current_description = trim((string)getProp($role, 'description'));
  11599. // $global_description = trim((string)getProp($global_role, 'description'));
  11600. // if ($current_description !== '' && $current_description !== $global_description) {
  11601. // $updated = true;
  11602. // $update_fields[] = 'description';
  11603. // }
  11604. // // 检查pic_prompt是否更新
  11605. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11606. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11607. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11608. // $updated = true;
  11609. // $update_fields[] = 'pic_prompt';
  11610. // }
  11611. // // 检查图片任务信息是否更新
  11612. // $current_task_id = getProp($role, 'task_id');
  11613. // $global_task_id = getProp($global_role, 'task_id');
  11614. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11615. // $updated = true;
  11616. // $update_fields[] = 'task_id';
  11617. // }
  11618. // // 如果有更新,同步到全局
  11619. // if ($updated) {
  11620. // foreach ($new_global_roles as &$global_role_item) {
  11621. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11622. // if ($global_role_key === $roleKey) {
  11623. // if (in_array('description', $update_fields)) {
  11624. // $global_role_item['description'] = $current_description;
  11625. // }
  11626. // if (in_array('pic_prompt', $update_fields)) {
  11627. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11628. // }
  11629. // if (in_array('task_id', $update_fields)) {
  11630. // $global_role_item['task_id'] = $current_task_id;
  11631. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11632. // $global_role_item['url'] = getProp($role, 'url', '');
  11633. // }
  11634. // break;
  11635. // }
  11636. // }
  11637. // $need_update = true;
  11638. // dLog('deepseek')->info("角色信息更新到全局", [
  11639. // 'anime_id' => $anime_id,
  11640. // 'role' => $role_name,
  11641. // 'update_fields' => implode(',', $update_fields),
  11642. // ]);
  11643. // }
  11644. // }
  11645. // }
  11646. }
  11647. // 检查并添加新场景到全局
  11648. foreach ($merged_scenes as $scene) {
  11649. $scene_name = getProp($scene, 'scene');
  11650. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11651. if ($sceneKey === '') {
  11652. continue;
  11653. }
  11654. // 如果全局中不存在该场景,添加到全局
  11655. if (!isset($global_scene_map[$sceneKey])) {
  11656. $new_global_scenes[] = [
  11657. 'scene' => $scene_name,
  11658. 'description' => getProp($scene, 'description', ''),
  11659. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11660. 'url' => getProp($scene, 'url', ''),
  11661. 'task_id' => getProp($scene, 'task_id', ''),
  11662. 'task_status' => getProp($scene, 'task_status', ''),
  11663. ];
  11664. $global_scene_map[$sceneKey] = true; // 标记已添加
  11665. $need_update = true;
  11666. dLog('deepseek')->info("新场景同步到全局", [
  11667. 'anime_id' => $anime_id,
  11668. 'scene' => $scene_name,
  11669. 'task_id' => getProp($scene, 'task_id', ''),
  11670. ]);
  11671. }
  11672. // else {
  11673. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11674. // $global_scene = $global_scene_map[$sceneKey];
  11675. // if (is_array($global_scene)) {
  11676. // $updated = false;
  11677. // $update_fields = [];
  11678. // // 检查描述是否更新
  11679. // $current_description = trim((string)getProp($scene, 'description'));
  11680. // $global_description = trim((string)getProp($global_scene, 'description'));
  11681. // if ($current_description !== '' && $current_description !== $global_description) {
  11682. // $updated = true;
  11683. // $update_fields[] = 'description';
  11684. // }
  11685. // // 检查pic_prompt是否更新
  11686. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11687. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11688. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11689. // $updated = true;
  11690. // $update_fields[] = 'pic_prompt';
  11691. // }
  11692. // // 检查图片任务信息是否更新
  11693. // $current_task_id = getProp($scene, 'task_id');
  11694. // $global_task_id = getProp($global_scene, 'task_id');
  11695. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11696. // $updated = true;
  11697. // $update_fields[] = 'task_id';
  11698. // }
  11699. // // 如果有更新,同步到全局
  11700. // if ($updated) {
  11701. // foreach ($new_global_scenes as &$global_scene_item) {
  11702. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11703. // if ($global_scene_key === $sceneKey) {
  11704. // if (in_array('description', $update_fields)) {
  11705. // $global_scene_item['description'] = $current_description;
  11706. // }
  11707. // if (in_array('pic_prompt', $update_fields)) {
  11708. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11709. // }
  11710. // if (in_array('task_id', $update_fields)) {
  11711. // $global_scene_item['task_id'] = $current_task_id;
  11712. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11713. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11714. // }
  11715. // break;
  11716. // }
  11717. // }
  11718. // $need_update = true;
  11719. // dLog('deepseek')->info("场景信息更新到全局", [
  11720. // 'anime_id' => $anime_id,
  11721. // 'scene' => $scene_name,
  11722. // 'update_fields' => implode(',', $update_fields),
  11723. // ]);
  11724. // }
  11725. // }
  11726. // }
  11727. }
  11728. // 如果有新增或更新,更新数据库
  11729. if ($need_update) {
  11730. $update_data = [
  11731. 'roles' => json_encode($new_global_roles, 256),
  11732. 'scenes' => json_encode($new_global_scenes, 256),
  11733. 'updated_at' => date('Y-m-d H:i:s'),
  11734. ];
  11735. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11736. if ($result !== false) {
  11737. dLog('deepseek')->info("全局角色和场景更新成功", [
  11738. 'anime_id' => $anime_id,
  11739. 'roles_count' => count($new_global_roles),
  11740. 'scenes_count' => count($new_global_scenes),
  11741. ]);
  11742. } else {
  11743. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11744. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11745. }
  11746. }
  11747. }
  11748. }