DeepSeekService.php 265 KB

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