DeepSeekService.php 285 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Facade\Site;
  5. use App\Libs\Utils;
  6. use GuzzleHttp\Client;
  7. use DateTime;
  8. use DateTimeZone;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\Redis;
  13. use OSS\Core\OssException;
  14. use OSS\OssClient;
  15. use Smalot\PdfParser\Parser as PdfParser;
  16. use TCPDF;
  17. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  18. use Predis\Command\Traits\Get\Get;
  19. class DeepSeekService
  20. {
  21. private $url;
  22. private $api_key;
  23. private $sys_message;
  24. private $headers;
  25. private $valid_text_models;
  26. protected $aiImageGenerationService;
  27. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  28. $this->aiImageGenerationService = $aiImageGenerationService;
  29. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  30. $this->api_key = env('DEEPSEEK_API_KEY');
  31. $this->headers = [
  32. 'Authorization' => 'Bearer '.$this->api_key,
  33. 'Content-Type' => 'application/json; charset=UTF-8'
  34. ];
  35. // 火山引擎模型列表
  36. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  37. $this->sys_message = [
  38. 'role' => 'system',
  39. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  40. 强制要求:\n
  41. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  42. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  43. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  44. 普通要求:\n
  45. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  46. 2.<分集剧本>要求包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。\n\n
  47. 示例如下:\n
  48. ###剧本名:西昆仑
  49. ###故事梗概
  50. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  51. ###剧本亮点
  52. 亮点1:绝境奇药,生死一线
  53. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  54. 亮点2:结拜兄妹,化解尴尬
  55. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  56. 亮点3:纤发夺命,情愫暗涌
  57. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  58. ###人物关系
  59. 阿雪与梁萧之间存在兄妹之情。
  60. ###核心矛盾
  61. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  62. ###主体列表
  63. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  64. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  65. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  66. 阴阳球:天地异宝,能化生精气,救人于危难。
  67. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  68. ###美术风格
  69. 基础画风风格词:厚涂古风
  70. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  71. ###场景列表
  72. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  73. ###分集剧本
  74. ##分集01
  75. 第1集: 第一集的标题
  76. 场景描述:地点、时间、场景
  77. 运镜:固定近距离
  78. 出场角色:男主、女主
  79. 台词内容:
  80. 女主: 女主对话
  81. 男主:男主对话
  82. 女主: 女主对话
  83. 男主: 男主对话
  84. ##分集02
  85. 第2集: 第二集的标题
  86. 场景描述:地点、时间、场景
  87. 运镜:固定近距离
  88. 出场角色:男主、女主
  89. 台词内容:
  90. 女主: 女主对话
  91. 男主:男主对话
  92. 女主: 女主对话
  93. 男主: 男主对话"
  94. ];
  95. }
  96. /**
  97. * 通用文生文方法 - 支持多模型流式输出和图片输入
  98. *
  99. * @param array $data 请求参数
  100. * @return \Generator 返回生成器,用于流式输出
  101. */
  102. public function generateText($data) {
  103. // 获取请求参数
  104. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  105. $messages = getProp($data, 'messages', []);
  106. $systemPrompt = getProp($data, 'system_prompt', '');
  107. $prompt = getProp($data, 'prompt', '');
  108. $images = getProp($data, 'images', []); // 支持多张图片
  109. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  110. // 如果没有提供messages,则根据system_prompt、content和images构建
  111. if (empty($messages)) {
  112. $messages = [];
  113. // 添加系统提示词
  114. if (!empty($systemPrompt)) {
  115. $messages[] = [
  116. 'role' => 'system',
  117. 'content' => $systemPrompt
  118. ];
  119. }
  120. // 构建用户消息内容(支持文本+图片)
  121. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  122. $userMessage = [
  123. 'role' => 'user',
  124. 'content' => []
  125. ];
  126. // 添加文本内容
  127. if (!empty($prompt)) {
  128. $userMessage['content'][] = [
  129. 'type' => 'text',
  130. 'text' => $prompt
  131. ];
  132. }
  133. // 处理上传的图片文件
  134. if (!empty($images)) {
  135. if (!is_array($images)) {
  136. $images = [$images];
  137. }
  138. foreach ($images as $image) {
  139. $imageBase64 = $this->processImageToBase64($image);
  140. if ($imageBase64) {
  141. $userMessage['content'][] = [
  142. 'type' => 'image_url',
  143. 'image_url' => [
  144. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  145. ]
  146. ];
  147. }
  148. }
  149. }
  150. // 处理图片URL
  151. if (!empty($imageUrls)) {
  152. if (!is_array($imageUrls)) {
  153. $imageUrls = [$imageUrls];
  154. }
  155. foreach ($imageUrls as $url) {
  156. if (!empty($url)) {
  157. $userMessage['content'][] = [
  158. 'type' => 'image_url',
  159. 'image_url' => [
  160. 'url' => $url
  161. ]
  162. ];
  163. }
  164. }
  165. }
  166. // 如果只有文本内容,简化为字符串格式
  167. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  168. $userMessage['content'] = $userMessage['content'][0]['text'];
  169. }
  170. $messages[] = $userMessage;
  171. }
  172. }
  173. // 验证messages不为空
  174. if (empty($messages)) {
  175. Utils::throwError('20003:请提供有效的对话内容');
  176. }
  177. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  178. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  179. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  180. if ($model === 'deepseek-chat') {
  181. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  182. $model = 'deepseek-v4-flash';
  183. $thinkingMode = 'disabled';
  184. } elseif ($model === 'deepseek-reasoner') {
  185. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  186. $model = 'deepseek-v4-flash';
  187. $thinkingMode = 'enabled';
  188. }
  189. // 构建请求参数
  190. $post_data = [
  191. 'model' => $model,
  192. 'messages' => $messages,
  193. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  194. 'temperature' => getProp($data, 'temperature', 1),
  195. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  196. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  197. 'thinking' => ['type' => $thinkingMode],
  198. 'stream' => true // 启用流式输出
  199. ];
  200. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  201. // 添加可选参数
  202. if (isset($data['top_p'])) {
  203. $post_data['top_p'] = $data['top_p'];
  204. }
  205. if (isset($data['response_format'])) {
  206. $post_data['response_format'] = $data['response_format'];
  207. }
  208. dLog('deepseek')->info('通用文生文请求参数', ['model' => $model, 'thinking' => $thinkingMode, 'messages_count' => count($messages)]);
  209. // 根据模型类型选择调用方法
  210. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  211. // DeepSeek 官方模型使用 DeepSeek API
  212. return $this->deepSeekStreamResponse($post_data);
  213. } else if (in_array($model, $this->valid_text_models)) {
  214. // 火山引擎支持的模型使用火山引擎 API
  215. return $this->volcEngineChatCompletion($post_data);
  216. } else {
  217. Utils::throwError('20003:不支持的模型: ' . $model);
  218. }
  219. }
  220. /**
  221. * 处理图片转换为base64
  222. *
  223. * @param mixed $image 图片文件对象或文件路径
  224. * @return string|null base64编码的图片数据
  225. */
  226. private function processImageToBase64($image) {
  227. try {
  228. // 获取文件路径
  229. if (is_string($image)) {
  230. $filePath = $image;
  231. } else {
  232. // Laravel UploadedFile 对象
  233. $filePath = $image->getRealPath();
  234. }
  235. if (!file_exists($filePath)) {
  236. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  237. return null;
  238. }
  239. // 验证是否为图片文件
  240. $imageInfo = @getimagesize($filePath);
  241. if ($imageInfo === false) {
  242. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  243. return null;
  244. }
  245. // 读取图片并转换为base64
  246. $imageData = file_get_contents($filePath);
  247. $base64Image = base64_encode($imageData);
  248. dLog('deepseek')->info('图片转换成功', [
  249. 'size' => strlen($imageData),
  250. 'type' => $imageInfo['mime']
  251. ]);
  252. return $base64Image;
  253. } catch (\Exception $e) {
  254. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  255. return null;
  256. }
  257. }
  258. private function getArtStylePromptMappings(): array
  259. {
  260. return [
  261. '日系动漫风格' => [
  262. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  263. 'prompt' => "日系动漫风格,线条干净流畅,色彩明亮柔和,人物精致,光影细腻,画面统一稳定"
  264. ],
  265. '国漫风格' => [
  266. 'aliases' => ['国漫风格', '国漫'],
  267. 'prompt' => "国漫风格,线条硬朗,人物成熟大气,色彩浓郁,光影对比强烈,整体画风统一,适合漫剧叙事"
  268. ],
  269. 'Q版卡通风格' => [
  270. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  271. 'prompt' => "Q版卡通风格,头大身小造型可爱,线条简洁,色彩明快,无复杂阴影,整体萌系干净统一"
  272. ],
  273. '简约扁平风格' => [
  274. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  275. 'prompt' => "简约扁平风格,大块纯色无渐变,线条简洁现代,画面干净清爽,不出现复杂纹理与光影"
  276. ],
  277. '古风仙侠风格' => [
  278. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  279. 'prompt' => "古风仙侠风格,汉服飘逸,云雾缭绕仙气空灵,色调清雅,光影柔和,国风氛围统一"
  280. ],
  281. '武侠风格' => [
  282. 'aliases' => ['武侠风格', '武侠'],
  283. 'prompt' => "武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态自然,色调沉稳大气"
  284. ],
  285. '新中式水墨风格' => [
  286. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  287. 'prompt' => "新中式水墨风格,淡墨渲染笔触自然,留白有意境,色调清雅,国风质感统一不杂乱"
  288. ],
  289. '写实插画风格' => [
  290. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  291. 'prompt' => "写实插画风格,真实人体比例,光影自然细腻,画面质感真实,不卡通不崩坏"
  292. ],
  293. '3D卡通风格' => [
  294. 'aliases' => ['3D卡通风格', '3D卡通'],
  295. 'prompt' => "3D卡通风格,立体建模质感柔和,造型圆润光滑,光影干净,整体风格统一不穿模"
  296. ],
  297. '条漫风格' => [
  298. 'aliases' => ['条漫风格', '条漫'],
  299. 'prompt' => "条漫风格,纵向分镜简洁,色彩清淡,适合上下滑动阅读,画面轻量化且整体统一"
  300. ],
  301. '赛博朋克风格' => [
  302. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  303. 'prompt' => "赛博朋克风格,霓虹灯光未来都市,暗色调科技感强,高对比光影,风格统一强烈"
  304. ],
  305. '暗黑悬疑风格' => [
  306. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  307. 'prompt' => "暗黑悬疑风格,低饱和冷色调,强阴影光线昏暗,氛围神秘压抑,整体色调统一"
  308. ],
  309. '治愈清新风格' => [
  310. 'aliases' => ['治愈清新风格', '治愈清新'],
  311. 'prompt' => "治愈清新风格,马卡龙柔和色系,柔光暖调,画面干净舒适,氛围温暖不杂乱"
  312. ],
  313. ];
  314. }
  315. public function getArtStylePromptByInput($inputArtStyle): string
  316. {
  317. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  318. if ($normalizedInput === '') {
  319. return '';
  320. }
  321. foreach ($this->getArtStylePromptMappings() as $mapping) {
  322. foreach ($mapping['aliases'] as $alias) {
  323. $normalizedAlias = $this->normalizeArtStyleInput($alias);
  324. if ($normalizedAlias === '') {
  325. continue;
  326. }
  327. if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  328. return $mapping['prompt'];
  329. }
  330. }
  331. }
  332. return '';
  333. }
  334. private function normalizeArtStyleInput($value): string
  335. {
  336. $value = trim((string)$value);
  337. if ($value === '') {
  338. return '';
  339. }
  340. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  341. return mb_strtolower($value, 'UTF-8');
  342. }
  343. private function replaceArtStyleSection(string $content, string $artStyle): string
  344. {
  345. if ($content === '' || $artStyle === '') {
  346. return $content;
  347. }
  348. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  349. if (!preg_match($pattern, $content)) {
  350. return $content;
  351. }
  352. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  353. }
  354. /**
  355. * DeepSeek流式输出处理方法
  356. *
  357. * @param array $post_data DeepSeek API请求参数
  358. * @return \Generator 返回生成器,用于流式输出
  359. */
  360. private function deepSeekStreamResponse($post_data) {
  361. $client = new Client(['timeout' => 1200, 'verify' => false]);
  362. $response = $client->post($this->url, [
  363. 'json' => $post_data,
  364. 'headers' => $this->headers,
  365. 'stream' => true // 启用流式响应
  366. ]);
  367. $body = $response->getBody();
  368. $fullContent = '';
  369. $fullReasoningContent = '';
  370. $usage = [];
  371. $buffer = '';
  372. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  373. // 逐行读取流式响应
  374. while (!$body->eof()) {
  375. $chunk = $body->read(1024); // 每次读取 1KB
  376. $buffer .= $chunk;
  377. // 按行分割
  378. $lines = explode("\n", $buffer);
  379. // 保留最后一个不完整的行
  380. $buffer = array_pop($lines);
  381. foreach ($lines as $line) {
  382. $line = trim($line);
  383. // 跳过空行
  384. if (empty($line)) {
  385. continue;
  386. }
  387. // 检查是否是 SSE 数据行
  388. if (strpos($line, 'data: ') !== 0) {
  389. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  390. continue;
  391. }
  392. $data = substr($line, 6); // 移除 "data: " 前缀
  393. if ($data === '[DONE]') {
  394. dLog('deepseek')->info('收到结束标记');
  395. break 2; // 跳出两层循环
  396. }
  397. try {
  398. $json = json_decode($data, true);
  399. if (json_last_error() !== JSON_ERROR_NONE) {
  400. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  401. continue;
  402. }
  403. if (isset($json['choices'][0]['delta'])) {
  404. $delta = $json['choices'][0]['delta'];
  405. // 处理思维链内容(仅 deepseek-reasoner 模型)
  406. if (isset($delta['reasoning_content'])) {
  407. $fullReasoningContent .= $delta['reasoning_content'];
  408. yield [
  409. 'type' => 'reasoning',
  410. 'content' => $delta['reasoning_content'],
  411. 'full_reasoning' => $fullReasoningContent
  412. ];
  413. }
  414. // 处理最终回答内容
  415. if (isset($delta['content'])) {
  416. $fullContent .= $delta['content'];
  417. yield [
  418. 'type' => 'content',
  419. 'content' => $delta['content'],
  420. ];
  421. }
  422. }
  423. // 获取使用统计信息
  424. if (isset($json['usage'])) {
  425. $usage = $json['usage'];
  426. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  427. }
  428. } catch (\Exception $e) {
  429. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  430. continue;
  431. }
  432. }
  433. }
  434. dLog('deepseek')->info('流式读取完成', [
  435. 'content_length' => strlen($fullContent),
  436. 'reasoning_length' => strlen($fullReasoningContent)
  437. ]);
  438. yield [
  439. 'type' => 'done',
  440. 'full_content' => $fullContent,
  441. 'full_reasoning' => $fullReasoningContent,
  442. 'usage' => $usage
  443. ];
  444. }
  445. // 与推理模型对话
  446. public function chatWithReasoner($data) {
  447. $content = getProp($data, 'content');
  448. $model = getProp($data, 'model', 'r1');
  449. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  450. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  451. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  452. if ($model == 'r1') {
  453. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  454. $thinkingMode = 'disabled';
  455. } else {
  456. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  457. $thinkingMode = 'disabled';
  458. }
  459. // 获取可选情感(根据音色可支持情感选)
  460. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  461. $emotion_list = [];
  462. foreach ($timbre_emotion as $emotion) {
  463. $tmp = explode(',', $emotion);
  464. $emotion_list = array_merge($emotion_list, $tmp);
  465. }
  466. $emotion_list = array_unique($emotion_list);
  467. $emotion_str = implode('、', $emotion_list);
  468. // // 获取可选情感
  469. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  470. // $emotion_str = implode('、', $emotion_list);
  471. // 是否启用情感
  472. $enable_emotion = getProp($data, 'enable_emotion', 0);
  473. if ($enable_emotion) {
  474. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  475. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  476. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  477. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  478. }else {
  479. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  480. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  481. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  482. }
  483. $messages = [
  484. [
  485. 'role' => 'system',
  486. 'content' => $sys_content
  487. ],
  488. [
  489. 'role' => 'user',
  490. 'content' => $content
  491. ]
  492. ];
  493. $post_data = [
  494. 'model' => $model,
  495. 'messages' => $messages,
  496. // 'max_tokens' => 8192,
  497. 'temperature' => 1,
  498. 'frequency_penalty' => 0,
  499. 'presence_penalty' => 0,
  500. 'thinking' => ['type' => $thinkingMode],
  501. 'response_format' => [
  502. 'type' => 'text'
  503. ],
  504. 'stream' => false
  505. ];
  506. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  507. // 根据模型类型选择调用方法
  508. $fullContent = '';
  509. $usage = [];
  510. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  511. // DeepSeek 官方模型使用 DeepSeek API
  512. $chatResult = $this->chatOnly($post_data);
  513. } else {
  514. // 其他模型使用火山引擎API
  515. $chatResult = $this->volcEngineChatCompletion($post_data);
  516. }
  517. if (is_array($chatResult)) {
  518. $fullContent = $chatResult['fullContent'];
  519. $usage = $chatResult['usage'];
  520. }
  521. // 处理获取到的剧本数据
  522. $script_content = handleScriptWords($fullContent, $enable_emotion);
  523. $result = [
  524. 'origin_content' => $fullContent,
  525. 'roles' => getProp($script_content, 'roles'),
  526. 'words' => getProp($script_content, 'words'),
  527. ];
  528. return $result;
  529. }
  530. public function resetParagraphAudio($data) {
  531. $bid = getProp($data, 'bid');
  532. $cid = getProp($data, 'cid');
  533. $version_id = getProp($data, 'version_id');
  534. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  535. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  536. 'generate_status' => '待制作',
  537. 'updated_at' => date('Y-m-d H:i:s')
  538. ]);
  539. }
  540. public function saveParagraphAudio($data) {
  541. $bid = getProp($data, 'bid');
  542. $cid = getProp($data, 'cid');
  543. $version_id = getProp($data, 'version_id');
  544. $sequence = getProp($data, 'sequence');
  545. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  546. // 获取所有情感
  547. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  548. $emotion_list = array_flip($emotion_list);
  549. // 获取音色支持情感
  550. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  551. $timbre_emotion = explode(',', $timbre_emotion);
  552. $emotion = getProp($data, 'emotion');
  553. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  554. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  555. $list = [
  556. 'bid' => $bid,
  557. 'cid' => $cid,
  558. 'version_id' => $version_id,
  559. 'sequence' => $sequence,
  560. 'role' => getProp($data, 'role'),
  561. 'gender' => getProp($data, 'gender'),
  562. 'text' => trim(getProp($data, 'text')),
  563. 'emotion' => $emotion,
  564. 'emotion_type' => $emotion_type,
  565. 'voice_type' => getProp($data, 'voice_type'),
  566. 'voice_name' => getProp($data, 'voice_name'),
  567. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  568. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  569. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  570. 'pitch' => getProp($data, 'pitch', 0),
  571. // 'paragraph_audio_url' => '',
  572. 'generate_status' => '制作中',
  573. 'error_msg' => '',
  574. 'updated_at' => date('Y-m-d H:i:s')
  575. ];
  576. $continue = false;
  577. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  578. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  579. $list['generate_status'] = '制作成功';
  580. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  581. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  582. $continue = true;
  583. }
  584. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  585. if ($id) {
  586. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  587. }else {
  588. $list['created_at'] = date('Y-m-d H:i:s');
  589. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  590. $boolen = $id ? true : false;
  591. }
  592. // 如果更新成功则加入查询队列
  593. if ($boolen) {
  594. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  595. Redis::sadd($redis_key, $id);
  596. }
  597. if ($boolen && !$continue) {
  598. $boolen = false;
  599. $client = new Client(['timeout' => 300, 'verify' => false]);
  600. // 根据ID通过API通知合成音频
  601. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  602. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  603. $response = $result->getBody()->getContents();
  604. $response_arr = json_decode($response, true);
  605. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  606. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  607. Log::info('通知火山生成段落音频失败: '.$error_msg);
  608. Utils::throwError('20003:通知火山生成段落音频失败');
  609. }
  610. $boolen = true;
  611. }
  612. return $boolen;
  613. }
  614. public function insertAudioEffect($data) {
  615. $audio_id = getProp($data, 'audio_id');
  616. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  617. $bid = getProp($chapter_audio, 'bid');
  618. $version_id = getProp($chapter_audio, 'version_id');
  619. $cid = getProp($chapter_audio, 'cid');
  620. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  621. $audio_effect_json = getProp($data, 'audio_effect_json');
  622. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  623. try {
  624. DB::beginTransaction();
  625. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  626. if (!$count) {
  627. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  628. }else {
  629. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  630. }
  631. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  632. 'audio_effect_status' => '添加中',
  633. 'audio_effect_json' => $audio_effect_json,
  634. 'updated_at' => date('Y-m-d H:i:s')
  635. ]);
  636. if (!$boolen1) {
  637. DB::rollBack();
  638. Utils::throwError('20003:更新生成数据失败');
  639. }
  640. $id = DB::table('mp_audio_tasks')->insertGetId([
  641. 'audio_id' => $audio_id,
  642. 'generate_status' => '执行中',
  643. 'generate_json' => json_encode([], 256),
  644. 'bid' => $bid,
  645. 'book_name' => getProp($chapter_audio, 'book_name'),
  646. 'version_id' => $version_id,
  647. 'version_name' => getProp($chapter_audio, 'version_name'),
  648. 'cid' => $cid,
  649. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  650. 'task_name' => $task_name,
  651. 'created_at' => date('Y-m-d H:i:s'),
  652. 'updated_at' => date('Y-m-d H:i:s')
  653. ]);
  654. if (!$id) {
  655. DB::rollBack();
  656. Utils::throwError('20003:创建任务失败');
  657. }
  658. }catch (\Exception $e) {
  659. DB::rollBack();
  660. Utils::throwError('20003:'.$e->getMessage());
  661. }
  662. DB::commit();
  663. $client = new Client(['timeout' => 300, 'verify' => false]);
  664. // 根据ID通过API通知合成音频
  665. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  666. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  667. $response = $result->getBody()->getContents();
  668. $response_arr = json_decode($response, true);
  669. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  670. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  671. Log::info('通知火山插入音效失败: '.$error_msg);
  672. Utils::throwError('20003:通知火山插入音效失败');
  673. }
  674. return true;
  675. }
  676. public function insertBgm($data) {
  677. $audio_id = getProp($data, 'audio_id');
  678. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  679. $bid = getProp($chapter_audio, 'bid');
  680. $version_id = getProp($chapter_audio, 'version_id');
  681. $cid = getProp($chapter_audio, 'cid');
  682. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  683. $bgm_json = getProp($data, 'bgm_json');
  684. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  685. if (!$bgm_json) {
  686. $bgm_json = getProp($data, 'audio_effect_json');
  687. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  688. }
  689. try {
  690. DB::beginTransaction();
  691. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  692. if (!$count) {
  693. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  694. }else {
  695. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  696. }
  697. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  698. 'bgm_status' => '添加中',
  699. 'bgm_json' => $bgm_json,
  700. 'updated_at' => date('Y-m-d H:i:s')
  701. ]);
  702. if (!$boolen1) {
  703. DB::rollBack();
  704. Utils::throwError('20003:更新生成数据失败');
  705. }
  706. $id = DB::table('mp_audio_tasks')->insertGetId([
  707. 'audio_id' => $audio_id,
  708. 'generate_status' => '执行中',
  709. 'generate_json' => json_encode([], 256),
  710. 'bid' => $bid,
  711. 'book_name' => getProp($chapter_audio, 'book_name'),
  712. 'version_id' => $version_id,
  713. 'version_name' => getProp($chapter_audio, 'version_name'),
  714. 'cid' => $cid,
  715. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  716. 'task_name' => $task_name,
  717. 'created_at' => date('Y-m-d H:i:s'),
  718. 'updated_at' => date('Y-m-d H:i:s')
  719. ]);
  720. if (!$id) {
  721. DB::rollBack();
  722. Utils::throwError('20003:创建任务失败');
  723. }
  724. }catch (\Exception $e) {
  725. DB::rollBack();
  726. Utils::throwError('20003:'.$e->getMessage());
  727. }
  728. DB::commit();
  729. $client = new Client(['timeout' => 300, 'verify' => false]);
  730. // 根据ID通过API通知合成音频
  731. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  732. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  733. $response = $result->getBody()->getContents();
  734. $response_arr = json_decode($response, true);
  735. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  736. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  737. Log::info('通知火山插入bgm失败: '.$error_msg);
  738. Utils::throwError('20003:通知火山插入bgm失败');
  739. }
  740. return true;
  741. }
  742. public function getParagraphAudios($data) {
  743. $bid = getProp($data, 'bid');
  744. $cid = getProp($data, 'cid');
  745. $version_id = getProp($data, 'version_id');
  746. $sequence = getProp($data, 'sequence');
  747. // 获取已生成的音频
  748. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  749. if ($sequence) $query->where('sequence', $sequence);
  750. $paragraph_audios = $query->orderBy('sequence')->get();
  751. $result = [];
  752. foreach($paragraph_audios as $item) {
  753. $result[] = [
  754. 'sequence' => getProp($item, 'sequence'),
  755. 'role' => getProp($item, 'role'),
  756. 'gender' => getProp($item, 'gender'),
  757. 'text' => trim(getProp($item, 'text')),
  758. 'emotion' => getProp($item, 'emotion'),
  759. 'emotion_type' => getProp($item, 'emotion_type'),
  760. 'voice_type' => getProp($item, 'voice_type'),
  761. 'voice_name' => getProp($item, 'voice_name'),
  762. 'speed_ratio' => getProp($item, 'speed_ratio'),
  763. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  764. 'emotion_scale' => getProp($item, 'emotion_scale'),
  765. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  766. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  767. ];
  768. }
  769. return $result;
  770. }
  771. // 新增合成任务
  772. public function addGenerateTask($data) {
  773. $bid = getProp($data, 'bid');
  774. $cid = getProp($data, 'cid');
  775. $version_id = getProp($data, 'version_id');
  776. $generate_json = getProp($data, 'generate_json');
  777. // 获取已生成的音频
  778. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  779. $paragraph_list = [];
  780. foreach($paragraph_audios as $item) {
  781. $paragraph_list[getProp($item, 'sequence')] = [
  782. 'role' => getProp($item, 'role'),
  783. 'gender' => getProp($item, 'gender'),
  784. 'text' => trim(getProp($item, 'text')),
  785. 'emotion' => getProp($item, 'emotion'),
  786. 'emotion_type' => getProp($item, 'emotion_type'),
  787. 'voice_type' => getProp($item, 'voice_type'),
  788. 'voice_name' => getProp($item, 'voice_name'),
  789. 'speed_ratio' => getProp($item, 'speed_ratio'),
  790. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  791. 'emotion_scale' => getProp($item, 'emotion_scale'),
  792. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  793. ];
  794. }
  795. // 更新角色-音色信息
  796. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  797. $existed_role_info = json_decode($existed_role_info, true);
  798. if (!$existed_role_info) $existed_role_info = [];
  799. // 获取情感信息
  800. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  801. $emotion_list = array_flip($emotion_list);
  802. // 获取音色对应情感组
  803. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  804. $timbre_emotion_list = [];
  805. foreach($timbre_emotions as $item) {
  806. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  807. }
  808. // 构造生成音频的json
  809. $words = json_decode($generate_json, true);
  810. // 最终合成前的参数组
  811. $mp_chapter_paragraph_audios = [];
  812. $sequence = 1;
  813. $complete_paragraph_sequences = [];
  814. foreach($words as &$word) {
  815. 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:参数格式有误');
  816. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  817. $role = getProp($word, 'role');
  818. $word['gender'] = (int)$word['gender'];
  819. // 判断音色对应情感是否支持,不支持则调整为中性
  820. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  821. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  822. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  823. if (isset($emotion_list[getProp($word, 'emotion')])) {
  824. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  825. }else {
  826. $word['emotion'] = '中性';
  827. $word['emotion_type'] = 'neutral';
  828. }
  829. $existed_role_info[$role] = [
  830. 'timbre_type' => $word['voice_type'],
  831. 'timbre_name' => $word['voice_name'],
  832. 'emotion' => $word['emotion'],
  833. 'emotion_type' => $word['emotion_type'],
  834. 'speed_ratio' => $word['speed_ratio'],
  835. 'loudness_ratio'=> $word['loudness_ratio'],
  836. 'emotion_scale' => $word['emotion_scale'],
  837. 'pitch' => $word['pitch']
  838. ];
  839. $word['paragraph_audio_url'] = '';
  840. // 判断生成参数是否相同,相同则直接使用已生成的音频
  841. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  842. // 如果音频存在并且参数都未改变则使用已生成的音频
  843. if (getProp($paragraph, 'paragraph_audio_url')) {
  844. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  845. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  846. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  847. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  848. // {
  849. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  850. // }
  851. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  852. }
  853. $tmp = $word;
  854. // 组装章节分句音频数据
  855. // $tmp['sequence'] = getProp($word, 'sequence');
  856. // $tmp['text'] = getProp($word, 'text');
  857. // $tmp['emotion'] = getProp($word, 'emotion');
  858. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  859. // $tmp['voice_name'] = getProp($word, 'voice_name');
  860. // $tmp['voice_type'] = getProp($word, 'voice_type');
  861. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  862. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  863. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  864. $tmp['bid'] = $bid;
  865. $tmp['version_id'] = $version_id;
  866. $tmp['cid'] = $cid;
  867. $tmp['sequence'] = $sequence;
  868. $tmp['created_at'] = date('Y-m-d H:i:s');
  869. $tmp['updated_at'] = date('Y-m-d H:i:s');
  870. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  871. $mp_chapter_paragraph_audios[] = $tmp;
  872. $complete_paragraph_sequences[] = $sequence;
  873. $sequence++;
  874. }
  875. $generate_json = json_encode($words, 256);
  876. // 判断是否有未生成字幕的段落
  877. $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();
  878. if ($no_subtitle_sequences) {
  879. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  880. }
  881. try {
  882. DB::beginTransaction();
  883. $role_info = json_encode($existed_role_info, 256);
  884. $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')]);
  885. if (!$boolen) {
  886. DB::rollBack();
  887. Utils::throwError('20003:更新角色信息失败');
  888. }
  889. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  890. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  891. if (!$count) {
  892. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  893. }else {
  894. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  895. }
  896. $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')]);
  897. if (!$boolen1) {
  898. DB::rollBack();
  899. Utils::throwError('20003:更新生成数据失败');
  900. }
  901. $id = DB::table('mp_audio_tasks')->insertGetId([
  902. 'audio_id' => getProp($chapter_audio, 'id'),
  903. 'generate_status' => '执行中',
  904. 'generate_json' => $generate_json,
  905. 'bid' => $bid,
  906. 'book_name' => getProp($chapter_audio, 'book_name'),
  907. 'version_id' => $version_id,
  908. 'version_name' => getProp($chapter_audio, 'version_name'),
  909. 'cid' => $cid,
  910. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  911. 'task_name' => $task_name,
  912. 'created_at' => date('Y-m-d H:i:s'),
  913. 'updated_at' => date('Y-m-d H:i:s')
  914. ]);
  915. if (!$id) {
  916. DB::rollBack();
  917. Utils::throwError('20003:创建任务失败');
  918. }
  919. // 删除不在段落序号范围内的其他数据
  920. if ($complete_paragraph_sequences) {
  921. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  922. }
  923. // // 删除章节分句音频数据并重新插入
  924. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  925. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  926. // if (!$boolen3) {
  927. // DB::rollBack();
  928. // Utils::throwError('20003:更新章节分句音频失败');
  929. // }
  930. } catch (\Exception $e) {
  931. DB::rollBack();
  932. Utils::throwError('20003:'.$e->getMessage());
  933. }
  934. DB::commit();
  935. // 通知火山生成音频
  936. $client = new Client(['timeout' => 300, 'verify' => false]);
  937. // 根据ID通过API通知合成音频
  938. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  939. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  940. $response = $result->getBody()->getContents();
  941. $response_arr = json_decode($response, true);
  942. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  943. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  944. Log::info('通知火山生成音频失败: '.$error_msg);
  945. Utils::throwError('20003:通知火山生成音频失败');
  946. }
  947. return true;
  948. }
  949. public function timbreList($data) {
  950. $gender = getProp($data, 'gender');
  951. $timbre_name = getProp($data, 'voice_name');
  952. $category_id = getProp($data, 'category_id');
  953. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  954. if ($gender) {
  955. $query->where('gender', $gender);
  956. }
  957. if ($timbre_name) {
  958. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  959. }
  960. if ($category_id) {
  961. $query->where(function ($query) use ($category_id) {
  962. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  963. });
  964. }
  965. $list = $query->get()->map(function ($value) {
  966. $value = (array)$value;
  967. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  968. return $value;
  969. })->toArray();
  970. return $list;
  971. }
  972. // 生成火山临时token
  973. public function setStsToken() {
  974. // ************* 配置参数 *************
  975. $method = 'GET';
  976. $service = 'sts';
  977. $host = 'open.volcengineapi.com';
  978. $region = env('VOLC_REGION');
  979. $endpoint = 'https://open.volcengineapi.com';
  980. // $endpoint = 'https://tos-cn-beijing.volces.com';
  981. $access_key = env('VOLC_AK');
  982. $secret_key = env('VOLC_SK');
  983. // 获取缓存中的token,如果没有则请求接口
  984. $token = Redis::get('volc_sts_token');
  985. if (!$token) {
  986. // 查询参数
  987. $query_parameters = [
  988. 'Action' => 'AssumeRole',
  989. 'RoleSessionName' => 'user@zw',
  990. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  991. 'Version' => '2018-01-01'
  992. ];
  993. // 生成URL编码的查询字符串
  994. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  995. // 获取签名头信息
  996. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  997. // 构建完整URL
  998. $request_url = $endpoint . '?' . $request_parameters;
  999. $client = new Client(['verify' => false]);
  1000. $response = $client->get($request_url, ['headers' => $headers]);
  1001. $response_arr = json_decode($response->getBody()->getContents(), true);
  1002. $result = [
  1003. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1004. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1005. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1006. 'Region' => env('VOLC_REGION'),
  1007. 'Endpoint' => env('VOLC_END_POINT'),
  1008. 'Bucket' => env('VOLC_BUCKET'),
  1009. ];
  1010. // 缓存token
  1011. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1012. return $result;
  1013. } else {
  1014. return json_decode($token, true);
  1015. }
  1016. // $response = $response['Response'];
  1017. // $access_key = $response['Credentials']['AccessKeyId'];
  1018. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1019. // $security_token = $response['Credentials']['SecurityToken'];
  1020. // $expiration = $response['Credentials']['Expiration'];
  1021. // dd($response_arr);
  1022. }
  1023. public function emotionGroups($data) {
  1024. $id = getProp($data, 'group_id');
  1025. $group_name = getProp($data, 'group_name');
  1026. $voice_type = getProp($data, 'voice_type');
  1027. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1028. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1029. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1030. if ($group_name) {
  1031. $query->where('group_name', 'like', "%{$group_name}%");
  1032. }
  1033. if ($id) {
  1034. $query->where('id', $id);
  1035. }
  1036. if ($voice_type) {
  1037. $query->where('voice_type', $voice_type);
  1038. }
  1039. return $query->orderBy('id')->get()->map(function ($value) {
  1040. return (array)$value;
  1041. })->toArray();
  1042. }
  1043. private function sign($key, $msg) {
  1044. return hash_hmac('sha256', $msg, $key, true);
  1045. }
  1046. // 生成签名密钥
  1047. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1048. $kDate = $this->sign($key, $dateStamp);
  1049. $kRegion = $this->sign($kDate, $regionName);
  1050. $kService = $this->sign($kRegion, $serviceName);
  1051. $kSigning = $this->sign($kService, 'request');
  1052. return $kSigning;
  1053. }
  1054. // 获取签名头信息
  1055. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1056. $contenttype = 'application/x-www-form-urlencoded';
  1057. $accept = 'application/json';
  1058. // 获取当前UTC时间
  1059. $t = new DateTime('now', new DateTimeZone('UTC'));
  1060. $xdate = $t->format('Ymd\THis\Z');
  1061. $datestamp = $t->format('Ymd');
  1062. // 1. 拼接规范请求串
  1063. $canonical_uri = '/';
  1064. $canonical_querystring = $request_parameters;
  1065. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1066. $signed_headers = 'content-type;host;x-date';
  1067. // 空请求体的SHA256哈希
  1068. $payload_hash = hash('sha256', '');
  1069. $canonical_request = implode("\n", [
  1070. $method,
  1071. $canonical_uri,
  1072. $canonical_querystring,
  1073. $canonical_headers,
  1074. $signed_headers,
  1075. $payload_hash
  1076. ]);
  1077. // 2. 拼接待签名字符串
  1078. $algorithm = 'HMAC-SHA256';
  1079. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1080. $hashed_canonical_request = hash('sha256', $canonical_request);
  1081. $string_to_sign = implode("\n", [
  1082. $algorithm,
  1083. $xdate,
  1084. $credential_scope,
  1085. $hashed_canonical_request
  1086. ]);
  1087. // 3. 计算签名
  1088. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1089. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1090. // 4. 添加签名到请求头
  1091. $authorization_header = sprintf(
  1092. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1093. $algorithm,
  1094. $access_key,
  1095. $credential_scope,
  1096. $signed_headers,
  1097. $signature
  1098. );
  1099. return [
  1100. 'Accept' => $accept,
  1101. 'Content-Type' => $contenttype,
  1102. 'X-Date' => $xdate,
  1103. 'Authorization' => $authorization_header
  1104. ];
  1105. }
  1106. // 文字合成语音(火山引擎)
  1107. public function tts($data) {
  1108. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1109. $headers = [
  1110. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1111. 'Content-Type' => 'application/json; charset=UTF-8'
  1112. ];
  1113. $post_data = [
  1114. 'app' => [
  1115. 'appid' => env('VOLC_APPID'),
  1116. 'token' => env('VOLC_TOKEN'),
  1117. 'cluster' => 'volcano_tts'
  1118. ],
  1119. 'user' => [
  1120. 'uid' => 'mp_audio'
  1121. ],
  1122. // 'audio' => [
  1123. // 'voice_type' =>
  1124. // ],
  1125. ];
  1126. }
  1127. public function scriptList($data) {
  1128. $script_id = getProp($data, 'script_id');
  1129. $script_name = getProp($data, 'script_name');
  1130. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  1131. if ($script_id) {
  1132. $query->where('id', $script_id);
  1133. }
  1134. if ($script_name) {
  1135. $query->where('script_name', 'like', "%{$script_name}%");
  1136. }
  1137. return $query->orderBy('created_at', 'desc')->paginate(12);
  1138. }
  1139. public function scripts($data) {
  1140. $script_id = getProp($data, 'script_id');
  1141. $script_name = getProp($data, 'script_name');
  1142. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('id as script_id', 'script_name');
  1143. if ($script_id) {
  1144. $query->where('id', $script_id);
  1145. }
  1146. if ($script_name) {
  1147. $query->where('script_name', 'like', "%{$script_name}%");
  1148. }
  1149. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1150. return (array)$value;
  1151. })->toArray();
  1152. }
  1153. public function scriptInfo($data) {
  1154. $script_id = getProp($data, 'script_id');
  1155. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1156. // ->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();
  1157. ->selectRaw('id as script_id, script_name')->first();
  1158. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1159. $script = (array)$script;
  1160. // 获取分集组信息
  1161. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  1162. ->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')
  1163. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  1164. $value = (array)$value;
  1165. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  1166. return (array)$value;
  1167. })->toArray();
  1168. $script['group'] = $groups;
  1169. return $script;
  1170. }
  1171. public function createScript($data) {
  1172. $script_name = getProp($data, 'script_name');
  1173. $uid = Site::getUid(); // 获取当前用户ID
  1174. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1175. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1176. $script_name .= '_'.date('YmdHis');
  1177. }
  1178. return DB::table('mp_scripts')->insertGetId([
  1179. 'script_name' => $script_name,
  1180. 'user_id' => $uid,
  1181. 'created_at' => date('Y-m-d H:i:s'),
  1182. 'updated_at' => date('Y-m-d H:i:s')
  1183. ]);
  1184. }
  1185. public function editScript($data) {
  1186. $script_id = getProp($data, 'script_id');
  1187. $script_name = getProp($data, 'script_name');
  1188. $uid = Site::getUid(); // 获取当前用户ID
  1189. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  1190. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  1191. if ($id && (int)$id !== (int)$script_id) {
  1192. $script_name .= '_'.date('YmdHis');
  1193. }
  1194. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1195. 'script_name' => $script_name,
  1196. 'updated_at' => date('Y-m-d H:i:s')
  1197. ]);
  1198. }
  1199. public function delScript($data) {
  1200. $script_id = getProp($data, 'script_id');
  1201. $uid = Site::getUid(); // 获取当前用户ID
  1202. if (!$script_id) Utils::throwError('20003:请选择剧本');
  1203. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1204. 'is_deleted' => 1,
  1205. 'updated_at' => date('Y-m-d H:i:s')
  1206. ]);
  1207. }
  1208. public function createEpisode($data) {
  1209. $script_id = getProp($data, 'script_id');
  1210. $group_name = getProp($data, 'group_name');
  1211. $remark = getProp($data, 'remark');
  1212. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  1213. $uid = Site::getUid(); // 获取当前用户ID
  1214. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  1215. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  1216. $group_name .= '_'.date('YmdHis');
  1217. }
  1218. return DB::table('mp_script_episode_group')->insertGetId([
  1219. 'script_id' => $script_id,
  1220. 'group_name' => $group_name,
  1221. 'user_id' => $uid,
  1222. 'remark' => $remark,
  1223. 'created_at' => date('Y-m-d H:i:s'),
  1224. 'updated_at' => date('Y-m-d H:i:s')
  1225. ]);
  1226. }
  1227. public function editEpisode($data) {
  1228. $group_id = getProp($data, 'group_id');
  1229. $start_episode_number = getProp($data, 'start_episode_number');
  1230. $end_episode_number = getProp($data, 'end_episode_number');
  1231. $group_name = getProp($data, 'group_name');
  1232. $uid = Site::getUid(); // 获取当前用户ID
  1233. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  1234. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  1235. if ($id && (int)$id !== (int)$group_id) {
  1236. $group_name .= '_'.date('YmdHis');
  1237. }
  1238. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1239. 'group_name' => $group_name,
  1240. 'start_episode_number' => $start_episode_number,
  1241. 'end_episode_number' => $end_episode_number,
  1242. 'updated_at' => date('Y-m-d H:i:s')
  1243. ]);
  1244. }
  1245. public function delEpisode($data) {
  1246. $group_id = getProp($data, 'group_id');
  1247. $uid = Site::getUid(); // 获取当前用户ID
  1248. if (!$group_id) Utils::throwError('20003:请选择分集');
  1249. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1250. 'is_deleted' => 1,
  1251. 'updated_at' => date('Y-m-d H:i:s')
  1252. ]);
  1253. }
  1254. /**
  1255. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1256. *
  1257. * @param array $data 包含以下参数:
  1258. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1259. * - question: 用户问题(可选)
  1260. * - model: 使用的模型(r1 或 v3,默认 v3)
  1261. * @return \Generator 返回生成器,用于流式输出
  1262. */
  1263. public function generateEpisodes($data) {
  1264. $script_id = getProp($data, 'script_id');
  1265. $group_id = getProp($data, 'group_id');
  1266. // $file = getProp($data, 'file');
  1267. $file = '';
  1268. $content = getProp($data, 'content', '');
  1269. // $bid = getProp($data, 'bid', 0);
  1270. $bid = 0;
  1271. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  1272. if (!$group) {
  1273. Utils::throwError('20003:剧本分集不存在');
  1274. }
  1275. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  1276. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  1277. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  1278. $prompt = getProp($data, 'prompt');
  1279. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  1280. $model = getProp($data, 'model');
  1281. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1282. Utils::throwError('20003:该模型不存在!');
  1283. }
  1284. // 检查是否存在重叠的剧集序号范围
  1285. $exists_groups = DB::table('mp_script_episode_group')
  1286. ->where('script_id', $script_id)
  1287. ->where('id', '<>', $group_id) // 排除当前组
  1288. ->where('is_deleted', 0)
  1289. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1290. // 检查新范围是否与现有范围重叠
  1291. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1292. // 新范围的开始在现有范围内
  1293. $q->where('start_episode_number', '<=', $start_episode_sequence)
  1294. ->where('end_episode_number', '>=', $start_episode_sequence);
  1295. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1296. // 新范围的结束在现有范围内
  1297. $q->where('start_episode_number', '<=', $end_episode_sequence)
  1298. ->where('end_episode_number', '>=', $end_episode_sequence);
  1299. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1300. // 新范围完全包含现有范围
  1301. $q->where('start_episode_number', '>=', $start_episode_sequence)
  1302. ->where('end_episode_number', '<=', $end_episode_sequence);
  1303. });
  1304. })
  1305. ->select('start_episode_number', 'end_episode_number')
  1306. ->get();
  1307. if ($exists_groups->isNotEmpty()) {
  1308. $conflict_ranges = [];
  1309. foreach ($exists_groups as $group) {
  1310. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  1311. }
  1312. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  1313. }
  1314. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1315. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1316. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1317. if ($model === 'deepseek-chat') {
  1318. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1319. $model = 'deepseek-v4-flash';
  1320. $thinkingMode = 'disabled';
  1321. } elseif ($model === 'deepseek-reasoner') {
  1322. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1323. $model = 'deepseek-v4-flash';
  1324. $thinkingMode = 'enabled';
  1325. }
  1326. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1327. if (!$script) {
  1328. Utils::throwError('20003:剧本不存在');
  1329. }
  1330. $content = getProp($group, 'content');
  1331. if (!$file && !$content && !$bid) {
  1332. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1333. }
  1334. // 提取文件内容
  1335. if ($file) {
  1336. $content = $this->extractFileContent($file);
  1337. if (!$content) {
  1338. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1339. }
  1340. } elseif ($bid) {
  1341. $content = $this->getContentByBid($bid);
  1342. if (!$content) {
  1343. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1344. }
  1345. } elseif ($content) {
  1346. $content = filterContent($content);
  1347. } elseif ($prompt) {
  1348. $content = filterContent($prompt);
  1349. } else {
  1350. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1351. }
  1352. // 构建消息
  1353. $messages = [
  1354. $this->sys_message,
  1355. [
  1356. 'role' => 'user',
  1357. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1358. ]
  1359. ];
  1360. $post_data = [
  1361. 'model' => $model,
  1362. 'messages' => $messages,
  1363. // 'max_tokens' => 8192,
  1364. 'temperature' => 0.7,
  1365. 'frequency_penalty' => 0,
  1366. 'presence_penalty' => 0,
  1367. 'thinking' => ['type' => $thinkingMode],
  1368. 'response_format' => ['type' => 'text'],
  1369. 'stream' => true
  1370. ];
  1371. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1372. // 根据模型类型选择调用方法
  1373. $fullContent = '';
  1374. $fullReasoningContent = '';
  1375. $usage = [];
  1376. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1377. // DeepSeek 官方模型使用 DeepSeek API
  1378. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1379. } else {
  1380. // 其他模型使用火山引擎API
  1381. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1382. }
  1383. // 处理流式输出
  1384. foreach ($streamGenerator as $chunk) {
  1385. if (isset($chunk['type'])) {
  1386. if ($chunk['type'] === 'done') {
  1387. // 最终结果
  1388. $fullContent = $chunk['full_content'];
  1389. $fullReasoningContent = $chunk['full_reasoning'];
  1390. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1391. } else {
  1392. // 逐块yield数据
  1393. yield $chunk;
  1394. }
  1395. }
  1396. }
  1397. dLog('deepseek')->info('完整内容: '.$fullContent);
  1398. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1399. // 处理完整内容并返回最终结果
  1400. $script_arr = [];
  1401. if ($fullContent) {
  1402. $script_arr = extractScriptContent($fullContent);
  1403. }
  1404. logDB('deepseek', 'info', '解析内容', $script_arr);
  1405. if (!$script_arr['episodes']) {
  1406. Utils::throwError('20003:未生成剧本相关信息');
  1407. // yield [
  1408. // 'type' => 'done',
  1409. // 'script' => $script_arr,
  1410. // 'msg' => '未生成剧本相关信息',
  1411. // 'answer' => $fullContent,
  1412. // 'reasoning' => $fullReasoningContent,
  1413. // 'usage' => $usage
  1414. // ];
  1415. // return ;
  1416. }
  1417. try {
  1418. DB::beginTransaction();
  1419. // // 返回前保存剧本内容
  1420. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1421. // 'content' => $content,
  1422. // 'updated_at' => date('Y-m-d H:i:s')
  1423. // ]);
  1424. // if (!$boolen) {
  1425. // Utils::throwError('20003:保存剧本内容失败');
  1426. // }
  1427. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1428. // 'start_episode_number' => $start_episode_sequence,
  1429. // 'end_episode_number' => $end_episode_sequence,
  1430. // 'updated_at' => date('Y-m-d H:i:s')
  1431. // ]);
  1432. // if (!$boolen1) {
  1433. // Utils::throwError('20003:保存分集失败');
  1434. // }
  1435. $episode_content = '';
  1436. $episodes = [];
  1437. foreach ($script_arr['episodes'] as $item) {
  1438. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  1439. // $episodes[] = [
  1440. // 'script_id' => $script_id,
  1441. // 'episode_number' => $item['episode_number'],
  1442. // 'episode_name' => $item['episode_name'],
  1443. // 'episode_content' => $item['episode_content'],
  1444. // 'created_at' => date('Y-m-d H:i:s'),
  1445. // 'updated_at' => date('Y-m-d H:i:s'),
  1446. // ];
  1447. }
  1448. if ($episode_content) {
  1449. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1450. 'episode_content' => $episode_content,
  1451. 'updated_at' => date('Y-m-d H:i:s')
  1452. ]);
  1453. if (!$boolen2) {
  1454. Utils::throwError('20003:保存分集内容失败');
  1455. }
  1456. }else {
  1457. Utils::throwError('20003:分集剧本解析失败');
  1458. }
  1459. }catch (\Exception $e) {
  1460. DB::rollBack();
  1461. Utils::throwError('20003:'.$e->getMessage());
  1462. }
  1463. DB::commit();
  1464. yield [
  1465. 'type' => 'done',
  1466. 'script' => $script_arr,
  1467. 'episode_content' => $episode_content,
  1468. 'answer' => $fullContent,
  1469. 'reasoning' => $fullReasoningContent,
  1470. 'usage' => $usage
  1471. ];
  1472. }
  1473. public function chatWithFileStream($data) {
  1474. $script_id = getProp($data, 'script_id');
  1475. $group_id = getProp($data, 'group_id');
  1476. $file = getProp($data, 'file');
  1477. $content = getProp($data, 'content', '');
  1478. $bid = getProp($data, 'bid', 0);
  1479. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1480. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1481. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  1482. $prompt = getProp($data, 'prompt');
  1483. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1484. $model = getProp($data, 'model');
  1485. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1486. Utils::throwError('20003:该模型不存在!');
  1487. }
  1488. // 检查是否存在重叠的剧集序号范围
  1489. $exists_groups = DB::table('mp_script_episode_group')
  1490. ->where('script_id', $script_id)
  1491. ->where('id', '<>', $group_id)
  1492. ->where('is_deleted', 0)
  1493. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1494. // 检查新范围是否与现有范围重叠
  1495. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1496. // 新范围的开始在现有范围内
  1497. $q->where('start_episode_number', '<=', $start_episode_sequence)
  1498. ->where('end_episode_number', '>=', $start_episode_sequence);
  1499. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1500. // 新范围的结束在现有范围内
  1501. $q->where('start_episode_number', '<=', $end_episode_sequence)
  1502. ->where('end_episode_number', '>=', $end_episode_sequence);
  1503. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1504. // 新范围完全包含现有范围
  1505. $q->where('start_episode_number', '>=', $start_episode_sequence)
  1506. ->where('end_episode_number', '<=', $end_episode_sequence);
  1507. });
  1508. })
  1509. ->select('start_episode_number', 'end_episode_number')
  1510. ->get();
  1511. if ($exists_groups->isNotEmpty()) {
  1512. $conflict_ranges = [];
  1513. foreach ($exists_groups as $group) {
  1514. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  1515. }
  1516. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  1517. }
  1518. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1519. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1520. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1521. if ($model === 'deepseek-chat') {
  1522. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1523. $model = 'deepseek-v4-flash';
  1524. $thinkingMode = 'disabled';
  1525. } elseif ($model === 'deepseek-reasoner') {
  1526. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1527. $model = 'deepseek-v4-flash';
  1528. $thinkingMode = 'enabled';
  1529. }
  1530. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1531. if (!$script) {
  1532. Utils::throwError('20003:剧本不存在');
  1533. }
  1534. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  1535. if (!$group) {
  1536. Utils::throwError('20003:剧本分集不存在');
  1537. }
  1538. if (!$file && !$content && !$bid) {
  1539. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1540. }
  1541. // 提取文件内容
  1542. if ($file) {
  1543. $content = $this->extractFileContent($file);
  1544. if (!$content) {
  1545. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1546. }
  1547. } elseif ($bid) {
  1548. $content = $this->getContentByBid($bid);
  1549. if (!$content) {
  1550. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1551. }
  1552. } elseif ($content) {
  1553. $content = filterContent($content);
  1554. } elseif ($prompt) {
  1555. $content = filterContent($prompt);
  1556. } else {
  1557. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1558. }
  1559. // 构建消息
  1560. $messages = [
  1561. [
  1562. 'role' => 'system',
  1563. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1564. 强制要求:\n
  1565. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  1566. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  1567. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  1568. 普通要求:\n
  1569. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  1570. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  1571. 示例如下:\n
  1572. ###剧本名:西昆仑
  1573. ###故事梗概
  1574. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1575. ###剧本亮点
  1576. 亮点1:绝境奇药,生死一线
  1577. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1578. 亮点2:结拜兄妹,化解尴尬
  1579. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1580. 亮点3:纤发夺命,情愫暗涌
  1581. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1582. ###人物关系
  1583. 阿雪与梁萧之间存在兄妹之情。
  1584. ###核心矛盾
  1585. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1586. ###主体列表
  1587. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1588. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1589. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1590. 阴阳球:天地异宝,能化生精气,救人于危难。
  1591. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1592. ###美术风格
  1593. 基础画风风格词:厚涂古风
  1594. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1595. ###场景列表
  1596. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  1597. [
  1598. 'role' => 'user',
  1599. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1600. ]
  1601. ];
  1602. $post_data = [
  1603. 'model' => $model,
  1604. 'messages' => $messages,
  1605. // 'max_tokens' => 8192,
  1606. 'temperature' => 0.7,
  1607. 'frequency_penalty' => 0,
  1608. 'presence_penalty' => 0,
  1609. 'thinking' => ['type' => $thinkingMode],
  1610. 'response_format' => ['type' => 'text'],
  1611. 'stream' => true
  1612. ];
  1613. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1614. // 根据模型类型选择调用方法
  1615. $fullContent = '';
  1616. $fullReasoningContent = '';
  1617. $usage = [];
  1618. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1619. // DeepSeek 官方模型使用 DeepSeek API
  1620. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1621. } else {
  1622. // 其他模型使用火山引擎API
  1623. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1624. }
  1625. // 处理流式输出
  1626. foreach ($streamGenerator as $chunk) {
  1627. if (isset($chunk['type'])) {
  1628. if ($chunk['type'] === 'done') {
  1629. // 最终结果
  1630. $fullContent = $chunk['full_content'];
  1631. $fullReasoningContent = $chunk['full_reasoning'];
  1632. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1633. } else {
  1634. // 逐块yield数据
  1635. yield $chunk;
  1636. }
  1637. }
  1638. }
  1639. dLog('deepseek')->info('完整内容: '.$fullContent);
  1640. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1641. // 处理完整内容并返回最终结果
  1642. $script_arr = [];
  1643. if ($fullContent) {
  1644. $script_arr = extractScriptContent($fullContent);
  1645. }
  1646. logDB('deepseek', 'info', '解析内容', $script_arr);
  1647. if (!$script_arr['roles']) {
  1648. Utils::throwError('20003:未生成剧本相关信息');
  1649. // yield [
  1650. // 'type' => 'done',
  1651. // 'script' => $script_arr,
  1652. // 'msg' => '未生成剧本相关信息',
  1653. // 'answer' => $fullContent,
  1654. // 'reasoning' => $fullReasoningContent,
  1655. // 'usage' => $usage
  1656. // ];
  1657. }
  1658. try {
  1659. DB::beginTransaction();
  1660. // // 返回前保存剧本内容
  1661. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1662. // 'content' => $content,
  1663. // 'status' => '解析完成',
  1664. // 'updated_at' => date('Y-m-d H:i:s')
  1665. // ]);
  1666. // if (!$boolen) {
  1667. // Utils::throwError('20003:保存剧本内容失败');
  1668. // }
  1669. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1670. 'start_episode_number' => $start_episode_sequence,
  1671. 'end_episode_number' => $end_episode_sequence,
  1672. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1673. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1674. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1675. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1676. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1677. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1678. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1679. 'status' => '解析完成',
  1680. 'content' => $content,
  1681. 'updated_at' => date('Y-m-d H:i:s')
  1682. ]);
  1683. if (!$boolen1) {
  1684. Utils::throwError('20003:保存分集失败');
  1685. }
  1686. // $episodes = [];
  1687. // foreach ($script_arr['episodes'] as $item) {
  1688. // $episodes[] = [
  1689. // 'script_id' => $script_id,
  1690. // 'episode_number' => $item['episode_number'],
  1691. // 'episode_name' => $item['episode_name'],
  1692. // 'episode_content' => $item['episode_content'],
  1693. // 'created_at' => date('Y-m-d H:i:s'),
  1694. // 'updated_at' => date('Y-m-d H:i:s'),
  1695. // ];
  1696. // }
  1697. // if ($episodes) {
  1698. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1699. // if (!$boolen2) {
  1700. // Utils::throwError('20003:保存分集内容失败');
  1701. // }
  1702. // }else {
  1703. // Utils::throwError('20003:分集剧本解析失败');
  1704. // }
  1705. }catch (\Exception $e) {
  1706. DB::rollBack();
  1707. Utils::throwError('20003:'.$e->getMessage());
  1708. }
  1709. DB::commit();
  1710. yield [
  1711. 'type' => 'done',
  1712. 'script' => $script_arr,
  1713. 'answer' => $fullContent,
  1714. 'reasoning' => $fullReasoningContent,
  1715. 'usage' => $usage
  1716. ];
  1717. }
  1718. /**
  1719. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1720. *
  1721. * @param array $data 包含以下参数:
  1722. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1723. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1724. * - model: 使用的模型(r1 或 v3,默认 v3)
  1725. * @return array
  1726. */
  1727. public function chatWithFile($data) {
  1728. $script_id = getProp($data, 'script_id');
  1729. $file = getProp($data, 'file');
  1730. $content = getProp($data, 'content', '');
  1731. $bid = getProp($data, 'bid', 0);
  1732. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1733. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1734. $prompt = getProp($data, 'prompt');
  1735. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1736. // 处理文本模型
  1737. $model = getProp($data, 'model');
  1738. if (!$model) {
  1739. // 用户没有输入,使用默认值
  1740. $model = 'doubao-seed-2-0-mini-260215';
  1741. }
  1742. // 验证模型是否在可用模型表中
  1743. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1744. $model = 'doubao-seed-2-0-mini-260215';
  1745. }
  1746. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1747. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1748. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1749. if ($model === 'deepseek-chat') {
  1750. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1751. $model = 'deepseek-v4-flash';
  1752. $thinkingMode = 'disabled';
  1753. } elseif ($model === 'deepseek-reasoner') {
  1754. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1755. $model = 'deepseek-v4-flash';
  1756. $thinkingMode = 'enabled';
  1757. }
  1758. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1759. if (!$script) {
  1760. Utils::throwError('20003:剧本不存在');
  1761. }
  1762. if (!$file && !$content && !$bid) {
  1763. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1764. }
  1765. // 提取文件内容
  1766. if ($file) {
  1767. $content = $this->extractFileContent($file);
  1768. if (!$content) {
  1769. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1770. }
  1771. } elseif ($bid) {
  1772. $content = $this->getContentByBid($bid);
  1773. if (!$content) {
  1774. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1775. }
  1776. } elseif ($content) {
  1777. $content = filterContent($content);
  1778. } elseif ($prompt) {
  1779. $content = filterContent($prompt);
  1780. } else {
  1781. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1782. }
  1783. // 构建消息
  1784. $messages = [
  1785. $this->sys_message,
  1786. [
  1787. 'role' => 'user',
  1788. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1789. ]
  1790. ];
  1791. $post_data = [
  1792. 'model' => $model,
  1793. 'messages' => $messages,
  1794. // 'max_tokens' => 8192,
  1795. 'temperature' => 0.7,
  1796. 'frequency_penalty' => 0,
  1797. 'presence_penalty' => 0,
  1798. 'thinking' => ['type' => $thinkingMode],
  1799. 'response_format' => ['type' => 'text'],
  1800. 'stream' => false
  1801. ];
  1802. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1803. // 根据模型类型选择调用方法
  1804. $fullContent = '';
  1805. $usage = [];
  1806. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1807. // DeepSeek 官方模型使用 DeepSeek API
  1808. $chatResult = $this->chatOnly($post_data);
  1809. } else {
  1810. // 其他模型使用火山引擎API
  1811. $chatResult = $this->volcEngineChatCompletion($post_data);
  1812. }
  1813. if (is_array($chatResult)) {
  1814. $fullContent = $chatResult['fullContent'];
  1815. $usage = $chatResult['usage'];
  1816. }
  1817. $script_arr = [];
  1818. // 处理结果
  1819. if ($fullContent) {
  1820. $script_arr = extractScriptContent($fullContent);
  1821. }
  1822. // 返回前保存剧本内容
  1823. DB::table('mp_scripts')->where('id', $script_id)->update([
  1824. 'content' => $content,
  1825. 'updated_at' => date('Y-m-d H:i:s')
  1826. ]);
  1827. return [
  1828. 'script' => $script_arr,
  1829. 'answer' => $fullContent,
  1830. 'usage' => $usage
  1831. ];
  1832. }
  1833. public function getEpisodeContent($data) {
  1834. $group_id = getProp($data, 'group_id');
  1835. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  1836. }
  1837. public function saveEpisodeContent($data) {
  1838. $group_id = getProp($data, 'group_id');
  1839. $episode_content = getProp($data, 'episode_content');
  1840. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1841. 'content' => $episode_content,
  1842. 'updated_at' => date('Y-m-d H:i:s')
  1843. ]);
  1844. $script_arr =getProp($data, 'script', []);
  1845. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1846. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1847. $script_id = getProp($data, 'script_id');
  1848. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1849. try {
  1850. DB::beginTransaction();
  1851. $update_data = [
  1852. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1853. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1854. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1855. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1856. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1857. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1858. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1859. 'status' => 3,
  1860. 'start_episode_sequence' => $start_episode_sequence,
  1861. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1862. 'episode_num' => count($script_arr['episodes']),
  1863. 'updated_at' => date('Y-m-d H:i:s')
  1864. ];
  1865. // 保存剧本内容
  1866. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1867. if (!$boolen) {
  1868. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1869. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  1870. Utils::throwError('20003:剧本内容保存失败');
  1871. }
  1872. // 保存分集内容
  1873. // 删除历史分集内容
  1874. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1875. $episodes = [];
  1876. $sequence = 1;
  1877. foreach ($script_arr['episodes'] as $episode) {
  1878. $segment_number = 1;
  1879. foreach($episode['segments'] as $segment) {
  1880. $episodes[] = [
  1881. 'script_id' => $script_id,
  1882. 'episode_number' => $episode['episode_number'],
  1883. 'title' => $episode['title'],
  1884. // 'content' => $episode['content'],
  1885. 'content' => '',
  1886. 'segment_number' => $segment_number,
  1887. 'segment_content' => $segment['segment_content'],
  1888. 'sequence' => $sequence,
  1889. 'created_at' => date('Y-m-d H:i:s'),
  1890. 'updated_at' => date('Y-m-d H:i:s')
  1891. ];
  1892. $sequence++;
  1893. $segment_number++;
  1894. }
  1895. }
  1896. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1897. if (!$boolen2) {
  1898. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1899. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  1900. Utils::throwError('20003:分集内容保存失败');
  1901. }
  1902. } catch (\Exception $e) {
  1903. DB::rollBack();
  1904. Utils::throwError('20003:'.$e->getMessage());
  1905. }
  1906. DB::commit();
  1907. return true;
  1908. }
  1909. public function getBookContent($data) {
  1910. $bid = getProp($data, 'bid');
  1911. $start_sequence = getProp($data, 'start_sequence');
  1912. $end_sequence = getProp($data, 'end_sequence');
  1913. $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])
  1914. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  1915. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  1916. return $return_content;
  1917. }
  1918. public function exportScript($data) {
  1919. $filename = getProp($data, 'filename');
  1920. $script_id = getProp($data, 'script_id');
  1921. $group_id = getProp($data, 'group_id');
  1922. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1923. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  1924. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1925. $script = (array)$script;
  1926. // 获取分集组信息
  1927. if ($group_id) {
  1928. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  1929. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  1930. ->get()->map(function($value) {
  1931. return (array)$value;
  1932. })->toArray();
  1933. }else {
  1934. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  1935. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  1936. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  1937. return (array)$value;
  1938. })->toArray();
  1939. }
  1940. if (!$groups) Utils::throwError('20003:分集不存在');
  1941. $script['group'] = $groups;
  1942. $export_type = getProp($data, 'export_type', 'txt');
  1943. // 生成文件名
  1944. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  1945. // 根据导出类型生成不同格式的文件
  1946. switch ($export_type) {
  1947. case 'txt':
  1948. return $this->exportScriptAsTxt($script, $filename);
  1949. case 'pdf':
  1950. return $this->exportScriptAsPdf($script, $filename);
  1951. default:
  1952. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  1953. }
  1954. }
  1955. /**
  1956. * 导出剧本为TXT格式
  1957. */
  1958. private function exportScriptAsTxt($script, $filename) {
  1959. // 构建TXT内容
  1960. $content = $this->buildScriptContent($script);
  1961. // 设置响应头,直接下载
  1962. header('Content-Type: text/plain; charset=utf-8');
  1963. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  1964. header('Content-Length: ' . strlen($content));
  1965. // 输出内容并结束
  1966. echo $content;
  1967. exit();
  1968. }
  1969. /**
  1970. * 导出剧本为PDF格式
  1971. */
  1972. private function exportScriptAsPdf($script, $filename) {
  1973. // 使用HTML转PDF的方式来更好地支持中文
  1974. $htmlContent = $this->buildScriptHtmlForPdf($script);
  1975. // 创建PDF实例
  1976. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1977. // 设置文档信息
  1978. $pdf->SetCreator('剧本导出系统');
  1979. $pdf->SetAuthor('系统');
  1980. $pdf->SetTitle($script['script_name']);
  1981. $pdf->SetSubject('剧本导出');
  1982. // 设置边距
  1983. $pdf->SetMargins(15, 15, 15);
  1984. $pdf->SetAutoPageBreak(TRUE, 15);
  1985. // 添加页面
  1986. $pdf->AddPage();
  1987. // 注册并使用 simsun.ttf 字体
  1988. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  1989. // 使用HTML内容生成PDF
  1990. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  1991. // 直接输出PDF文件供下载
  1992. header('Content-Type: application/pdf');
  1993. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  1994. // 直接输出PDF内容
  1995. $pdf->Output($filename . '.pdf', 'D');
  1996. exit();
  1997. }
  1998. /**
  1999. * 构建用于PDF的HTML内容
  2000. */
  2001. private function buildScriptHtmlForPdf($script) {
  2002. $html = '<style>
  2003. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2004. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2005. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2006. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2007. .info { margin-bottom: 8px; }
  2008. .episode { margin-bottom: 20px; page-break-inside: avoid; }
  2009. .segment { margin-bottom: 10px; margin-left: 20px; }
  2010. </style>';
  2011. // 标题
  2012. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2013. // 剧本简介
  2014. if (!empty($script['intro'])) {
  2015. $html .= '<h2>剧本简介</h2>';
  2016. $html .= '<p>' . nl2br(htmlspecialchars($script['intro'])) . '</p>';
  2017. }
  2018. // 亮点
  2019. if (!empty($script['highlights'])) {
  2020. $html .= '<h2>亮点</h2>';
  2021. $html .= '<p>' . nl2br(htmlspecialchars($script['highlights'])) . '</p>';
  2022. }
  2023. // 核心矛盾
  2024. if (!empty($script['core_contradiction'])) {
  2025. $html .= '<h2>核心矛盾</h2>';
  2026. $html .= '<p>' . nl2br(htmlspecialchars($script['core_contradiction'])) . '</p>';
  2027. }
  2028. // 艺术风格
  2029. if (!empty($script['art_style'])) {
  2030. $html .= '<h2>艺术风格</h2>';
  2031. $html .= '<p>' . nl2br(htmlspecialchars($script['art_style'])) . '</p>';
  2032. }
  2033. // 角色列表
  2034. if (!empty($script['roles']) && is_array($script['roles'])) {
  2035. $html .= '<h2>角色列表</h2>';
  2036. $html .= '<ul>';
  2037. foreach ($script['roles'] as $role) {
  2038. if (is_array($role) || is_object($role)) {
  2039. $html .= '<li>' . htmlspecialchars(getProp($role, 'role', '')) . ':' . htmlspecialchars(getProp($role, 'description', '')) . '</li>';
  2040. } else {
  2041. $html .= '<li>' . htmlspecialchars($role) . '</li>';
  2042. }
  2043. }
  2044. $html .= '</ul>';
  2045. }
  2046. // 角色关系
  2047. if (!empty($script['role_relationship'])) {
  2048. $html .= '<h2>角色关系</h2>';
  2049. $html .= '<p>' . nl2br(htmlspecialchars($script['role_relationship'])) . '</p>';
  2050. }
  2051. // 场景列表
  2052. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  2053. $html .= '<h2>场景列表</h2>';
  2054. $html .= '<ul>';
  2055. foreach ($script['scenes'] as $scene) {
  2056. if (is_array($scene) || is_object($scene)) {
  2057. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene', '')) . ':' . htmlspecialchars(getProp($scene, 'description', '')) . '</li>';
  2058. } else {
  2059. $html .= '<li>' . htmlspecialchars($scene) . '</li>';
  2060. }
  2061. }
  2062. $html .= '</ul>';
  2063. }
  2064. // 分集内容
  2065. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  2066. $html .= '<h2>分集内容</h2>';
  2067. foreach ($script['episodes'] as $episode) {
  2068. $html .= '<div class="episode">';
  2069. $html .= '<h3>第' . htmlspecialchars($episode['episode_number']) . '集';
  2070. if (!empty($episode['episode_name'])) {
  2071. $html .= ':' . htmlspecialchars($episode['episode_name']);
  2072. }
  2073. $html .= '</h3>';
  2074. // 处理分集内容
  2075. if (!empty($episode['episode_content'])) {
  2076. $html .= '<div class="segment">';
  2077. // 去掉第一行(标题行)
  2078. $content = $episode['episode_content'];
  2079. $lines = explode("\n", $content);
  2080. if (count($lines) > 1) {
  2081. array_shift($lines); // 移除第一行
  2082. $content = implode("\n", $lines);
  2083. } else {
  2084. $content = ''; // 如果只有一行,则清空
  2085. }
  2086. $html .= nl2br(htmlspecialchars($content));
  2087. $html .= '</div>';
  2088. }
  2089. $html .= '</div>';
  2090. }
  2091. }
  2092. return $html;
  2093. }
  2094. /**
  2095. * 构建PDF内容
  2096. */
  2097. private function buildPdfContent($pdf, $script) {
  2098. // 标题
  2099. $pdf->SetFont('dejavusans', 'B', 18);
  2100. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2101. $pdf->Ln(5);
  2102. // 基本信息
  2103. $pdf->SetFont('dejavusans', '', 12);
  2104. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2105. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2106. $pdf->Ln(5);
  2107. // 剧本简介
  2108. if (!empty($script['intro'])) {
  2109. $pdf->SetFont('dejavusans', 'B', 14);
  2110. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2111. $pdf->SetFont('dejavusans', '', 12);
  2112. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2113. $pdf->Ln(3);
  2114. }
  2115. // 亮点
  2116. if (!empty($script['highlights'])) {
  2117. $pdf->SetFont('dejavusans', 'B', 14);
  2118. $pdf->Cell(0, 10, '亮点', 0, 1);
  2119. $pdf->SetFont('dejavusans', '', 12);
  2120. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2121. $pdf->Ln(3);
  2122. }
  2123. // 核心矛盾
  2124. if (!empty($script['core_contradiction'])) {
  2125. $pdf->SetFont('dejavusans', 'B', 14);
  2126. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2127. $pdf->SetFont('dejavusans', '', 12);
  2128. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2129. $pdf->Ln(3);
  2130. }
  2131. // 艺术风格
  2132. if (!empty($script['art_style'])) {
  2133. $pdf->SetFont('dejavusans', 'B', 14);
  2134. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2135. $pdf->SetFont('dejavusans', '', 12);
  2136. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2137. $pdf->Ln(3);
  2138. }
  2139. // 备注
  2140. if (!empty($script['remark'])) {
  2141. $pdf->SetFont('dejavusans', 'B', 14);
  2142. $pdf->Cell(0, 10, '备注', 0, 1);
  2143. $pdf->SetFont('dejavusans', '', 12);
  2144. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2145. $pdf->Ln(3);
  2146. }
  2147. // 角色列表
  2148. if (!empty($script['roles']) && is_array($script['roles'])) {
  2149. $pdf->SetFont('dejavusans', 'B', 14);
  2150. $pdf->Cell(0, 10, '角色列表', 0, 1);
  2151. $pdf->SetFont('dejavusans', '', 12);
  2152. foreach ($script['roles'] as $index => $role) {
  2153. if (is_array($role) || is_object($role)) {
  2154. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  2155. } else {
  2156. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  2157. }
  2158. }
  2159. $pdf->Ln(3);
  2160. }
  2161. // 角色关系
  2162. if (!empty($script['role_relationship'])) {
  2163. $pdf->SetFont('dejavusans', 'B', 14);
  2164. $pdf->Cell(0, 10, '角色关系', 0, 1);
  2165. $pdf->SetFont('dejavusans', '', 12);
  2166. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  2167. $pdf->Ln(3);
  2168. }
  2169. // 场景列表
  2170. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  2171. $pdf->SetFont('dejavusans', 'B', 14);
  2172. $pdf->Cell(0, 10, '场景列表', 0, 1);
  2173. $pdf->SetFont('dejavusans', '', 12);
  2174. foreach ($script['scenes'] as $index => $scene) {
  2175. if (is_array($scene) || is_object($scene)) {
  2176. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  2177. } else {
  2178. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  2179. }
  2180. }
  2181. $pdf->Ln(5);
  2182. }
  2183. // 分集内容
  2184. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  2185. $pdf->SetFont('dejavusans', 'B', 16);
  2186. $pdf->Cell(0, 12, '分集内容', 0, 1);
  2187. $pdf->Ln(3);
  2188. foreach ($script['episodes'] as $episode) {
  2189. // 检查是否需要新页面
  2190. if ($pdf->GetY() > 250) {
  2191. $pdf->AddPage();
  2192. }
  2193. $pdf->SetFont('dejavusans', 'B', 14);
  2194. $episodeTitle = '第' . $episode['episode_number'] . '集';
  2195. if (!empty($episode['title'])) {
  2196. $episodeTitle .= ':' . $episode['title'];
  2197. }
  2198. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  2199. // 处理分段内容
  2200. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  2201. $pdf->SetFont('dejavusans', '', 12);
  2202. foreach ($episode['segments'] as $segment) {
  2203. if (!empty($segment['segment_content'])) {
  2204. // 如果有分段编号,显示分段标题
  2205. if (!empty($segment['segment_number'])) {
  2206. $pdf->SetFont('dejavusans', 'B', 12);
  2207. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  2208. $pdf->SetFont('dejavusans', '', 12);
  2209. }
  2210. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  2211. $pdf->Ln(2);
  2212. }
  2213. }
  2214. }
  2215. $pdf->Ln(5);
  2216. }
  2217. }
  2218. }
  2219. /**
  2220. * 构建剧本文本内容
  2221. */
  2222. private function buildScriptContent($script) {
  2223. $content = '';
  2224. $groups = $script['group'];
  2225. $groups = (array)$groups;
  2226. foreach ($groups as $group) {
  2227. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  2228. // 剧本基本信息
  2229. if (!empty($group['intro'])) {
  2230. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  2231. }
  2232. if (!empty($group['highlights'])) {
  2233. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  2234. }
  2235. if (!empty($group['role_relationship'])) {
  2236. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  2237. }
  2238. if (!empty($group['core_contradiction'])) {
  2239. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  2240. }
  2241. if (!empty($group['roles']) && is_array($group['roles'])) {
  2242. $content .= "###主体列表\n";
  2243. foreach ($group['roles'] as $role) {
  2244. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  2245. }
  2246. $content .= "\n\n";
  2247. }
  2248. if (!empty($group['art_style'])) {
  2249. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  2250. }
  2251. // 场景信息
  2252. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2253. $content .= "###场景列表\n";
  2254. foreach ($group['scenes'] as $scene) {
  2255. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  2256. }
  2257. $content .= "\n\n";
  2258. }
  2259. // 分集内容
  2260. if (!empty($group['episode_content'])) {
  2261. $content .= "###分集剧本\n";
  2262. $content .= $group['episode_content'];
  2263. // foreach ($script['episodes'] as $episode) {
  2264. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  2265. // // if (!empty($episode['episode_name'])) {
  2266. // // $content .= ":" . $episode['episode_name'];
  2267. // // }
  2268. // // $content .= "\n";
  2269. // $content .= $episode['episode_content'] . "\n\n";
  2270. // }
  2271. }
  2272. }
  2273. return $content;
  2274. }
  2275. /**
  2276. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2277. *
  2278. * @param array $data 包含以下参数:
  2279. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2280. * - question: 用户问题(可选)
  2281. * - model: 使用的模型(r1 或 v3,默认 v3)
  2282. * @return \Generator 返回生成器,用于流式输出
  2283. */
  2284. public function addChat($data) {
  2285. $uid = Site::getUid();
  2286. $anime_id = getProp($data, 'anime_id');
  2287. if (!$anime_id) Utils::throwError('20003:请选择对话');
  2288. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2289. if (!$anime) Utils::throwError('20003:对话不存在');
  2290. $file = getProp($data, 'file');
  2291. $content = getProp($data, 'content', '');
  2292. $bid = getProp($data, 'bid', 0);
  2293. $script_id = getProp($data, 'script_id', 0);
  2294. $prompt = getProp($data, 'prompt');
  2295. // 处理文本模型
  2296. $model = getProp($data, 'model');
  2297. if (!$model) {
  2298. // 用户没有输入,从anime表获取
  2299. $model = getProp($anime, 'model');
  2300. if (!$model) {
  2301. // anime表也没有,使用默认值
  2302. $model = 'doubao-seed-2-0-mini-260215';
  2303. }
  2304. }
  2305. // 验证模型是否在可用模型表中
  2306. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2307. $model = 'doubao-seed-2-0-mini-260215';
  2308. }
  2309. $is_multi = getProp($anime, 'is_multi');
  2310. $is_single = (int)$is_multi !== 1;
  2311. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2312. // if (!$file && !$content && !$bid) {
  2313. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2314. // }
  2315. // 提取文件内容
  2316. if ($file) {
  2317. $content = $this->extractFileContent($file);
  2318. if (!$content) {
  2319. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2320. }
  2321. } elseif ($script_id) {
  2322. $content = $this->getContentByScriptId($script_id);
  2323. if (!$content) {
  2324. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2325. }
  2326. } elseif ($bid) {
  2327. $content = $this->getContentByBid($bid);
  2328. if (!$content) {
  2329. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2330. }
  2331. } elseif ($content) {
  2332. $content = filterContent($content);
  2333. } else {
  2334. $content = getProp($anime, 'content');
  2335. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2336. $need_generate_content = true;
  2337. }
  2338. }
  2339. // 美术风格
  2340. $input_art_style = getProp($data, 'art_style');
  2341. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2342. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2343. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2344. 中年女:邻居阿姨
  2345. 老年男:幽默大爷
  2346. 老年女:婆婆
  2347. 萌娃:奶气萌娃";
  2348. // 判断是否需要生成原文内容
  2349. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2350. // 如果需要生成原文内容,添加额外的要求
  2351. $content_generation_requirement = $need_generate_content
  2352. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2353. : "";
  2354. $systemPrompt = $is_single
  2355. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2356. 强制要求:
  2357. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2358. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2359. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2360. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2361. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2362. 普通要求:
  2363. 1.剧集标题必须与文档内容高度相关,剧集序号是1。
  2364. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2365. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2366. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2367. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2368. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2369. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2370. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2371. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2372. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2373. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2374. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2375. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2376. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2377. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2378. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2379. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2380. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2381. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2382. 示例如下:\n
  2383. ###剧本名:西昆仑
  2384. ###故事梗概
  2385. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2386. ###剧本亮点
  2387. 亮点1:绝境奇药,生死一线
  2388. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2389. 亮点2:结拜兄妹,化解尴尬
  2390. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2391. 亮点3:纤发夺命,情愫暗涌
  2392. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2393. ###人物关系
  2394. 阿雪与梁萧之间存在兄妹之情。
  2395. ###核心矛盾
  2396. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2397. ###主体列表
  2398. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2399. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2400. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2401. 阴阳球:天地异宝,能化生精气,救人于危难。
  2402. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2403. ###美术风格
  2404. 基础画风风格词:厚涂古风
  2405. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2406. ###场景列表
  2407. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2408. ###分镜剧本
  2409. ##第1幕:徐家老旧厨房 白天 室内
  2410. 分镜1
  2411. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2412. 场景:徐家老旧厨房
  2413. 构图设计:全景,低角度仰视
  2414. 运镜调度:手持拍摄
  2415. 配音角色:旁白
  2416. 出镜角色:许芸-校服装、徐母
  2417. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2418. 画面类型:普通画面
  2419. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2420. 分镜2
  2421. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2422. 场景:徐家老旧厨房
  2423. 构图设计:近景,徐母面部特写
  2424. 运镜调度:固定镜头
  2425. 配音角色:徐母
  2426. 出镜角色:徐母
  2427. 台词内容:问我夜不归宿死哪儿去了。
  2428. 画面类型:对口型
  2429. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2430. ##第2幕:徐家简陋客厅 黄昏 室内
  2431. 分镜3
  2432. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2433. 场景:徐家简陋客厅
  2434. 构图设计:全景,景深虚化
  2435. 运镜调度:固定镜头
  2436. 配音角色:旁白
  2437. 出镜角色:无
  2438. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2439. 画面类型:普通画面
  2440. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2441. 分镜4
  2442. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2443. 场景:徐家简陋客厅
  2444. 构图设计:特写,火车票
  2445. 运镜调度:固定镜头
  2446. 配音角色:旁白
  2447. 出镜角色:无
  2448. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2449. 画面类型:普通画面
  2450. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  2451. "
  2452. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2453. 强制要求:\n
  2454. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2455. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2456. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2457. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2458. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2459. 普通要求:\n
  2460. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2461. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  2462. 示例如下:\n
  2463. ###剧本名:西昆仑
  2464. ###故事梗概
  2465. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2466. ###剧本亮点
  2467. 亮点1:绝境奇药,生死一线
  2468. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2469. 亮点2:结拜兄妹,化解尴尬
  2470. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2471. 亮点3:纤发夺命,情愫暗涌
  2472. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2473. ###人物关系
  2474. 阿雪与梁萧之间存在兄妹之情。
  2475. ###核心矛盾
  2476. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2477. ###主体列表
  2478. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2479. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2480. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2481. 阴阳球:天地异宝,能化生精气,救人于危难。
  2482. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2483. ###美术风格
  2484. 基础画风风格词:厚涂古风
  2485. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2486. ###场景列表
  2487. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。";
  2488. // 构建消息
  2489. $messages = [
  2490. [
  2491. 'role' => 'system',
  2492. 'content' => $systemPrompt
  2493. ],
  2494. [
  2495. 'role' => 'user',
  2496. 'content' => "以下是文档内容:
  2497. {$content}
  2498. 用户问题:
  2499. {$question}"
  2500. ]
  2501. ];
  2502. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2503. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2504. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2505. if ($model === 'deepseek-chat') {
  2506. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2507. $model = 'deepseek-v4-flash';
  2508. $thinkingMode = 'disabled';
  2509. } elseif ($model === 'deepseek-reasoner') {
  2510. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2511. $model = 'deepseek-v4-flash';
  2512. $thinkingMode = 'enabled';
  2513. }
  2514. $post_data = [
  2515. 'model' => $model,
  2516. 'messages' => $messages,
  2517. // 'max_tokens' => 8192,
  2518. 'temperature' => 0.7,
  2519. 'frequency_penalty' => 0,
  2520. 'presence_penalty' => 0,
  2521. 'response_format' => ['type' => 'text'],
  2522. 'thinking' => ['type'=>$thinkingMode],
  2523. 'stream' => true // 启用流式输出
  2524. ];
  2525. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2526. // 根据模型类型选择调用方法
  2527. $fullContent = '';
  2528. $fullReasoningContent = '';
  2529. $usage = [];
  2530. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2531. // DeepSeek 官方模型使用 DeepSeek API
  2532. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2533. } else {
  2534. // 其他模型使用火山引擎API
  2535. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2536. }
  2537. // 处理流式输出
  2538. if (!is_iterable($streamGenerator)) {
  2539. dLog('deepseek')->error('addChat流式生成器无效', ['generator_type' => gettype($streamGenerator)]);
  2540. Utils::throwError('20003:接口返回数据异常,请重新请求');
  2541. }
  2542. foreach ($streamGenerator as $chunk) {
  2543. if (isset($chunk['type'])) {
  2544. if ($chunk['type'] === 'done') {
  2545. // 最终结果
  2546. $fullContent = $chunk['full_content'];
  2547. $fullReasoningContent = $chunk['full_reasoning'];
  2548. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2549. } else {
  2550. // 逐块yield数据
  2551. yield $chunk;
  2552. }
  2553. }
  2554. }
  2555. dLog('deepseek')->info('完整内容: '.$fullContent);
  2556. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  2557. // 处理完整内容并返回最终结果
  2558. $script_arr = [];
  2559. if ($fullContent) {
  2560. $script_arr = handleScriptContent($fullContent);
  2561. dLog('deepseek')->info('解析内容', $script_arr);
  2562. logDB('deepseek', 'info', '解析内容', $script_arr);
  2563. }
  2564. if (empty($script_arr['roles'])) {
  2565. // 未生成剧本相关内容,保存对话记录并返回提示
  2566. dLog('deepseek')->info('未生成剧本相关的内容');
  2567. try {
  2568. DB::beginTransaction();
  2569. $now = date('Y-m-d H:i:s');
  2570. // 保存对话记录
  2571. $records = [
  2572. [
  2573. 'uid' => $uid,
  2574. 'anime_id' => $anime_id,
  2575. 'sequence' => 0,
  2576. 'role' => 'user',
  2577. 'content' => "用户问题:\n
  2578. {$prompt}\n\n
  2579. 以下是文档内容:\n
  2580. {$content}",
  2581. 'created_at' => $now,
  2582. 'updated_at' => $now
  2583. ],
  2584. [
  2585. 'uid' => $uid,
  2586. 'anime_id' => $anime_id,
  2587. 'sequence' => 0,
  2588. 'role' => 'assistant',
  2589. 'content' => $fullContent,
  2590. 'created_at' => $now,
  2591. 'updated_at' => $now
  2592. ]
  2593. ];
  2594. DB::table('mp_anime_records')->insert($records);
  2595. DB::commit();
  2596. } catch (\Exception $e) {
  2597. DB::rollBack();
  2598. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2599. }
  2600. yield [
  2601. 'type' => 'done',
  2602. 'script' => [],
  2603. 'episode' => [],
  2604. 'answer' => $fullContent,
  2605. 'reasoning' => $fullReasoningContent,
  2606. 'usage' => $usage,
  2607. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  2608. ];
  2609. return;
  2610. }
  2611. // 如果需要生成原文内容,从script_arr中提取
  2612. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  2613. $content = $script_arr['content'];
  2614. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  2615. if (!$content) {
  2616. yield [
  2617. 'type' => 'done',
  2618. 'script' => [],
  2619. 'episode' => [],
  2620. 'answer' => $fullContent,
  2621. 'reasoning' => $fullReasoningContent,
  2622. 'usage' => $usage,
  2623. 'error' => '未生成剧本内容,请调整提示词再试'
  2624. ];
  2625. return;
  2626. }
  2627. }
  2628. // 替换美术风格
  2629. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2630. if ($mappedArtStyle !== '') {
  2631. $script_arr['art_style'] = $mappedArtStyle;
  2632. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2633. }
  2634. // 新建动漫
  2635. $anime_name = getProp($script_arr, 'script_name');
  2636. if (!$anime_name) {
  2637. // 未识别到剧本名,保存对话记录并返回提示
  2638. dLog('deepseek')->info('未能识别到剧本名称');
  2639. try {
  2640. DB::beginTransaction();
  2641. $now = date('Y-m-d H:i:s');
  2642. // 保存对话记录
  2643. $records = [
  2644. [
  2645. 'uid' => $uid,
  2646. 'anime_id' => $anime_id,
  2647. 'sequence' => 0,
  2648. 'role' => 'user',
  2649. 'content' => "用户问题:\n
  2650. {$prompt}\n\n
  2651. 以下是文档内容:\n
  2652. {$content}",
  2653. 'created_at' => $now,
  2654. 'updated_at' => $now
  2655. ],
  2656. [
  2657. 'uid' => $uid,
  2658. 'anime_id' => $anime_id,
  2659. 'sequence' => 0,
  2660. 'role' => 'assistant',
  2661. 'content' => $fullContent,
  2662. 'created_at' => $now,
  2663. 'updated_at' => $now
  2664. ]
  2665. ];
  2666. DB::table('mp_anime_records')->insert($records);
  2667. DB::commit();
  2668. } catch (\Exception $e) {
  2669. DB::rollBack();
  2670. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2671. }
  2672. yield [
  2673. 'type' => 'done',
  2674. 'script' => [],
  2675. 'episode' => [],
  2676. 'answer' => $fullContent,
  2677. 'reasoning' => $fullReasoningContent,
  2678. 'usage' => $usage,
  2679. 'error' => '未能识别到剧本名称,请调整提示词再试'
  2680. ];
  2681. return;
  2682. }
  2683. // 确认对话名称唯一性
  2684. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  2685. $anime_name = $anime_name . '_' . date('YmdHis');
  2686. }
  2687. $table_data = [
  2688. 'user_id' => $uid,
  2689. 'anime_name' => $anime_name,
  2690. 'model' => $model,
  2691. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2692. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2693. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2694. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2695. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2696. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2697. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2698. 'status' => '解析完成',
  2699. 'content' => $content,
  2700. 'is_multi' => $is_multi,
  2701. 'generate_status' => '待执行',
  2702. 'updated_at' => date('Y-m-d H:i:s')
  2703. ];
  2704. $single_episode = [];
  2705. try {
  2706. DB::beginTransaction();
  2707. $now = date('Y-m-d H:i:s');
  2708. // 更新动漫大纲
  2709. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2710. if (!$boolen) {
  2711. dLog('deepseek')->info('动漫保存失败', $table_data);
  2712. Utils::throwError('20003:动漫保存失败');
  2713. }
  2714. // 保存对话记录
  2715. $records = [
  2716. [
  2717. 'uid' => $uid,
  2718. 'anime_id' => $anime_id,
  2719. 'sequence' => 0,
  2720. 'role' => 'user',
  2721. 'content' => "用户问题:\n
  2722. {$prompt}\n\n
  2723. 以下是文档内容:\n
  2724. {$content}",
  2725. 'created_at' => date('Y-m-d H:i:s'),
  2726. 'updated_at' => date('Y-m-d H:i:s')
  2727. ],
  2728. [
  2729. 'uid' => $uid,
  2730. 'anime_id' => $anime_id,
  2731. 'sequence' => 0,
  2732. 'role' => 'assistant',
  2733. 'content' => $fullContent,
  2734. 'created_at' => date('Y-m-d H:i:s'),
  2735. 'updated_at' => date('Y-m-d H:i:s')
  2736. ]
  2737. ];
  2738. // 保存对话记录
  2739. $boolen3 = DB::table('mp_anime_records')->insert($records);
  2740. if (!$boolen3) {
  2741. Utils::throwError('20003:对话记录保存失败');
  2742. }
  2743. if ($is_single) {
  2744. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  2745. if (empty($episode_arr['acts'])) {
  2746. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  2747. }
  2748. $saveResult = $this->saveEpisodeVersionData(
  2749. $anime_id,
  2750. 1,
  2751. $episode_arr,
  2752. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  2753. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  2754. null,
  2755. null,
  2756. false,
  2757. $content,
  2758. $now
  2759. );
  2760. $single_episode = $saveResult['episode'];
  2761. $episode_id = $saveResult['episode_id'];
  2762. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  2763. 'roles' => json_encode($saveResult['merged_roles'], 256),
  2764. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  2765. 'updated_at' => $now
  2766. ]);
  2767. if ($boolen5 === false) {
  2768. Utils::throwError('20003:单剧集主表资源同步失败');
  2769. }
  2770. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  2771. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  2772. $episode_record_content = '确认分镜大纲';
  2773. if ($content !== '') {
  2774. $episode_record_content .= "\n\n###上传内容\n" . $content;
  2775. }
  2776. $episode_records = [
  2777. [
  2778. 'uid' => $uid,
  2779. 'anime_id' => $anime_id,
  2780. 'role' => 'user',
  2781. 'content' => $episode_record_content,
  2782. 'sequence' => 1,
  2783. 'episode_id' => $episode_id,
  2784. 'created_at' => $now,
  2785. 'updated_at' => $now
  2786. ],
  2787. [
  2788. 'uid' => $uid,
  2789. 'anime_id' => $anime_id,
  2790. 'role' => 'assistant',
  2791. 'content' => $fullContent,
  2792. 'sequence' => 1,
  2793. 'episode_id' => $episode_id,
  2794. 'created_at' => $now,
  2795. 'updated_at' => $now
  2796. ]
  2797. ];
  2798. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  2799. if (!$boolen4) {
  2800. Utils::throwError('20003:单剧集分镜记录保存失败');
  2801. }
  2802. }
  2803. }catch (\Exception $e) {
  2804. DB::rollBack();
  2805. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2806. yield [
  2807. 'type' => 'done',
  2808. 'answer' => $fullContent,
  2809. 'reasoning' => $fullReasoningContent,
  2810. 'usage' => $usage,
  2811. 'error' => $e->getMessage(),
  2812. ];
  2813. return;
  2814. }
  2815. DB::commit();
  2816. dLog('deepseek')->info('保存完毕');
  2817. if ($is_single && !empty($single_episode)) {
  2818. $this->batchSetGlobalRoleImg([
  2819. 'anime_id' => $anime_id,
  2820. ]);
  2821. $this->batchSetGlobalSceneImg([
  2822. 'anime_id' => $anime_id,
  2823. ]);
  2824. }
  2825. $table_data['anime_id'] = $anime_id;
  2826. $table_data['roles'] = json_decode($table_data['roles'], true);
  2827. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  2828. // $table_data['episodes'] = $script_arr['episodes'];
  2829. unset($table_data['created_at']);
  2830. unset($table_data['updated_at']);
  2831. unset($table_data['status']);
  2832. dLog('deepseek')->info('开始返回');
  2833. yield [
  2834. 'type' => 'done',
  2835. 'script' => $table_data,
  2836. 'episode' => $single_episode,
  2837. 'answer' => $fullContent,
  2838. 'reasoning' => $fullReasoningContent,
  2839. 'usage' => $usage
  2840. ];
  2841. }
  2842. public function reGenerateAnime($data) {
  2843. $uid = Site::getUid();
  2844. $file = getProp($data, 'file');
  2845. $content = getProp($data, 'content', '');
  2846. $bid = getProp($data, 'bid', 0);
  2847. $script_id = getProp($data, 'script_id', 0);
  2848. $anime_id = getProp($data, 'anime_id');
  2849. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  2850. if (!$anime) {
  2851. Utils::throwError('20003:该对话不存在');
  2852. }
  2853. $prompt = getProp($data, 'prompt');
  2854. // 处理文本模型
  2855. $model = getProp($data, 'model');
  2856. if (!$model) {
  2857. // 用户没有输入,从anime表获取
  2858. $model = getProp($anime, 'model');
  2859. if (!$model) {
  2860. // anime表也没有,使用默认值
  2861. $model = 'doubao-seed-2-0-mini-260215';
  2862. }
  2863. }
  2864. // 验证模型是否在可用模型表中
  2865. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2866. $model = 'doubao-seed-2-0-mini-260215';
  2867. }
  2868. $is_multi = getProp($anime, 'is_multi', 1);
  2869. $is_single = (int)$is_multi !== 1;
  2870. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  2871. if ($is_single) {
  2872. $episode_exists = DB::table('mp_anime_episodes')
  2873. ->where('anime_id', $anime_id)
  2874. ->where('sequence', 1)
  2875. ->exists();
  2876. if ($episode_exists) {
  2877. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  2878. }
  2879. }
  2880. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2881. // 提取文件内容
  2882. if ($file) {
  2883. $content = $this->extractFileContent($file);
  2884. if (!$content) {
  2885. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2886. }
  2887. } elseif ($script_id) {
  2888. $content = $this->getContentByScriptId($script_id);
  2889. if (!$content) {
  2890. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2891. }
  2892. } elseif ($bid) {
  2893. $content = $this->getContentByBid($bid);
  2894. if (!$content) {
  2895. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2896. }
  2897. } elseif ($content) {
  2898. $content = filterContent($content);
  2899. }else {
  2900. $content = filterContent(getProp($anime, 'content'));
  2901. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2902. $need_generate_content = true;
  2903. }
  2904. }
  2905. // 判断是否需要生成原文内容
  2906. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2907. // 如果需要生成原文内容,添加额外的要求
  2908. $content_generation_requirement = $need_generate_content
  2909. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2910. : "";
  2911. // 美术风格
  2912. $input_art_style = getProp($data, 'art_style');
  2913. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2914. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2915. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2916. 中年女:邻居阿姨
  2917. 老年男:幽默大爷
  2918. 老年女:婆婆
  2919. 萌娃:奶气萌娃";
  2920. $system_message = ['role'=>'system', 'content'=>$is_single
  2921. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2922. 强制要求:
  2923. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2924. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2925. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2926. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2927. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2928. 普通要求:
  2929. 1.剧集标题必须与文档内容高度相关,剧集序号是1。
  2930. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2931. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2932. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2933. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2934. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2935. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2936. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2937. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2938. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2939. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2940. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2941. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2942. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2943. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2944. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2945. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2946. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2947. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2948. 示例如下:\n
  2949. ###剧本名:西昆仑
  2950. ###故事梗概
  2951. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2952. ###剧本亮点
  2953. 亮点1:绝境奇药,生死一线
  2954. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2955. 亮点2:结拜兄妹,化解尴尬
  2956. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2957. 亮点3:纤发夺命,情愫暗涌
  2958. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2959. ###人物关系
  2960. 阿雪与梁萧之间存在兄妹之情。
  2961. ###核心矛盾
  2962. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2963. ###主体列表
  2964. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2965. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2966. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2967. 阴阳球:天地异宝,能化生精气,救人于危难。
  2968. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2969. ###美术风格
  2970. 基础画风风格词:厚涂古风
  2971. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2972. ###场景列表
  2973. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2974. ###分镜剧本
  2975. ##第1幕:徐家老旧厨房 白天 室内
  2976. 分镜1
  2977. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2978. 场景:徐家老旧厨房
  2979. 构图设计:全景,低角度仰视
  2980. 运镜调度:手持拍摄
  2981. 配音角色:旁白
  2982. 出镜角色:许芸-校服装、徐母
  2983. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2984. 画面类型:普通画面
  2985. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2986. 分镜2
  2987. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2988. 场景:徐家老旧厨房
  2989. 构图设计:近景,徐母面部特写
  2990. 运镜调度:固定镜头
  2991. 配音角色:徐母
  2992. 出镜角色:徐母
  2993. 台词内容:问我夜不归宿死哪儿去了。
  2994. 画面类型:对口型
  2995. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2996. ##第2幕:徐家简陋客厅 黄昏 室内
  2997. 分镜3
  2998. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2999. 场景:徐家简陋客厅
  3000. 构图设计:全景,景深虚化
  3001. 运镜调度:固定镜头
  3002. 配音角色:旁白
  3003. 出镜角色:无
  3004. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3005. 画面类型:普通画面
  3006. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3007. 分镜4
  3008. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3009. 场景:徐家简陋客厅
  3010. 构图设计:特写,火车票
  3011. 运镜调度:固定镜头
  3012. 配音角色:旁白
  3013. 出镜角色:无
  3014. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3015. 画面类型:普通画面
  3016. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3017. "
  3018. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  3019. 强制要求:\n
  3020. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3021. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3022. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3023. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3024. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3025. 普通要求:\n
  3026. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  3027. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  3028. 示例如下:\n
  3029. ###剧本名:西昆仑
  3030. ###故事梗概
  3031. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3032. ###剧本亮点
  3033. 亮点1:绝境奇药,生死一线
  3034. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3035. 亮点2:结拜兄妹,化解尴尬
  3036. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3037. 亮点3:纤发夺命,情愫暗涌
  3038. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3039. ###人物关系
  3040. 阿雪与梁萧之间存在兄妹之情。
  3041. ###核心矛盾
  3042. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3043. ###主体列表
  3044. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3045. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  3046. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3047. 阴阳球:天地异宝,能化生精气,救人于危难。
  3048. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3049. ###美术风格
  3050. 基础画风风格词:厚涂古风
  3051. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3052. ###场景列表
  3053. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"];
  3054. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  3055. $episode_count = $this->extractEpisodeNumber($prompt);
  3056. if ((int)getProp($anime, 'is_multi') !== 1) {
  3057. yield [
  3058. 'type' => 'done',
  3059. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  3060. 'reasoning' => '',
  3061. 'usage' => []
  3062. ];
  3063. return;
  3064. }
  3065. if ($episode_count) {
  3066. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  3067. $system_message = [
  3068. 'role' => 'system',
  3069. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  3070. 强制要求:\n
  3071. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3072. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3073. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3074. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3075. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3076. 普通要求:\n
  3077. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  3078. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  3079. 3.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  3080. 示例如下:\n
  3081. ###剧本名:西昆仑
  3082. ###故事梗概
  3083. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3084. ###剧本亮点
  3085. 亮点1:绝境奇药,生死一线
  3086. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3087. 亮点2:结拜兄妹,化解尴尬
  3088. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3089. 亮点3:纤发夺命,情愫暗涌
  3090. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3091. ###人物关系
  3092. 阿雪与梁萧之间存在兄妹之情。
  3093. ###核心矛盾
  3094. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3095. ###主体列表
  3096. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3097. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  3098. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3099. 阴阳球:天地异宝,能化生精气,救人于危难。
  3100. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3101. ###美术风格
  3102. 基础画风风格词:厚涂古风
  3103. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3104. ###场景列表
  3105. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  3106. ###分集详细内容
  3107. ##第1章 重生
  3108. 我重生了。
  3109. 源于一个男人偏执的暗恋。
  3110. ##第2章 相救
  3111. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  3112. 我眼睛扫向站在锅炉后的卞大伟。"
  3113. ];
  3114. // 构建消息
  3115. $messages = [
  3116. $system_message,
  3117. [
  3118. 'role' => 'user',
  3119. 'content' => "以下是文档内容:
  3120. {$content}
  3121. 用户问题:
  3122. {$question}"
  3123. ]
  3124. ];
  3125. }else {
  3126. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  3127. // 构建消息
  3128. $messages = [
  3129. $system_message,
  3130. [
  3131. 'role' => 'user',
  3132. 'content' => "以下是文档内容:
  3133. {$content}
  3134. 用户问题:
  3135. {$question}"
  3136. ]
  3137. ];
  3138. }else {
  3139. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  3140. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  3141. return (array)$value;
  3142. })->toArray();
  3143. array_unshift($messages, $system_message);
  3144. $messages[] = [
  3145. 'role' => 'user',
  3146. 'content' => $prompt
  3147. ];
  3148. }
  3149. }
  3150. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3151. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3152. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3153. if ($model === 'deepseek-chat') {
  3154. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3155. $model = 'deepseek-v4-flash';
  3156. $thinkingMode = 'disabled';
  3157. } elseif ($model === 'deepseek-reasoner') {
  3158. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3159. $model = 'deepseek-v4-flash';
  3160. $thinkingMode = 'enabled';
  3161. }
  3162. $post_data = [
  3163. 'model' => $model,
  3164. 'messages' => $messages,
  3165. // 'max_tokens' => 8192,
  3166. 'temperature' => 0.7,
  3167. 'frequency_penalty' => 0,
  3168. 'presence_penalty' => 0,
  3169. 'response_format' => ['type' => 'text'],
  3170. 'thinking' => ['type' => $thinkingMode],
  3171. 'stream' => true // 启用流式输出
  3172. ];
  3173. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3174. // 根据模型类型选择调用方法
  3175. $fullContent = '';
  3176. $fullReasoningContent = '';
  3177. $usage = [];
  3178. // dd($post_data);
  3179. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  3180. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3181. // DeepSeek 官方模型使用 DeepSeek API
  3182. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3183. } else {
  3184. // 其他模型使用火山引擎API
  3185. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3186. }
  3187. // 处理流式输出
  3188. foreach ($streamGenerator as $chunk) {
  3189. if (isset($chunk['type'])) {
  3190. if ($chunk['type'] === 'done') {
  3191. // 最终结果
  3192. $fullContent = $chunk['full_content'];
  3193. $fullReasoningContent = $chunk['full_reasoning'];
  3194. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3195. } else {
  3196. // 逐块yield数据
  3197. yield $chunk;
  3198. }
  3199. }
  3200. }
  3201. dLog('deepseek')->info('完整内容: '.$fullContent);
  3202. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3203. // 处理完整内容并返回最终结果
  3204. $script_arr = [];
  3205. if ($fullContent) {
  3206. $script_arr = handleScriptContent($fullContent);
  3207. dLog('deepseek')->info('解析内容', $script_arr);
  3208. logDB('deepseek', 'info', '解析内容', $script_arr);
  3209. }
  3210. if (empty($script_arr['roles'])) {
  3211. // 未生成剧本相关内容,保存对话记录并返回提示
  3212. dLog('deepseek')->info('未生成剧本相关的内容');
  3213. try {
  3214. $now = date('Y-m-d H:i:s');
  3215. // 保存对话记录
  3216. $records = [
  3217. [
  3218. 'uid' => $uid,
  3219. 'anime_id' => $anime_id,
  3220. 'sequence' => 0,
  3221. 'role' => 'user',
  3222. 'content' => $prompt,
  3223. 'created_at' => $now,
  3224. 'updated_at' => $now
  3225. ],
  3226. [
  3227. 'uid' => $uid,
  3228. 'anime_id' => $anime_id,
  3229. 'sequence' => 0,
  3230. 'role' => 'assistant',
  3231. 'content' => $fullContent,
  3232. 'created_at' => $now,
  3233. 'updated_at' => $now
  3234. ]
  3235. ];
  3236. DB::table('mp_anime_records')->insert($records);
  3237. } catch (\Exception $e) {
  3238. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3239. }
  3240. yield [
  3241. 'type' => 'done',
  3242. 'script' => [],
  3243. 'episode' => [],
  3244. 'answer' => $fullContent,
  3245. 'reasoning' => $fullReasoningContent,
  3246. 'usage' => $usage,
  3247. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3248. ];
  3249. return;
  3250. }
  3251. // 替换美术风格
  3252. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3253. if ($mappedArtStyle !== '') {
  3254. $script_arr['art_style'] = $mappedArtStyle;
  3255. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3256. }
  3257. $table_data = [
  3258. 'user_id' => $uid,
  3259. 'model' => $model,
  3260. 'anime_name' => isset($script_arr['script_name']) ? $script_arr['script_name'] : '',
  3261. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3262. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3263. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3264. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3265. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  3266. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3267. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  3268. 'status' => '解析完成',
  3269. 'generate_status' => '待执行',
  3270. 'updated_at' => date('Y-m-d H:i:s')
  3271. ];
  3272. // 如果是修改集数,则将content内容更新(会改变原文)
  3273. if (isset($episode_count) && $episode_count > 0) {
  3274. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  3275. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  3276. }else {
  3277. // 如果需要生成原文内容,从script_arr中提取
  3278. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3279. $table_data['content'] = $script_arr['content'];
  3280. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  3281. if (!$content) {
  3282. yield [
  3283. 'type' => 'done',
  3284. 'script' => [],
  3285. 'episode' => [],
  3286. 'answer' => $fullContent,
  3287. 'reasoning' => $fullReasoningContent,
  3288. 'usage' => $usage,
  3289. 'error' => '未生成剧本内容,请调整提示词再试'
  3290. ];
  3291. return;
  3292. }
  3293. } else {
  3294. $chapters = $this->splitContent($content);
  3295. $chapter_count = count($chapters);
  3296. if ($chapter_count > 0) {
  3297. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3298. }
  3299. }
  3300. }
  3301. $single_episode = [];
  3302. try {
  3303. DB::beginTransaction();
  3304. $now = date('Y-m-d H:i:s');
  3305. // 更新动漫大纲
  3306. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3307. if (!$boolen) {
  3308. dLog('deepseek')->info('对话修改失败', $table_data);
  3309. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  3310. Utils::throwError('20003:对话修改失败');
  3311. }
  3312. // 保存对话记录
  3313. $records = [
  3314. [
  3315. 'uid' => $uid,
  3316. 'anime_id' => $anime_id,
  3317. 'sequence' => 0,
  3318. 'role' => 'user',
  3319. 'content' => $prompt,
  3320. 'created_at' => $now,
  3321. 'updated_at' => $now
  3322. ],
  3323. [
  3324. 'uid' => $uid,
  3325. 'anime_id' => $anime_id,
  3326. 'sequence' => 0,
  3327. 'role' => 'assistant',
  3328. 'content' => $fullContent,
  3329. 'created_at' => $now,
  3330. 'updated_at' => $now
  3331. ]
  3332. ];
  3333. // 保存对话记录
  3334. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3335. if (!$boolen3) {
  3336. Utils::throwError('20003:对话记录保存失败');
  3337. }
  3338. // 单剧集模式:生成并保存剧集信息
  3339. if ($is_single) {
  3340. $anime_name = getProp($anime, 'anime_name', '未命名');
  3341. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3342. if (empty($episode_arr['acts'])) {
  3343. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3344. }
  3345. $saveResult = $this->saveEpisodeVersionData(
  3346. $anime_id,
  3347. 1,
  3348. $episode_arr,
  3349. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3350. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3351. null,
  3352. null,
  3353. false,
  3354. $content,
  3355. $now
  3356. );
  3357. $single_episode = $saveResult['episode'];
  3358. $episode_id = $saveResult['episode_id'];
  3359. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3360. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3361. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3362. 'updated_at' => $now
  3363. ]);
  3364. if ($boolen5 === false) {
  3365. Utils::throwError('20003:单剧集主表资源同步失败');
  3366. }
  3367. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3368. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3369. $episode_record_content = '确认分镜大纲';
  3370. if ($content !== '') {
  3371. $episode_record_content .= "\n\n###上传内容\n" . $content;
  3372. }
  3373. $episode_records = [
  3374. [
  3375. 'uid' => $uid,
  3376. 'anime_id' => $anime_id,
  3377. 'role' => 'user',
  3378. 'content' => $episode_record_content,
  3379. 'sequence' => 1,
  3380. 'episode_id' => $episode_id,
  3381. 'created_at' => $now,
  3382. 'updated_at' => $now
  3383. ],
  3384. [
  3385. 'uid' => $uid,
  3386. 'anime_id' => $anime_id,
  3387. 'role' => 'assistant',
  3388. 'content' => $fullContent,
  3389. 'sequence' => 1,
  3390. 'episode_id' => $episode_id,
  3391. 'created_at' => $now,
  3392. 'updated_at' => $now
  3393. ]
  3394. ];
  3395. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3396. if (!$boolen4) {
  3397. Utils::throwError('20003:单剧集分镜记录保存失败');
  3398. }
  3399. }
  3400. }catch (\Exception $e) {
  3401. DB::rollBack();
  3402. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  3403. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  3404. yield [
  3405. 'type' => 'done',
  3406. 'answer' => $fullContent,
  3407. 'reasoning' => $fullReasoningContent,
  3408. 'usage' => $usage,
  3409. 'error' => $e->getMessage(),
  3410. ];
  3411. return;
  3412. }
  3413. DB::commit();
  3414. dLog('deepseek')->info('保存完毕');
  3415. if ($is_single && !empty($single_episode)) {
  3416. $this->batchSetGlobalRoleImg([
  3417. 'anime_id' => $anime_id,
  3418. ]);
  3419. $this->batchSetGlobalSceneImg([
  3420. 'anime_id' => $anime_id,
  3421. ]);
  3422. }
  3423. $table_data['anime_id'] = $anime_id;
  3424. $table_data['roles'] = json_decode($table_data['roles'], true);
  3425. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3426. unset($table_data['updated_at']);
  3427. unset($table_data['status']);
  3428. yield [
  3429. 'type' => 'done',
  3430. 'script' => $table_data,
  3431. 'episode' => $single_episode,
  3432. 'answer' => $fullContent,
  3433. 'reasoning' => $fullReasoningContent,
  3434. 'usage' => $usage
  3435. ];
  3436. }
  3437. public function chat($data) {
  3438. $uid = Site::getUid();
  3439. $anime_id = getProp($data, 'anime_id');
  3440. $file = getProp($data, 'file');
  3441. $content = getProp($data, 'content', '');
  3442. $bid = getProp($data, 'bid', 0);
  3443. $script_id = getProp($data, 'script_id', 0);
  3444. $episode_number = getProp($data, 'episode_number', 1);
  3445. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3446. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3447. if (!$anime) Utils::throwError('20003:该对话不存在!');
  3448. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  3449. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  3450. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  3451. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  3452. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  3453. $roles = is_array($roles) ? $roles : [];
  3454. $scenes = is_array($scenes) ? $scenes : [];
  3455. // 转换主体列表和场景列表的格式
  3456. $roles_content = $this->buildEpisodeItemContent($roles, 'role');
  3457. $scenes_content = $this->buildEpisodeItemContent($scenes, 'scene');
  3458. // 获取音色列表
  3459. // $timbres = DB::table('mp_timbres')->select('timbre_name')->where('is_enabled', 1)->where('id', '<=', 15)->get()->map(function ($value) {
  3460. // $value = (array)$value;
  3461. // $value['timbre_name'] = str_replace('(多情感)', '', $value['timbre_name']);
  3462. // return $value;
  3463. // })->pluck('timbre_name')->toArray();
  3464. // $timbres_content = implode('、', $timbres);
  3465. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3466. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3467. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3468. 中年女:邻居阿姨
  3469. 老年男:幽默大爷
  3470. 老年女:婆婆
  3471. 萌娃:奶气萌娃";
  3472. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3473. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3474. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3475. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3476. // 提取文件内容
  3477. if ($file) {
  3478. $uploaded_content = $this->extractFileContent($file);
  3479. if (!$uploaded_content) {
  3480. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3481. }
  3482. } elseif ($script_id) {
  3483. $uploaded_content = $this->getContentByScriptId($script_id);
  3484. if (!$uploaded_content) {
  3485. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3486. }
  3487. } elseif ($bid) {
  3488. $uploaded_content = $this->getContentByBid($bid);
  3489. if (!$uploaded_content) {
  3490. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3491. }
  3492. } elseif ($content) {
  3493. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  3494. }
  3495. // elseif ($prompt) {
  3496. // $uploaded_content = filterContent($prompt);
  3497. // }
  3498. else {
  3499. $uploaded_content = '';
  3500. }
  3501. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3502. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  3503. 强制要求:
  3504. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3505. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3506. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3507. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3508. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3509. 普通要求:
  3510. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  3511. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):\n{$roles_content}。
  3512. 2.1如果分集内容中出现了<主体列表>中不存在的新主体,则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在主题列表中。
  3513. 2.2主体列表的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3514. 3.<场景列表>必须在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,除非出现<场景列表>中不存在的场景,否则不得自定义:\n{$scenes_content}。
  3515. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3516. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3517. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3518. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3519. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3520. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3521. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  3522. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3523. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3524. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3525. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3526. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3527. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3528. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3529. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3530. 示例格式:\n
  3531. 第1集:隐形的守护者
  3532. ###故事梗概
  3533. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  3534. ###美术风格
  3535. 基础画风风格词:韩漫二次元
  3536. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  3537. ###主体列表
  3538. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{{甜心小美}}
  3539. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{{爽快思思}}
  3540. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{{阳光青年}}
  3541. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。{{广州德哥}}
  3542. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。{{邻居阿姨}}
  3543. ###场景列表
  3544. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  3545. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  3546. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  3547. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  3548. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  3549. ###分镜剧本
  3550. ##第1幕:徐家老旧厨房 白天 室内
  3551. 分镜1
  3552. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3553. 场景:徐家老旧厨房
  3554. 构图设计:全景,低角度仰视
  3555. 运镜调度:手持拍摄
  3556. 配音角色:旁白
  3557. 出镜角色:许芸-校服装、徐母
  3558. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3559. 画面类型:普通画面
  3560. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3561. 分镜2
  3562. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3563. 场景:徐家老旧厨房
  3564. 构图设计:近景,徐母面部特写
  3565. 运镜调度:固定镜头
  3566. 配音角色:徐母
  3567. 出镜角色:徐母
  3568. 台词内容:问我夜不归宿死哪儿去了。
  3569. 画面类型:对口型
  3570. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3571. ##第2幕:徐家简陋客厅 黄昏 室内
  3572. 分镜3
  3573. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3574. 场景:徐家简陋客厅
  3575. 构图设计:全景,景深虚化
  3576. 运镜调度:固定镜头
  3577. 配音角色:旁白
  3578. 出镜角色:无
  3579. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3580. 画面类型:普通画面
  3581. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3582. 分镜4
  3583. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3584. 场景:徐家简陋客厅
  3585. 构图设计:特写,火车票
  3586. 运镜调度:固定镜头
  3587. 配音角色:旁白
  3588. 出镜角色:无
  3589. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3590. 画面类型:普通画面
  3591. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  3592. \n\n";
  3593. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3594. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  3595. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  3596. $prompt = $origin_prompt;
  3597. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  3598. // 获取章节内容
  3599. $full_content = getProp($anime, 'content');
  3600. // 根据章节内容拆分章节
  3601. $chapters = $this->splitContent($full_content);
  3602. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  3603. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  3604. $messages = [];
  3605. if ($prompt == '确认分镜大纲') {
  3606. $content = $uploaded_content ?: $chapter_content;
  3607. if ($is_single) $content = $full_content; // 单剧集使用全文
  3608. if (!$content) {
  3609. Utils::throwError('20003:章节内容无法获取,请确认');
  3610. }
  3611. $question = $is_single
  3612. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  3613. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  3614. // 构建消息
  3615. $messages[] =
  3616. [
  3617. 'role' => 'user',
  3618. 'content' => $question
  3619. ];
  3620. }else if ($prompt == '继续策划下一集') {
  3621. if ($is_single) {
  3622. Utils::throwError('20003:单剧集不支持继续策划下一集');
  3623. }
  3624. $content = $uploaded_content ?: $chapter_content;
  3625. if (!$content) {
  3626. Utils::throwError('20003:章节内容无法获取,请确认');
  3627. }
  3628. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  3629. // 获取上一集最后记录
  3630. $prev_sequence = $episode_number - 1;
  3631. $messages = $this->getEpisodeChatMessages($anime_id, $prev_sequence);
  3632. // 构建消息
  3633. $messages[] =
  3634. [
  3635. 'role' => 'user',
  3636. 'content' => $question
  3637. ];
  3638. }else {
  3639. $content = $uploaded_content ?: trim((string)getProp($base_episode, 'content'));
  3640. if (!$content) {
  3641. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  3642. }
  3643. if (!$content) {
  3644. Utils::throwError('20003:章节内容无法获取,请确认');
  3645. }
  3646. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  3647. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  3648. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。"
  3649. . "\n\n本次修改要求如下:\n{$origin_prompt}";
  3650. $messages[] =
  3651. [
  3652. 'role' => 'user',
  3653. 'content' => $question
  3654. ];
  3655. }
  3656. // 处理文本模型
  3657. $model = getProp($data, 'model');
  3658. if (!$model) {
  3659. // 用户没有输入,从anime表获取
  3660. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3661. $model = getProp($anime, 'model');
  3662. if (!$model) {
  3663. // anime表也没有,使用默认值
  3664. $model = 'doubao-seed-2-0-mini-260215';
  3665. }
  3666. }
  3667. // 验证模型是否在可用模型表中
  3668. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3669. $model = 'doubao-seed-2-0-mini-260215';
  3670. }
  3671. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3672. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3673. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3674. if ($model === 'deepseek-chat') {
  3675. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3676. $model = 'deepseek-v4-flash';
  3677. $thinkingMode = 'disabled';
  3678. } elseif ($model === 'deepseek-reasoner') {
  3679. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3680. $model = 'deepseek-v4-flash';
  3681. $thinkingMode = 'enabled';
  3682. }
  3683. $post_data = [
  3684. 'model' => $model,
  3685. 'messages' => $messages,
  3686. // 'max_tokens' => 8192,
  3687. 'temperature' => 0.7,
  3688. 'frequency_penalty' => 0,
  3689. 'presence_penalty' => 0,
  3690. 'response_format' => ['type' => 'text'],
  3691. 'thinking' => ['type' => $thinkingMode],
  3692. 'stream' => true // 启用流式输出
  3693. ];
  3694. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3695. // 根据模型类型选择调用方法
  3696. $fullContent = '';
  3697. $fullReasoningContent = '';
  3698. $usage = [];
  3699. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3700. // DeepSeek 官方模型使用 DeepSeek API
  3701. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3702. } else {
  3703. // 其他模型使用火山引擎API
  3704. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3705. }
  3706. // 处理流式输出
  3707. if (!is_iterable($streamGenerator)) {
  3708. dLog('deepseek')->error('chat流式生成器无效', ['generator_type' => gettype($streamGenerator)]);
  3709. Utils::throwError('20003:接口返回数据异常,请重新请求');
  3710. }
  3711. foreach ($streamGenerator as $chunk) {
  3712. if (isset($chunk['type'])) {
  3713. if ($chunk['type'] === 'done') {
  3714. // 最终结果
  3715. $fullContent = $chunk['full_content'];
  3716. $fullReasoningContent = $chunk['full_reasoning'];
  3717. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3718. } else {
  3719. // 逐块yield数据
  3720. yield $chunk;
  3721. }
  3722. }
  3723. }
  3724. dLog('deepseek')->info('完整内容: '.$fullContent);
  3725. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3726. // 处理完整内容并返回最终结果
  3727. $episode_arr = handleEpisodeContent($fullContent);
  3728. logDB('deepseek', 'info', '解析内容', $episode_arr);
  3729. if (empty($episode_arr['acts'])) {
  3730. // 未生成剧本相关内容,保存对话记录并返回提示
  3731. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  3732. try {
  3733. $now = date('Y-m-d H:i:s');
  3734. // 保存对话记录
  3735. $records = [
  3736. [
  3737. 'uid' => $uid,
  3738. 'anime_id' => $anime_id,
  3739. 'sequence' => $episode_number,
  3740. 'role' => 'user',
  3741. 'content' => $prompt,
  3742. 'created_at' => $now,
  3743. 'updated_at' => $now
  3744. ],
  3745. [
  3746. 'uid' => $uid,
  3747. 'anime_id' => $anime_id,
  3748. 'sequence' => $episode_number,
  3749. 'role' => 'assistant',
  3750. 'content' => $fullContent,
  3751. 'created_at' => $now,
  3752. 'updated_at' => $now
  3753. ]
  3754. ];
  3755. DB::table('mp_anime_records')->insert($records);
  3756. } catch (\Exception $e) {
  3757. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3758. }
  3759. yield [
  3760. 'type' => 'done',
  3761. 'episode' => [],
  3762. 'answer' => $fullContent,
  3763. 'reasoning' => $fullReasoningContent,
  3764. 'usage' => $usage,
  3765. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  3766. ];
  3767. return;
  3768. }
  3769. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3770. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3771. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3772. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3773. $now = date('Y-m-d H:i:s');
  3774. try {
  3775. DB::beginTransaction();
  3776. $saveResult = $this->saveEpisodeVersionData(
  3777. $anime_id,
  3778. $episode_number,
  3779. $episode_arr,
  3780. $existing_roles,
  3781. $existing_scenes,
  3782. $current_episode,
  3783. $base_episode,
  3784. $is_regenerate_version,
  3785. $content,
  3786. $now
  3787. );
  3788. $episode = $saveResult['episode'];
  3789. $episode_id = $saveResult['episode_id'];
  3790. $merged_roles = $saveResult['merged_roles'];
  3791. $merged_scenes = $saveResult['merged_scenes'];
  3792. $record_content = $origin_prompt;
  3793. if ($uploaded_content !== '') {
  3794. $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  3795. }
  3796. $records = [
  3797. [
  3798. 'uid' => $uid,
  3799. 'anime_id' => $anime_id,
  3800. 'role' => 'user',
  3801. 'content' => $record_content,
  3802. 'sequence' => $episode_number,
  3803. 'episode_id' => $episode_id,
  3804. 'created_at' => $now,
  3805. 'updated_at' => $now
  3806. ],
  3807. [
  3808. 'uid' => $uid,
  3809. 'anime_id' => $anime_id,
  3810. 'role' => 'assistant',
  3811. 'content' => $fullContent,
  3812. 'sequence' => $episode_number,
  3813. 'episode_id' => $episode_id,
  3814. 'created_at' => $now,
  3815. 'updated_at' => $now
  3816. ]
  3817. ];
  3818. $boolen4 = DB::table('mp_anime_records')->insert($records);
  3819. if (!$boolen4) {
  3820. Utils::throwError('20003:对话记录保存失败');
  3821. }
  3822. // 保存模型到anime表
  3823. DB::table('mp_animes')->where('id', $anime_id)->update([
  3824. 'model' => $model,
  3825. 'updated_at' => $now
  3826. ]);
  3827. }catch (\Exception $e) {
  3828. DB::rollBack();
  3829. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3830. yield [
  3831. 'type' => 'done',
  3832. 'answer' => $fullContent,
  3833. 'reasoning' => $fullReasoningContent,
  3834. 'usage' => $usage,
  3835. 'error' => $e->getMessage(),
  3836. ];
  3837. return;
  3838. }
  3839. DB::commit();
  3840. if ($is_global_generate_pics) {
  3841. // 批量生成全局角色图片
  3842. $this->batchSetGlobalRoleImg([
  3843. 'anime_id' => $anime_id,
  3844. ]);
  3845. // 批量生成全局场景图片
  3846. $this->batchSetGlobalSceneImg([
  3847. 'anime_id' => $anime_id,
  3848. ]);
  3849. }
  3850. $episode['episode_id'] = $episode_id;
  3851. $episode['roles'] = $merged_roles;
  3852. $episode['scenes'] = $merged_scenes;
  3853. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  3854. yield [
  3855. 'type' => 'done',
  3856. 'episode' => $episode,
  3857. 'answer' => $fullContent,
  3858. 'reasoning' => $fullReasoningContent,
  3859. 'usage' => $usage
  3860. ];
  3861. }
  3862. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  3863. {
  3864. $episode_arr = [
  3865. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  3866. 'intro' => getProp($script_arr, 'intro'),
  3867. 'art_style' => getProp($script_arr, 'art_style'),
  3868. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3869. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3870. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  3871. ];
  3872. if (empty($episode_arr['acts'])) {
  3873. $fallback_episode_arr = handleEpisodeContent($fullContent);
  3874. if (!empty($fallback_episode_arr['acts'])) {
  3875. $episode_arr = array_merge($fallback_episode_arr, [
  3876. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  3877. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  3878. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  3879. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  3880. ]);
  3881. }
  3882. }
  3883. // if (!getProp($episode_arr, 'episode_title')) {
  3884. // $episode_title = '';
  3885. // $episodes = getProp($script_arr, 'episodes', []);
  3886. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  3887. // $episode_title = '第1集:' . $episodes[0]['title'];
  3888. // }
  3889. // if (!$episode_title) {
  3890. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  3891. // }
  3892. // $episode_arr['episode_title'] = $episode_title;
  3893. // }
  3894. return $episode_arr;
  3895. }
  3896. private function saveEpisodeVersionData(
  3897. int $anime_id,
  3898. int $episode_number,
  3899. array $episode_arr,
  3900. array $existing_roles,
  3901. array $existing_scenes,
  3902. $current_episode,
  3903. $base_episode,
  3904. bool $is_regenerate_version,
  3905. string $content,
  3906. string $now
  3907. ): array {
  3908. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  3909. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  3910. $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  3911. $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  3912. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  3913. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3914. $global_roles = json_decode(getProp($anime, 'roles'), true);
  3915. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  3916. $global_roles = is_array($global_roles) ? $global_roles : [];
  3917. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  3918. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  3919. // 检查并创建 roles 的图片生成任务
  3920. $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  3921. // 检查并创建 scenes 的图片生成任务
  3922. $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  3923. $role_arr = [];
  3924. foreach ($merged_roles as $item) {
  3925. $role_arr[$item['role']] = $item;
  3926. }
  3927. $version_count = DB::table('mp_anime_episodes')
  3928. ->where('anime_id', $anime_id)
  3929. ->where('episode_number', $episode_number)
  3930. ->count('id');
  3931. $episode = [
  3932. 'anime_id' => $anime_id,
  3933. 'episode_number' => $episode_number,
  3934. 'title' => getProp($episode_arr, 'episode_title'),
  3935. 'content' => $content,
  3936. 'intro' => getProp($episode_arr, 'intro'),
  3937. 'art_style' => getProp($episode_arr, 'art_style'),
  3938. 'roles' => json_encode($merged_roles, 256),
  3939. 'scenes' => json_encode($merged_scenes, 256),
  3940. 'generate_status' => '待执行',
  3941. 'generate_at' => $now,
  3942. 'is_default' => 1,
  3943. 'updated_at' => $now,
  3944. ];
  3945. $del_flag = false;
  3946. if ($is_regenerate_version) {
  3947. DB::table('mp_anime_episodes')
  3948. ->where('anime_id', $anime_id)
  3949. ->where('episode_number', $episode_number)
  3950. ->update(['is_default' => 0, 'updated_at' => $now]);
  3951. $episode['sequence'] = $version_count + 1;
  3952. $episode['created_at'] = $now;
  3953. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  3954. if (!$episode_id) {
  3955. Utils::throwError('20003:创建剧集版本失败');
  3956. }
  3957. } else {
  3958. $target_episode = $current_episode ?: $base_episode;
  3959. if ($target_episode) {
  3960. $episode_id = getProp($target_episode, 'id');
  3961. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  3962. DB::table('mp_anime_episodes')
  3963. ->where('anime_id', $anime_id)
  3964. ->where('episode_number', $episode_number)
  3965. ->where('id', '<>', $episode_id)
  3966. ->update(['is_default' => 0, 'updated_at' => $now]);
  3967. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  3968. if ($boolen === false) {
  3969. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  3970. Utils::throwError('20003:分集内容保存失败');
  3971. }
  3972. $del_flag = true;
  3973. } else {
  3974. DB::table('mp_anime_episodes')
  3975. ->where('anime_id', $anime_id)
  3976. ->where('episode_number', $episode_number)
  3977. ->update(['is_default' => 0, 'updated_at' => $now]);
  3978. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  3979. $episode['created_at'] = $now;
  3980. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  3981. if (!$episode_id) {
  3982. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  3983. Utils::throwError('20003:分集内容保存失败');
  3984. }
  3985. }
  3986. }
  3987. $segments = [];
  3988. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  3989. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3990. $emotion_list = array_flip($emotion_list);
  3991. foreach ($acts as $act) {
  3992. $act_segments = getProp($act, 'segments', []);
  3993. if (!is_array($act_segments)) {
  3994. continue;
  3995. }
  3996. foreach ($act_segments as $segment) {
  3997. $voice_actor = getProp($segment, 'voice_actor');
  3998. $timbre_info = isset($role_arr[$voice_actor]) ? $role_arr[$voice_actor] : [];
  3999. $voice_type = getProp($timbre_info, 'voice_type');
  4000. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  4001. if ($timbre_emotion) {
  4002. $timbre_emotion = explode(',', $timbre_emotion);
  4003. } else {
  4004. $timbre_emotion = [];
  4005. }
  4006. $emotion = getProp($segment, 'emotion', '中性');
  4007. if (!in_array($emotion, $timbre_emotion)) {
  4008. $emotion = '中性';
  4009. }
  4010. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  4011. $segments[] = [
  4012. 'anime_id' => $anime_id,
  4013. 'episode_id' => $episode_id,
  4014. 'episode_number' => $episode_number,
  4015. 'act_number' => getProp($act, 'act_number'),
  4016. 'act_title' => getProp($act, 'act_title'),
  4017. 'segment_id' => getProp($segment, 'segment_id'),
  4018. 'segment_number' => getProp($segment, 'segment_number'),
  4019. 'segment_content' => getProp($segment, 'segment_content'),
  4020. 'description' => getProp($segment, 'description'),
  4021. 'composition' => getProp($segment, 'composition'),
  4022. 'camera_movement' => getProp($segment, 'camera_movement'),
  4023. 'voice_actor' => $voice_actor,
  4024. 'dialogue' => getProp($segment, 'dialogue'),
  4025. 'frame_type' => getProp($segment, 'frame_type'),
  4026. 'scene' => getProp($segment, 'scene'),
  4027. 'characters' => getProp($segment, 'characters'),
  4028. 'tail_frame' => getProp($segment, 'tail_frame'),
  4029. 'voice_name' => getProp($timbre_info, 'voice_name'),
  4030. 'voice_type' => $voice_type,
  4031. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  4032. 'emotion' => $emotion,
  4033. 'emotion_type' => $emotion_type,
  4034. 'gender' => getProp($segment, 'gender', '0'),
  4035. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  4036. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  4037. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  4038. 'pitch' => getProp($segment, 'pitch', 0),
  4039. 'created_at' => $now,
  4040. 'updated_at' => $now
  4041. ];
  4042. }
  4043. }
  4044. if ($segments) {
  4045. if ($del_flag) {
  4046. DB::table('mp_episode_segments')
  4047. ->where('anime_id', $anime_id)
  4048. ->where('episode_id', $episode_id)
  4049. ->delete();
  4050. }
  4051. $boolen = DB::table('mp_episode_segments')->insert($segments);
  4052. if (!$boolen) {
  4053. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  4054. Utils::throwError('20003:分镜内容保存失败');
  4055. }
  4056. }
  4057. $episode['episode_id'] = $episode_id;
  4058. $episode['roles'] = $merged_roles;
  4059. $episode['scenes'] = $merged_scenes;
  4060. $episode['acts'] = $acts;
  4061. return [
  4062. 'episode' => $episode,
  4063. 'episode_id' => $episode_id,
  4064. 'merged_roles' => $merged_roles,
  4065. 'merged_scenes' => $merged_scenes,
  4066. ];
  4067. }
  4068. private function buildEpisodeItemContent(array $items, string $nameKey): string
  4069. {
  4070. $content = '';
  4071. foreach ($items as $item) {
  4072. $name = trim((string)getProp($item, $nameKey));
  4073. if ($name === '') {
  4074. continue;
  4075. }
  4076. $description = trim((string)getProp($item, 'description'));
  4077. $content .= $name . ': ' . $description . "\n";
  4078. }
  4079. return trim($content);
  4080. }
  4081. private function getEpisodeChatMessages($animeId, $sequence): array
  4082. {
  4083. if ((int)$sequence <= 0) {
  4084. return [];
  4085. }
  4086. return DB::table('mp_anime_records')
  4087. ->where('anime_id', $animeId)
  4088. ->where('sequence', $sequence)
  4089. ->select('role', 'content')
  4090. ->orderBy('created_at')
  4091. ->orderBy('id')
  4092. ->get()
  4093. ->map(function ($value) {
  4094. return (array)$value;
  4095. })
  4096. ->toArray();
  4097. }
  4098. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  4099. {
  4100. $existingMap = [];
  4101. foreach ($existingItems as $item) {
  4102. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4103. if ($itemKey === '') {
  4104. continue;
  4105. }
  4106. $existingMap[$itemKey] = $item;
  4107. }
  4108. if (!$generatedItems) {
  4109. return array_values($existingItems);
  4110. }
  4111. $merged = [];
  4112. foreach ($generatedItems as $item) {
  4113. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4114. if ($itemKey === '') {
  4115. continue;
  4116. }
  4117. if (isset($existingMap[$itemKey])) {
  4118. if (trim((string)getProp($item, 'description')) === '') {
  4119. $merged[] = $existingMap[$itemKey];
  4120. continue;
  4121. }
  4122. // 检查内容是否发生变化
  4123. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  4124. if (!$isChanged) {
  4125. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  4126. $mergedItem = [
  4127. $nameKey => trim((string)getProp($item, $nameKey)),
  4128. 'description' => trim((string)getProp($item, 'description')),
  4129. ];
  4130. // 继承现有项的 URL
  4131. $existingUrl = getProp($existingMap[$itemKey], 'url');
  4132. if (!empty($existingUrl)) {
  4133. $mergedItem['url'] = $existingUrl;
  4134. }
  4135. // 继承现有项的 task_id
  4136. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  4137. if (!empty($existingTaskId)) {
  4138. $mergedItem['task_id'] = $existingTaskId;
  4139. }
  4140. // 继承现有项的 task_status
  4141. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  4142. if (!empty($existingTaskStatus)) {
  4143. $mergedItem['task_status'] = $existingTaskStatus;
  4144. }
  4145. // 保留生成项的音色字段
  4146. $voiceName = getProp($item, 'voice_name');
  4147. if (!empty($voiceName)) {
  4148. $mergedItem['voice_name'] = $voiceName;
  4149. }
  4150. $voiceType = getProp($item, 'voice_type');
  4151. if (!empty($voiceType)) {
  4152. $mergedItem['voice_type'] = $voiceType;
  4153. }
  4154. $audioUrl = getProp($item, 'voice_audio_url');
  4155. if (!empty($audioUrl)) {
  4156. $mergedItem['voice_audio_url'] = $audioUrl;
  4157. }
  4158. $merged[] = $mergedItem;
  4159. } else {
  4160. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  4161. $mergedItem = [
  4162. $nameKey => trim((string)getProp($item, $nameKey)),
  4163. 'description' => trim((string)getProp($item, 'description')),
  4164. ];
  4165. // 保留生成项的音色字段
  4166. $voiceName = getProp($item, 'voice_name');
  4167. if (!empty($voiceName)) {
  4168. $mergedItem['voice_name'] = $voiceName;
  4169. }
  4170. $voiceType = getProp($item, 'voice_type');
  4171. if (!empty($voiceType)) {
  4172. $mergedItem['voice_type'] = $voiceType;
  4173. }
  4174. $audioUrl = getProp($item, 'voice_audio_url');
  4175. if (!empty($audioUrl)) {
  4176. $mergedItem['voice_audio_url'] = $audioUrl;
  4177. }
  4178. // 不继承 URL、task_id 和 task_status(重置状态)
  4179. $merged[] = $mergedItem;
  4180. }
  4181. } else {
  4182. // 新增项,保留生成项的所有字段
  4183. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url']);
  4184. }
  4185. }
  4186. return $merged ?: array_values($existingItems);
  4187. }
  4188. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  4189. {
  4190. $resetItem = [
  4191. $nameKey => trim((string)getProp($item, $nameKey)),
  4192. 'description' => trim((string)getProp($item, 'description')),
  4193. ];
  4194. // 保留指定的字段
  4195. foreach ($preserveFields as $field) {
  4196. $value = getProp($item, $field);
  4197. if (!empty($value)) {
  4198. $resetItem[$field] = $value;
  4199. }
  4200. }
  4201. return $resetItem;
  4202. }
  4203. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  4204. {
  4205. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  4206. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  4207. if ($existingKey !== $generatedKey) {
  4208. return true;
  4209. }
  4210. return trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'));
  4211. }
  4212. private function normalizeEpisodeResourceKey($value): string
  4213. {
  4214. $value = trim((string)$value);
  4215. if ($value === '') {
  4216. return '';
  4217. }
  4218. return strtolower((string)preg_replace('/\s+/u', '', $value));
  4219. }
  4220. // 生成全局角色图片
  4221. private function batchSetGlobalRoleImg($data, $is_force=false) {
  4222. $anime_id = getProp($data, 'anime_id');
  4223. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4224. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4225. $roles = json_decode(getProp($anime, 'roles'), true);
  4226. $art_style = getProp($anime, 'art_style');
  4227. $update_flag = false;
  4228. foreach ($roles as &$role) {
  4229. $role_name = getProp($role, 'role');
  4230. if ($role_name == '旁白') continue;
  4231. $description = getProp($role, 'description');
  4232. if ($art_style) $description = "美术风格:\n$art_style\n主体描述:$description";
  4233. // 参考图地址
  4234. $ref_img_url = getProp($role, 'url');
  4235. if (!$is_force && $ref_img_url) continue;
  4236. $update_flag = true;
  4237. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4238. try {
  4239. $params = [
  4240. 'prompt' => $description,
  4241. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  4242. ];
  4243. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4244. $task_id = $task->id;
  4245. if (!$task_id) {
  4246. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  4247. }
  4248. $role['task_id'] = $task_id;
  4249. $role['task_status'] = 'processing';
  4250. } catch (\Exception $e) {
  4251. Utils::throwError("20003:" . $e->getMessage());
  4252. }
  4253. }
  4254. if (!$update_flag) return true;
  4255. // 保存角色信息
  4256. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4257. 'roles' => json_encode($roles, 256),
  4258. 'generate_status' => '执行中',
  4259. 'generate_at' => date('Y-m-d H:i:s'),
  4260. 'updated_at' => date('Y-m-d H:i:s')
  4261. ]);
  4262. if (!$boolen) {
  4263. Utils::throwError('20003:保存角色信息失败');
  4264. }
  4265. return $boolen;
  4266. }
  4267. // 生成全局场景图片
  4268. private function batchSetGlobalSceneImg($data, $is_force=false) {
  4269. $anime_id = getProp($data, 'anime_id');
  4270. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4271. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4272. $scenes = json_decode(getProp($anime, 'scenes'), true);
  4273. $art_style = getProp($anime, 'art_style');
  4274. $update_flag = false;
  4275. foreach ($scenes as &$scene) {
  4276. $scene_name = getProp($scene, 'scene');
  4277. $description = getProp($scene, 'description');
  4278. if ($art_style) $description = "美术风格:\n$art_style\n\n场景描述:$description";
  4279. // 参考图地址
  4280. $ref_img_url = getProp($scene, 'url');
  4281. if (!$is_force && $ref_img_url) continue;
  4282. $update_flag = true;
  4283. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4284. try {
  4285. $params = [
  4286. 'prompt' => $description,
  4287. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  4288. ];
  4289. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4290. $task_id = $task->id;
  4291. if (!$task_id) {
  4292. Utils::throwError("20003: 角色({$scene_name})生成图片失败");
  4293. }
  4294. $scene['task_id'] = $task_id;
  4295. $scene['task_status'] = 'processing';
  4296. } catch (\Exception $e) {
  4297. Utils::throwError("20003:" . $e->getMessage());
  4298. }
  4299. }
  4300. if (!$update_flag) return true;
  4301. // 保存角色信息
  4302. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4303. 'scenes' => json_encode($scenes, 256),
  4304. 'generate_status' => '执行中',
  4305. 'generate_at' => date('Y-m-d H:i:s'),
  4306. 'updated_at' => date('Y-m-d H:i:s')
  4307. ]);
  4308. if (!$boolen) {
  4309. Utils::throwError('20003:保存角色信息失败');
  4310. }
  4311. return $boolen;
  4312. }
  4313. public function chatChangeImg($data) {
  4314. $segment = getProp($data, 'segment');
  4315. $segment_content = getProp($segment, 'segment_content');
  4316. $prompt = getProp($data, 'prompt');
  4317. $ref_img = getProp($data, 'ref_img');
  4318. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  4319. // 处理文本模型
  4320. $model = getProp($data, 'model');
  4321. if (!$model) {
  4322. // 用户没有输入,从anime表获取
  4323. $segment_id = getProp($segment, 'segment_id');
  4324. if ($segment_id) {
  4325. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  4326. if ($episode_id) {
  4327. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  4328. if ($anime_id) {
  4329. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  4330. }
  4331. }
  4332. }
  4333. if (!$model) {
  4334. // anime表也没有,使用默认值
  4335. $model = 'doubao-seed-2-0-mini-260215';
  4336. }
  4337. }
  4338. // 验证模型是否在可用模型表中
  4339. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4340. $model = 'doubao-seed-2-0-mini-260215';
  4341. }
  4342. $messages[] =
  4343. [
  4344. 'role' => 'user',
  4345. 'content' => $question
  4346. ];
  4347. $post_data = [
  4348. 'model' => $model,
  4349. 'messages' => $messages,
  4350. // 'max_tokens' => 8192,
  4351. 'temperature' => 0.7,
  4352. 'frequency_penalty' => 0,
  4353. 'presence_penalty' => 0,
  4354. 'response_format' => ['type' => 'text'],
  4355. 'stream' => false // 是否启用流式输出
  4356. ];
  4357. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4358. // DeepSeek 官方模型使用 DeepSeek API
  4359. $chatResult = $this->chatOnly($post_data);
  4360. } else {
  4361. // 其他模型使用火山引擎API
  4362. $chatResult = $this->volcEngineChatCompletion($post_data);
  4363. }
  4364. if (is_array($chatResult)) {
  4365. extract($chatResult);
  4366. }else {
  4367. Utils::throwError('20003: 接口调用失败!');
  4368. }
  4369. return [
  4370. 'type' => 'done',
  4371. // 'episode' => $episode,
  4372. 'answer' => $fullContent,
  4373. 'reasoning' => $fullReasoningContent,
  4374. 'usage' => $usage
  4375. ];
  4376. }
  4377. // 仅调用deepseek对话接口
  4378. private function chatOnly($post_data) {
  4379. $client = new Client(['timeout' => 1200, 'verify' => false]);
  4380. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  4381. $response = $result->getBody()->getContents();
  4382. $response_arr = json_decode($response, true);
  4383. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  4384. $fullContent = '';
  4385. $fullReasoningContent = [];
  4386. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  4387. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  4388. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  4389. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  4390. }
  4391. return [
  4392. 'fullContent' => $fullContent,
  4393. 'fullReasoningContent' => $fullReasoningContent,
  4394. 'usage' => $usage
  4395. ];
  4396. }
  4397. private function splitContent($content) {
  4398. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  4399. $chapters = [];
  4400. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  4401. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  4402. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  4403. foreach ($matches as $match) {
  4404. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  4405. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  4406. if (!empty($title) && !empty($chapterContent)) {
  4407. $chapters[] = [
  4408. 'title' => $title,
  4409. 'content' => $chapterContent
  4410. ];
  4411. }
  4412. }
  4413. }else {
  4414. $chapters[] = [
  4415. 'title' => '',
  4416. 'content' => $content
  4417. ];
  4418. }
  4419. return $chapters;
  4420. }
  4421. public function getContentByBid($bid) {
  4422. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  4423. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  4424. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  4425. $content = '';
  4426. foreach ($chapters as $chapter) {
  4427. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  4428. }
  4429. return $content;
  4430. }
  4431. public function getContentByScriptId($script_id) {
  4432. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  4433. if (!$content) $content = '';
  4434. return $content;
  4435. }
  4436. /**
  4437. * 根据文件类型提取文本内容
  4438. *
  4439. * @param mixed $file 文件对象或文件路径
  4440. * @return string
  4441. */
  4442. public function extractFileContent($file) {
  4443. // 获取文件路径和扩展名
  4444. if (is_string($file)) {
  4445. $filePath = $file;
  4446. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  4447. } else {
  4448. // Laravel UploadedFile 对象
  4449. $filePath = $file->getRealPath();
  4450. $extension = strtolower($file->getClientOriginalExtension());
  4451. }
  4452. $content = '';
  4453. switch ($extension) {
  4454. case 'txt':
  4455. $content = $this->extractTxtContent($filePath);
  4456. break;
  4457. case 'pdf':
  4458. $content = $this->extractPdfContent($filePath);
  4459. break;
  4460. case 'doc':
  4461. case 'docx':
  4462. $content = $this->extractWordContent($filePath);
  4463. break;
  4464. // case 'jpg':
  4465. // case 'jpeg':
  4466. // case 'png':
  4467. // case 'gif':
  4468. // case 'bmp':
  4469. // case 'webp':
  4470. // $content = $this->extractImageContent($filePath);
  4471. // break;
  4472. default:
  4473. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  4474. }
  4475. return $content;
  4476. }
  4477. /**
  4478. * 提取 TXT 文件内容
  4479. */
  4480. private function extractTxtContent($filePath) {
  4481. if (!file_exists($filePath)) {
  4482. Utils::throwError('20003:文件不存在');
  4483. }
  4484. $content = file_get_contents($filePath);
  4485. // 尝试检测并转换编码
  4486. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  4487. if ($encoding && $encoding !== 'UTF-8') {
  4488. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  4489. }
  4490. return trim($content);
  4491. }
  4492. /**
  4493. * 提取 PDF 文件内容
  4494. */
  4495. private function extractPdfContent($filePath) {
  4496. if (!file_exists($filePath)) {
  4497. Utils::throwError('20003:文件不存在');
  4498. }
  4499. try {
  4500. $parser = new PdfParser();
  4501. $pdf = $parser->parseFile($filePath);
  4502. $content = $pdf->getText();
  4503. return trim($content);
  4504. } catch (\Exception $e) {
  4505. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  4506. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  4507. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  4508. }
  4509. }
  4510. /**
  4511. * 提取 Word 文件内容(支持 doc 和 docx)
  4512. */
  4513. private function extractWordContent($filePath) {
  4514. if (!file_exists($filePath)) {
  4515. Utils::throwError('20003:文件不存在');
  4516. }
  4517. try {
  4518. $phpWord = WordIOFactory::load($filePath);
  4519. $content = '';
  4520. foreach ($phpWord->getSections() as $section) {
  4521. foreach ($section->getElements() as $element) {
  4522. $content .= $this->extractWordElementText($element);
  4523. }
  4524. }
  4525. return trim($content);
  4526. } catch (\Exception $e) {
  4527. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  4528. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  4529. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  4530. }
  4531. }
  4532. /**
  4533. * 递归提取 Word 元素中的文本
  4534. */
  4535. private function extractWordElementText($element) {
  4536. $text = '';
  4537. if (method_exists($element, 'getText')) {
  4538. $text .= $element->getText() . "\n";
  4539. } elseif (method_exists($element, 'getElements')) {
  4540. foreach ($element->getElements() as $childElement) {
  4541. $text .= $this->extractWordElementText($childElement);
  4542. }
  4543. }
  4544. return $text;
  4545. }
  4546. /**
  4547. * 提取图片内容(使用火山引擎 OCR)
  4548. */
  4549. private function extractImageContent($filePath) {
  4550. if (!file_exists($filePath)) {
  4551. Utils::throwError('20003:文件不存在');
  4552. }
  4553. try {
  4554. // 读取图片并转换为 base64
  4555. $imageData = file_get_contents($filePath);
  4556. $base64Image = base64_encode($imageData);
  4557. // 调用火山引擎 OCR 服务
  4558. $content = $this->callVolcEngineOCR($base64Image);
  4559. return trim($content);
  4560. } catch (\Exception $e) {
  4561. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  4562. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  4563. Utils::throwError('20003:图片识别失败');
  4564. }
  4565. }
  4566. /**
  4567. * 调用火山引擎 OCR 服务识别图片文字
  4568. *
  4569. * @param string $base64Image base64 编码的图片数据
  4570. * @return string 识别的文字内容
  4571. */
  4572. private function callVolcEngineOCR($base64Image) {
  4573. $method = 'POST';
  4574. $service = 'cv';
  4575. $host = 'visual.volcengineapi.com';
  4576. $region = env('VOLC_REGION', 'cn-north-1');
  4577. $access_key = env('VOLC_AK');
  4578. $secret_key = env('VOLC_SK');
  4579. $action = 'OCRNormal';
  4580. $version = '2020-08-26';
  4581. if (!$access_key || !$secret_key) {
  4582. Utils::throwError('20003:请配置火山引擎 AK/SK');
  4583. }
  4584. // 请求体
  4585. $body = json_encode([
  4586. 'image_base64' => $base64Image
  4587. ]);
  4588. // 生成签名
  4589. $headers = $this->getVolcEngineSignHeaders(
  4590. $method, $service, $host, $region,
  4591. "Action={$action}&Version={$version}",
  4592. $access_key, $secret_key, $body
  4593. );
  4594. $client = new Client(['timeout' => 60, 'verify' => false]);
  4595. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  4596. 'headers' => $headers,
  4597. 'body' => $body
  4598. ]);
  4599. $response_arr = json_decode($response->getBody()->getContents(), true);
  4600. // 提取识别的文字
  4601. $textLines = [];
  4602. if (isset($response_arr['data']['line_texts'])) {
  4603. $textLines = $response_arr['data']['line_texts'];
  4604. } elseif (isset($response_arr['data']['ocr_infos'])) {
  4605. foreach ($response_arr['data']['ocr_infos'] as $info) {
  4606. if (isset($info['text'])) {
  4607. $textLines[] = $info['text'];
  4608. }
  4609. }
  4610. }
  4611. if (empty($textLines)) {
  4612. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  4613. return '';
  4614. }
  4615. return implode("\n", $textLines);
  4616. }
  4617. /**
  4618. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  4619. */
  4620. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  4621. $contentType = 'application/json';
  4622. $accept = 'application/json';
  4623. // 获取当前UTC时间
  4624. $t = new DateTime('now', new DateTimeZone('UTC'));
  4625. $xDate = $t->format('Ymd\THis\Z');
  4626. $dateStamp = $t->format('Ymd');
  4627. // 计算 body 的 sha256 哈希
  4628. $payloadHash = hash('sha256', $body);
  4629. // 1. 拼接规范请求串
  4630. $canonicalUri = '/';
  4631. $canonicalQueryString = $queryString;
  4632. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  4633. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  4634. $canonicalRequest = implode("\n", [
  4635. $method,
  4636. $canonicalUri,
  4637. $canonicalQueryString,
  4638. $canonicalHeaders,
  4639. $signedHeaders,
  4640. $payloadHash
  4641. ]);
  4642. // 2. 拼接待签名字符串
  4643. $algorithm = 'HMAC-SHA256';
  4644. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  4645. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  4646. $stringToSign = implode("\n", [
  4647. $algorithm,
  4648. $xDate,
  4649. $credentialScope,
  4650. $hashedCanonicalRequest
  4651. ]);
  4652. // 3. 计算签名
  4653. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  4654. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  4655. // 4. 添加签名到请求头
  4656. $authorizationHeader = sprintf(
  4657. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4658. $algorithm,
  4659. $access_key,
  4660. $credentialScope,
  4661. $signedHeaders,
  4662. $signature
  4663. );
  4664. return [
  4665. 'Accept' => $accept,
  4666. 'Content-Type' => $contentType,
  4667. 'Host' => $host,
  4668. 'X-Date' => $xDate,
  4669. 'X-Content-Sha256'=> $payloadHash,
  4670. 'Authorization' => $authorizationHeader
  4671. ];
  4672. }
  4673. public function generateScriptWords($cid, $model = 'r1') {
  4674. ini_set('max_execution_time', 0);
  4675. if (!$cid) Utils::throwError('20003: 请选择章节!');
  4676. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  4677. // 模型兼容性处理和思考模式设置
  4678. $thinkingMode = 'disabled';
  4679. $reasoningEffort = 'high';
  4680. if ($model == 'r1') {
  4681. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  4682. $thinkingMode = 'enabled';
  4683. } else {
  4684. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  4685. $thinkingMode = 'disabled';
  4686. }
  4687. $messages = [
  4688. [
  4689. 'role' => 'system',
  4690. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  4691. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  4692. 2.非对话部分请全部用旁白角色代替
  4693. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  4694. ],
  4695. [
  4696. 'role' => 'user',
  4697. 'content' => $content
  4698. ]
  4699. ];
  4700. $post_data = [
  4701. 'model' => $model,
  4702. 'messages' => $messages,
  4703. // 'max_tokens' => 8192,
  4704. 'temperature' => 1,
  4705. 'frequency_penalty' => 0,
  4706. 'presence_penalty' => 0,
  4707. 'thinking' => ['type' => $thinkingMode],
  4708. 'response_format' => [
  4709. 'type' => 'text'
  4710. ],
  4711. 'stream' => false
  4712. ];
  4713. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4714. // 根据模型类型选择调用方法
  4715. $fullContent = '';
  4716. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4717. // DeepSeek 官方模型使用 DeepSeek API
  4718. $chatResult = $this->chatOnly($post_data);
  4719. } else {
  4720. // 其他模型使用火山引擎API
  4721. $chatResult = $this->volcEngineChatCompletion($post_data);
  4722. }
  4723. if (is_array($chatResult)) {
  4724. $fullContent = $chatResult['fullContent'];
  4725. }
  4726. return $fullContent;
  4727. }
  4728. /**
  4729. * 智能化解析集数信息
  4730. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  4731. *
  4732. * @param string $prompt 用户输入的提示词
  4733. * @return int|null 解析出的集数,如果没有找到则返回null
  4734. */
  4735. private function extractEpisodeNumber($prompt)
  4736. {
  4737. if (empty($prompt)) {
  4738. return null;
  4739. }
  4740. // 定义各种可能的表达模式
  4741. $patterns = [
  4742. // 基本模式:改成N集、调整成N集、修改成N集
  4743. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  4744. // 扩展模式:分成N集、拆分成N集、分割成N集
  4745. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  4746. // 数量模式:N集、共N集、总共N集
  4747. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  4748. // 制作模式:制作N集、生成N集、创建N集
  4749. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  4750. // 计划模式:计划N集、预计N集、打算N集
  4751. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  4752. // 需要模式:需要N集、要N集
  4753. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  4754. // 中文数字模式:改成三集、调整成五集等
  4755. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  4756. // 英文数字模式
  4757. '/(?: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',
  4758. ];
  4759. // 中文数字转阿拉伯数字的映射
  4760. $chineseNumbers = [
  4761. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  4762. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  4763. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  4764. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  4765. ];
  4766. // 逐个尝试匹配模式
  4767. foreach ($patterns as $pattern) {
  4768. if (preg_match($pattern, $prompt, $matches)) {
  4769. $number = trim($matches[1]);
  4770. // 如果是中文数字,转换为阿拉伯数字
  4771. if (isset($chineseNumbers[$number])) {
  4772. return $chineseNumbers[$number];
  4773. }
  4774. // 如果是阿拉伯数字,直接返回
  4775. if (is_numeric($number)) {
  4776. $episodeNum = intval($number);
  4777. // 合理性检查:集数应该在1-100之间
  4778. if ($episodeNum >= 1 && $episodeNum <= 100) {
  4779. return $episodeNum;
  4780. }
  4781. }
  4782. }
  4783. }
  4784. return null;
  4785. }
  4786. /**
  4787. * 调用火山引擎对话(Chat) API
  4788. *
  4789. * @param array $params 包含以下参数:
  4790. * - model: 模型ID(必填)
  4791. * - messages: 消息列表(必填)
  4792. * - stream: 是否流式输出(可选,默认false)
  4793. * - max_tokens: 最大输出token数(可选)
  4794. * - temperature: 采样温度(可选,默认1)
  4795. * - top_p: 核采样概率(可选,默认0.7)
  4796. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  4797. * - presence_penalty: 存在惩罚系数(可选,默认0)
  4798. * - stop: 停止词(可选)
  4799. * - tools: 工具列表(可选)
  4800. * @return array|Generator 非流式返回数组,流式返回生成器
  4801. */
  4802. public function volcEngineChatCompletion(array $params)
  4803. {
  4804. $apiKey = env('VOLC_AI_API_KEY');
  4805. if (empty($apiKey)) {
  4806. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  4807. }
  4808. // 构建请求参数
  4809. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  4810. $requestData = [
  4811. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  4812. 'messages' => $params['messages'] ?? [],
  4813. ];
  4814. if (!in_array($originalModel, $this->valid_text_models)) {
  4815. Utils::throwError('20003:该模型不支持!');
  4816. }
  4817. // 添加可选参数
  4818. if (isset($params['stream'])) {
  4819. $requestData['stream'] = $params['stream'];
  4820. }
  4821. if (isset($params['stream_options'])) {
  4822. $requestData['stream_options'] = $params['stream_options'];
  4823. }
  4824. if (isset($params['max_tokens'])) {
  4825. $requestData['max_tokens'] = $params['max_tokens'];
  4826. }
  4827. if (isset($params['max_completion_tokens'])) {
  4828. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  4829. }
  4830. if (isset($params['temperature'])) {
  4831. $requestData['temperature'] = $params['temperature'];
  4832. }
  4833. if (isset($params['top_p'])) {
  4834. $requestData['top_p'] = $params['top_p'];
  4835. }
  4836. if (isset($params['frequency_penalty'])) {
  4837. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  4838. }
  4839. if (isset($params['presence_penalty'])) {
  4840. $requestData['presence_penalty'] = $params['presence_penalty'];
  4841. }
  4842. if (isset($params['stop'])) {
  4843. $requestData['stop'] = $params['stop'];
  4844. }
  4845. if (isset($params['tools'])) {
  4846. $requestData['tools'] = $params['tools'];
  4847. }
  4848. if (isset($params['tool_choice'])) {
  4849. $requestData['tool_choice'] = $params['tool_choice'];
  4850. }
  4851. if (isset($params['response_format'])) {
  4852. $requestData['response_format'] = $params['response_format'];
  4853. }
  4854. if (isset($params['thinking'])) {
  4855. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  4856. if (is_array($params['thinking'])) {
  4857. $requestData['thinking'] = $params['thinking'];
  4858. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  4859. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  4860. }
  4861. } else {
  4862. $requestData['thinking'] = ['type' => $params['thinking']];
  4863. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  4864. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  4865. }
  4866. }
  4867. } else {
  4868. $requestData['thinking'] = ['type' => 'disabled'];
  4869. }
  4870. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  4871. $client = new Client(['verify' => false, 'timeout' => 1200]);
  4872. try {
  4873. // 判断是否为流式输出
  4874. $isStream = isset($params['stream']) && $params['stream'] === true;
  4875. if ($isStream) {
  4876. // 流式输出
  4877. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  4878. } else {
  4879. // 非流式输出
  4880. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  4881. 'headers' => [
  4882. 'Authorization' => 'Bearer ' . $apiKey,
  4883. 'Content-Type' => 'application/json',
  4884. ],
  4885. 'json' => $requestData
  4886. ]);
  4887. $responseData = json_decode($response->getBody(), true);
  4888. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  4889. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  4890. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  4891. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  4892. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  4893. }
  4894. return [
  4895. 'fullContent' => $fullContent,
  4896. 'fullReasoningContent' => $fullReasoningContent,
  4897. 'usage' => $usage
  4898. ];
  4899. }
  4900. } catch (\Exception $e) {
  4901. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  4902. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  4903. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  4904. }
  4905. }
  4906. /**
  4907. * 火山引擎对话API流式输出
  4908. *
  4909. * @param Client $client HTTP客户端
  4910. * @param string $apiKey API密钥
  4911. * @param array $requestData 请求数据
  4912. * @return Generator
  4913. */
  4914. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  4915. {
  4916. try {
  4917. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  4918. 'headers' => [
  4919. 'Authorization' => 'Bearer ' . $apiKey,
  4920. 'Content-Type' => 'application/json',
  4921. ],
  4922. 'json' => $requestData,
  4923. 'stream' => true
  4924. ]);
  4925. $body = $response->getBody();
  4926. $buffer = '';
  4927. $fullContent = '';
  4928. $fullReasoningContent = '';
  4929. $usage = [];
  4930. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  4931. // 逐行读取流式响应
  4932. while (!$body->eof()) {
  4933. $chunk = $body->read(1024);
  4934. $buffer .= $chunk;
  4935. // 按行分割
  4936. $lines = explode("\n", $buffer);
  4937. $buffer = array_pop($lines);
  4938. foreach ($lines as $line) {
  4939. $line = trim($line);
  4940. if (empty($line)) {
  4941. continue;
  4942. }
  4943. // 检查是否是SSE数据行
  4944. if (strpos($line, 'data: ') !== 0) {
  4945. continue;
  4946. }
  4947. $data = substr($line, 6);
  4948. if ($data === '[DONE]') {
  4949. dLog('deepseek')->info('收到结束标记');
  4950. break 2;
  4951. }
  4952. try {
  4953. $json = json_decode($data, true);
  4954. if (json_last_error() !== JSON_ERROR_NONE) {
  4955. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  4956. continue;
  4957. }
  4958. if (isset($json['choices'][0]['delta'])) {
  4959. $delta = $json['choices'][0]['delta'];
  4960. // 处理思维链内容
  4961. if (isset($delta['reasoning_content'])) {
  4962. $fullReasoningContent .= $delta['reasoning_content'];
  4963. yield [
  4964. 'type' => 'reasoning',
  4965. 'content' => $delta['reasoning_content'],
  4966. 'full_reasoning' => $fullReasoningContent
  4967. ];
  4968. }
  4969. // 处理回答内容
  4970. if (isset($delta['content'])) {
  4971. $fullContent .= $delta['content'];
  4972. yield [
  4973. 'type' => 'content',
  4974. 'content' => $delta['content'],
  4975. ];
  4976. }
  4977. }
  4978. // 获取使用统计信息
  4979. if (isset($json['usage'])) {
  4980. $usage = $json['usage'];
  4981. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  4982. }
  4983. } catch (\Exception $e) {
  4984. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  4985. continue;
  4986. }
  4987. }
  4988. }
  4989. dLog('deepseek')->info('流式读取完成', [
  4990. 'content_length' => strlen($fullContent),
  4991. 'reasoning_length' => strlen($fullReasoningContent)
  4992. ]);
  4993. yield [
  4994. 'type' => 'done',
  4995. 'full_content' => $fullContent,
  4996. 'full_reasoning' => $fullReasoningContent,
  4997. 'usage' => $usage
  4998. ];
  4999. } catch (\Exception $e) {
  5000. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  5001. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  5002. throw $e;
  5003. }
  5004. }
  5005. /**
  5006. * 检查并创建图片生成任务
  5007. *
  5008. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  5009. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  5010. * @param string $nameKey 资源名称字段('role' 或 'scene')
  5011. * @param string $art_style 美术风格
  5012. * @return array 更新后的资源列表
  5013. */
  5014. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  5015. {
  5016. // 构建全局资源映射表,用于快速查找
  5017. $global_map = [];
  5018. foreach ($global_items as $item) {
  5019. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  5020. if ($itemKey === '') {
  5021. continue;
  5022. }
  5023. $global_map[$itemKey] = $item;
  5024. }
  5025. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  5026. foreach ($merged_items as &$item) {
  5027. $item_name = getProp($item, $nameKey);
  5028. $item_description = getProp($item, 'description');
  5029. // $item_url = getProp($item, 'url');
  5030. // // 如果已有图片URL,跳过
  5031. // if (!empty($item_url)) {
  5032. // continue;
  5033. // }
  5034. // 如果是旁白角色,跳过
  5035. if ($nameKey === 'role' && $item_name === '旁白') {
  5036. continue;
  5037. }
  5038. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  5039. if ($itemKey === '') {
  5040. continue;
  5041. }
  5042. $need_create_task = false;
  5043. // 条件1:在全局资源中找不到匹配的名称
  5044. if (!isset($global_map[$itemKey])) {
  5045. $need_create_task = true;
  5046. } else {
  5047. // 条件2:名称匹配但描述不一致
  5048. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  5049. $current_description = trim((string)$item_description);
  5050. if ($global_description !== $current_description) {
  5051. $need_create_task = true;
  5052. }
  5053. }
  5054. // 如果需要创建任务,调用图片生成服务
  5055. if ($need_create_task) {
  5056. try {
  5057. $description = $item_description;
  5058. // 添加美术风格前缀
  5059. if ($art_style) {
  5060. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  5061. $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  5062. }
  5063. $params = [
  5064. 'prompt' => $description,
  5065. 'ref_img_urls' => []
  5066. ];
  5067. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5068. $task_id = $task->id;
  5069. if ($task_id) {
  5070. $item['task_id'] = $task_id;
  5071. $item['task_status'] = 'processing';
  5072. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  5073. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  5074. }
  5075. } catch (\Exception $e) {
  5076. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  5077. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  5078. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  5079. // 不抛出异常,继续处理其他资源
  5080. }
  5081. }
  5082. }
  5083. return $merged_items;
  5084. }
  5085. /**
  5086. * 解析分镜内容的公开方法
  5087. */
  5088. public function parseSegmentContent($segment_content, $model = null) {
  5089. if (!$model) {
  5090. $model = DB::table('mp_text_models')->where('is_enabled', 1)->orderBy('id')->value('model');
  5091. if (!$model) {
  5092. return $segment_content;
  5093. }
  5094. }
  5095. // 构建系统提示词
  5096. $systemPrompt = "你是一个专业的分镜内容解析助手。请将用户提供的分镜内容解析成标准格式,包含以下字段:
  5097. 画面描述:详细描述画面内容
  5098. 构图设计:镜头构图方式
  5099. 运镜调度:摄影机运动方式
  5100. 配音角色:配音的角色名称
  5101. 台词内容:角色说的话
  5102. 画面类型:普通画面或对口型
  5103. 场景:拍摄场景
  5104. 出镜角色:画面中出现的角色
  5105. 尾帧描述:镜头结束时的画面描述
  5106. 情感:配音情感(开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦)
  5107. 性别:1(男)、2(女)、0(中性)
  5108. 语速:-50到100之间的整数
  5109. 音量:-50到100之间的整数
  5110. 情感强度:1到5之间的整数
  5111. 音调:-12到12之间的整数
  5112. 请严格按照上述格式输出,如果某个字段无法确定,请设置合理的默认值。";
  5113. // 构建消息
  5114. $messages = [
  5115. [
  5116. 'role' => 'system',
  5117. 'content' => $systemPrompt
  5118. ],
  5119. [
  5120. 'role' => 'user',
  5121. 'content' => $segment_content
  5122. ]
  5123. ];
  5124. $post_data = [
  5125. 'model' => $model,
  5126. 'messages' => $messages,
  5127. // 'max_tokens' => 2048,
  5128. 'temperature' => 0.7,
  5129. 'frequency_penalty' => 0,
  5130. 'presence_penalty' => 0,
  5131. 'response_format' => ['type' => 'text'],
  5132. 'stream' => false
  5133. ];
  5134. try {
  5135. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5136. // 使用DeepSeek API
  5137. $chatResult = $this->chatOnly($post_data);
  5138. } else {
  5139. // 使用火山引擎API
  5140. $chatResult = $this->volcEngineChatCompletion($post_data);
  5141. }
  5142. if (is_array($chatResult) && !empty($chatResult['fullContent'])) {
  5143. return $chatResult['fullContent'];
  5144. }
  5145. } catch (\Exception $e) {
  5146. dLog('deepseek')->error('解析分镜内容失败: ' . $e->getMessage());
  5147. logDB('deepseek', 'error', '解析分镜内容失败', ['error' => $e->getMessage()]);
  5148. }
  5149. return $segment_content;
  5150. }
  5151. }