DeepSeekService.php 266 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529
  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. $exists_sequence_arr = DB::table('mp_script_episodes')->where('script_id', $script_id)->whereBetween('episode_number', [$start_episode_sequence, $end_episode_sequence])->pluck('episode_number')->toArray();
  1285. if ($exists_sequence_arr) Utils::throwError('20003:剧集 '.implode('、', $exists_sequence_arr).' 已存在,不得创建!');
  1286. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1287. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1288. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1289. if ($model === 'deepseek-chat') {
  1290. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1291. $model = 'deepseek-v4-flash';
  1292. $thinkingMode = 'disabled';
  1293. } elseif ($model === 'deepseek-reasoner') {
  1294. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1295. $model = 'deepseek-v4-flash';
  1296. $thinkingMode = 'enabled';
  1297. }
  1298. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1299. if (!$script) {
  1300. Utils::throwError('20003:剧本不存在');
  1301. }
  1302. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->first();
  1303. if (!$group) {
  1304. Utils::throwError('20003:剧本分集不存在');
  1305. }
  1306. if (!$file && !$content && !$bid) {
  1307. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1308. }
  1309. // 提取文件内容
  1310. if ($file) {
  1311. $content = $this->extractFileContent($file);
  1312. if (!$content) {
  1313. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1314. }
  1315. } elseif ($bid) {
  1316. $content = $this->getContentByBid($bid);
  1317. if (!$content) {
  1318. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1319. }
  1320. } elseif ($content) {
  1321. $content = filterContent($content);
  1322. } elseif ($prompt) {
  1323. $content = filterContent($prompt);
  1324. } else {
  1325. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1326. }
  1327. // 构建消息
  1328. $messages = [
  1329. $this->sys_message,
  1330. [
  1331. 'role' => 'user',
  1332. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1333. ]
  1334. ];
  1335. $post_data = [
  1336. 'model' => $model,
  1337. 'messages' => $messages,
  1338. // 'max_tokens' => 8192,
  1339. 'temperature' => 0.7,
  1340. 'frequency_penalty' => 0,
  1341. 'presence_penalty' => 0,
  1342. 'thinking' => ['type' => $thinkingMode],
  1343. 'response_format' => ['type' => 'text'],
  1344. 'stream' => true
  1345. ];
  1346. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1347. // 根据模型类型选择调用方法
  1348. $fullContent = '';
  1349. $fullReasoningContent = '';
  1350. $usage = [];
  1351. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1352. // DeepSeek 官方模型使用 DeepSeek API
  1353. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1354. } else {
  1355. // 其他模型使用火山引擎API
  1356. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1357. }
  1358. // 处理流式输出
  1359. foreach ($streamGenerator as $chunk) {
  1360. if (isset($chunk['type'])) {
  1361. if ($chunk['type'] === 'done') {
  1362. // 最终结果
  1363. $fullContent = $chunk['full_content'];
  1364. $fullReasoningContent = $chunk['full_reasoning'];
  1365. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1366. } else {
  1367. // 逐块yield数据
  1368. yield $chunk;
  1369. }
  1370. }
  1371. }
  1372. dLog('deepseek')->info('完整内容: '.$fullContent);
  1373. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1374. // 处理完整内容并返回最终结果
  1375. $script_arr = [];
  1376. if ($fullContent) {
  1377. $script_arr = extractScriptContent($fullContent);
  1378. }
  1379. logDB('deepseek', 'info', '解析内容', $script_arr);
  1380. if (!$script_arr['episodes']) {
  1381. yield [
  1382. 'type' => 'error',
  1383. 'script' => $script_arr,
  1384. 'msg' => '未生成剧本相关信息',
  1385. 'answer' => $fullContent,
  1386. 'reasoning' => $fullReasoningContent,
  1387. 'usage' => $usage
  1388. ];
  1389. }
  1390. try {
  1391. DB::beginTransaction();
  1392. // 返回前保存剧本内容
  1393. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1394. 'content' => $content,
  1395. 'updated_at' => date('Y-m-d H:i:s')
  1396. ]);
  1397. if (!$boolen) {
  1398. Utils::throwError('20003:保存剧本内容失败');
  1399. }
  1400. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1401. 'start_episode_number' => $start_episode_sequence,
  1402. 'end_episode_number' => $end_episode_sequence,
  1403. 'updated_at' => date('Y-m-d H:i:s')
  1404. ]);
  1405. if (!$boolen1) {
  1406. Utils::throwError('20003:保存分集失败');
  1407. }
  1408. $episodes = [];
  1409. foreach ($script_arr['episodes'] as $item) {
  1410. $episodes[] = [
  1411. 'script_id' => $script_id,
  1412. 'episode_number' => $item['episode_number'],
  1413. 'episode_name' => $item['episode_name'],
  1414. 'episode_content' => $item['episode_content'],
  1415. 'created_at' => date('Y-m-d H:i:s'),
  1416. 'updated_at' => date('Y-m-d H:i:s'),
  1417. ];
  1418. }
  1419. if ($episodes) {
  1420. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1421. if (!$boolen2) {
  1422. Utils::throwError('20003:保存分集内容失败');
  1423. }
  1424. }else {
  1425. Utils::throwError('20003:分集剧本解析失败');
  1426. }
  1427. }catch (\Exception $e) {
  1428. DB::rollBack();
  1429. Utils::throwError('20003:'.$e->getMessage());
  1430. }
  1431. DB::commit();
  1432. yield [
  1433. 'type' => 'done',
  1434. 'script' => $script_arr,
  1435. 'answer' => $fullContent,
  1436. 'reasoning' => $fullReasoningContent,
  1437. 'usage' => $usage
  1438. ];
  1439. }
  1440. /**
  1441. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1442. *
  1443. * @param array $data 包含以下参数:
  1444. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1445. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1446. * - model: 使用的模型(r1 或 v3,默认 v3)
  1447. * @return array
  1448. */
  1449. public function chatWithFile($data) {
  1450. $script_id = getProp($data, 'script_id');
  1451. $file = getProp($data, 'file');
  1452. $content = getProp($data, 'content', '');
  1453. $bid = getProp($data, 'bid', 0);
  1454. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1455. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1456. $prompt = getProp($data, 'prompt');
  1457. $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");
  1458. // 处理文本模型
  1459. $model = getProp($data, 'model');
  1460. if (!$model) {
  1461. // 用户没有输入,使用默认值
  1462. $model = 'doubao-seed-2-0-mini-260215';
  1463. }
  1464. // 验证模型是否在可用模型表中
  1465. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1466. $model = 'doubao-seed-2-0-mini-260215';
  1467. }
  1468. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1469. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1470. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1471. if ($model === 'deepseek-chat') {
  1472. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1473. $model = 'deepseek-v4-flash';
  1474. $thinkingMode = 'disabled';
  1475. } elseif ($model === 'deepseek-reasoner') {
  1476. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1477. $model = 'deepseek-v4-flash';
  1478. $thinkingMode = 'enabled';
  1479. }
  1480. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1481. if (!$script) {
  1482. Utils::throwError('20003:剧本不存在');
  1483. }
  1484. if (!$file && !$content && !$bid) {
  1485. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1486. }
  1487. // 提取文件内容
  1488. if ($file) {
  1489. $content = $this->extractFileContent($file);
  1490. if (!$content) {
  1491. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1492. }
  1493. } elseif ($bid) {
  1494. $content = $this->getContentByBid($bid);
  1495. if (!$content) {
  1496. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1497. }
  1498. } elseif ($content) {
  1499. $content = filterContent($content);
  1500. } elseif ($prompt) {
  1501. $content = filterContent($prompt);
  1502. } else {
  1503. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1504. }
  1505. // 构建消息
  1506. $messages = [
  1507. $this->sys_message,
  1508. [
  1509. 'role' => 'user',
  1510. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1511. ]
  1512. ];
  1513. $post_data = [
  1514. 'model' => $model,
  1515. 'messages' => $messages,
  1516. // 'max_tokens' => 8192,
  1517. 'temperature' => 0.7,
  1518. 'frequency_penalty' => 0,
  1519. 'presence_penalty' => 0,
  1520. 'thinking' => ['type' => $thinkingMode],
  1521. 'response_format' => ['type' => 'text'],
  1522. 'stream' => false
  1523. ];
  1524. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1525. // 根据模型类型选择调用方法
  1526. $fullContent = '';
  1527. $usage = [];
  1528. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1529. // DeepSeek 官方模型使用 DeepSeek API
  1530. $chatResult = $this->chatOnly($post_data);
  1531. } else {
  1532. // 其他模型使用火山引擎API
  1533. $chatResult = $this->volcEngineChatCompletion($post_data);
  1534. }
  1535. if (is_array($chatResult)) {
  1536. $fullContent = $chatResult['fullContent'];
  1537. $usage = $chatResult['usage'];
  1538. }
  1539. $script_arr = [];
  1540. // 处理结果
  1541. if ($fullContent) {
  1542. $script_arr = extractScriptContent($fullContent);
  1543. }
  1544. // 返回前保存剧本内容
  1545. DB::table('mp_scripts')->where('id', $script_id)->update([
  1546. 'content' => $content,
  1547. 'updated_at' => date('Y-m-d H:i:s')
  1548. ]);
  1549. return [
  1550. 'script' => $script_arr,
  1551. 'answer' => $fullContent,
  1552. 'usage' => $usage
  1553. ];
  1554. }
  1555. public function saveScript($data) {
  1556. $script_arr =getProp($data, 'script', []);
  1557. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1558. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1559. $script_id = getProp($data, 'script_id');
  1560. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1561. try {
  1562. DB::beginTransaction();
  1563. $update_data = [
  1564. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1565. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1566. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1567. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1568. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1569. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1570. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1571. 'status' => 3,
  1572. 'start_episode_sequence' => $start_episode_sequence,
  1573. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1574. 'episode_num' => count($script_arr['episodes']),
  1575. 'updated_at' => date('Y-m-d H:i:s')
  1576. ];
  1577. // 保存剧本内容
  1578. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1579. if (!$boolen) {
  1580. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1581. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  1582. Utils::throwError('20003:剧本内容保存失败');
  1583. }
  1584. // 保存分集内容
  1585. // 删除历史分集内容
  1586. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1587. $episodes = [];
  1588. $sequence = 1;
  1589. foreach ($script_arr['episodes'] as $episode) {
  1590. $segment_number = 1;
  1591. foreach($episode['segments'] as $segment) {
  1592. $episodes[] = [
  1593. 'script_id' => $script_id,
  1594. 'episode_number' => $episode['episode_number'],
  1595. 'title' => $episode['title'],
  1596. // 'content' => $episode['content'],
  1597. 'content' => '',
  1598. 'segment_number' => $segment_number,
  1599. 'segment_content' => $segment['segment_content'],
  1600. 'sequence' => $sequence,
  1601. 'created_at' => date('Y-m-d H:i:s'),
  1602. 'updated_at' => date('Y-m-d H:i:s')
  1603. ];
  1604. $sequence++;
  1605. $segment_number++;
  1606. }
  1607. }
  1608. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1609. if (!$boolen2) {
  1610. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1611. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  1612. Utils::throwError('20003:分集内容保存失败');
  1613. }
  1614. } catch (\Exception $e) {
  1615. DB::rollBack();
  1616. Utils::throwError('20003:'.$e->getMessage());
  1617. }
  1618. DB::commit();
  1619. return true;
  1620. }
  1621. public function exportScript($data) {
  1622. $filename = getProp($data, 'filename');
  1623. $script_id = getProp($data, 'script_id');
  1624. $group_id = getProp($data, 'group_id');
  1625. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1626. ->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();
  1627. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1628. $script = (array)$script;
  1629. $script['roles'] = json_decode($script['roles']);
  1630. $script['scenes'] = json_decode($script['scenes']);
  1631. $start = 1;
  1632. $end = DB::table('mp_script_episodes')->where('script_id', $script_id)->count('id');
  1633. // 获取分集组信息
  1634. if ($group_id) {
  1635. $group = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)
  1636. ->select('start_episode_number', 'end_episode_number')->first();
  1637. if (!$group) Utils::throwError('20003:分集不存在');
  1638. $start = getProp($group, 'start_episode_number');
  1639. $end = getProp($group, 'end_episode_number');
  1640. }
  1641. // 获取分集信息
  1642. $episode_list = DB::table('mp_script_episodes')->where('script_id', $script_id)->whereBetween('episode_number', [$start, $end])
  1643. ->select('episode_number', 'episode_name', 'episode_content')->orderBy('episode_number')->get()->map(function ($value) {
  1644. return (array)$value;
  1645. })->toArray();
  1646. $script['episodes'] = $episode_list;
  1647. $export_type = getProp($data, 'export_type', 'txt');
  1648. // 生成文件名
  1649. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  1650. // 根据导出类型生成不同格式的文件
  1651. switch ($export_type) {
  1652. case 'txt':
  1653. return $this->exportScriptAsTxt($script, $filename);
  1654. case 'pdf':
  1655. return $this->exportScriptAsPdf($script, $filename);
  1656. default:
  1657. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  1658. }
  1659. }
  1660. /**
  1661. * 导出剧本为TXT格式
  1662. */
  1663. private function exportScriptAsTxt($script, $filename) {
  1664. // 构建TXT内容
  1665. $content = $this->buildScriptContent($script);
  1666. // 设置响应头,直接下载
  1667. header('Content-Type: text/plain; charset=utf-8');
  1668. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  1669. header('Content-Length: ' . strlen($content));
  1670. // 输出内容并结束
  1671. echo $content;
  1672. exit();
  1673. }
  1674. /**
  1675. * 导出剧本为PDF格式
  1676. */
  1677. private function exportScriptAsPdf($script, $filename) {
  1678. // 使用HTML转PDF的方式来更好地支持中文
  1679. $htmlContent = $this->buildScriptHtmlForPdf($script);
  1680. // 创建PDF实例
  1681. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1682. // 设置文档信息
  1683. $pdf->SetCreator('剧本导出系统');
  1684. $pdf->SetAuthor('系统');
  1685. $pdf->SetTitle($script['script_name']);
  1686. $pdf->SetSubject('剧本导出');
  1687. // 设置边距
  1688. $pdf->SetMargins(15, 15, 15);
  1689. $pdf->SetAutoPageBreak(TRUE, 15);
  1690. // 添加页面
  1691. $pdf->AddPage();
  1692. // 注册并使用 simsun.ttf 字体
  1693. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  1694. // 使用HTML内容生成PDF
  1695. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  1696. // 直接输出PDF文件供下载
  1697. header('Content-Type: application/pdf');
  1698. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  1699. // 直接输出PDF内容
  1700. $pdf->Output($filename . '.pdf', 'D');
  1701. exit();
  1702. }
  1703. /**
  1704. * 构建用于PDF的HTML内容
  1705. */
  1706. private function buildScriptHtmlForPdf($script) {
  1707. $html = '<style>
  1708. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  1709. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  1710. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  1711. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  1712. .info { margin-bottom: 8px; }
  1713. .episode { margin-bottom: 20px; page-break-inside: avoid; }
  1714. .segment { margin-bottom: 10px; margin-left: 20px; }
  1715. </style>';
  1716. // 标题
  1717. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  1718. // 剧本简介
  1719. if (!empty($script['intro'])) {
  1720. $html .= '<h2>剧本简介</h2>';
  1721. $html .= '<p>' . nl2br(htmlspecialchars($script['intro'])) . '</p>';
  1722. }
  1723. // 亮点
  1724. if (!empty($script['highlights'])) {
  1725. $html .= '<h2>亮点</h2>';
  1726. $html .= '<p>' . nl2br(htmlspecialchars($script['highlights'])) . '</p>';
  1727. }
  1728. // 核心矛盾
  1729. if (!empty($script['core_contradiction'])) {
  1730. $html .= '<h2>核心矛盾</h2>';
  1731. $html .= '<p>' . nl2br(htmlspecialchars($script['core_contradiction'])) . '</p>';
  1732. }
  1733. // 艺术风格
  1734. if (!empty($script['art_style'])) {
  1735. $html .= '<h2>艺术风格</h2>';
  1736. $html .= '<p>' . nl2br(htmlspecialchars($script['art_style'])) . '</p>';
  1737. }
  1738. // 角色列表
  1739. if (!empty($script['roles']) && is_array($script['roles'])) {
  1740. $html .= '<h2>角色列表</h2>';
  1741. $html .= '<ul>';
  1742. foreach ($script['roles'] as $role) {
  1743. if (is_array($role) || is_object($role)) {
  1744. $html .= '<li>' . htmlspecialchars(getProp($role, 'role', '')) . ':' . htmlspecialchars(getProp($role, 'description', '')) . '</li>';
  1745. } else {
  1746. $html .= '<li>' . htmlspecialchars($role) . '</li>';
  1747. }
  1748. }
  1749. $html .= '</ul>';
  1750. }
  1751. // 角色关系
  1752. if (!empty($script['role_relationship'])) {
  1753. $html .= '<h2>角色关系</h2>';
  1754. $html .= '<p>' . nl2br(htmlspecialchars($script['role_relationship'])) . '</p>';
  1755. }
  1756. // 场景列表
  1757. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1758. $html .= '<h2>场景列表</h2>';
  1759. $html .= '<ul>';
  1760. foreach ($script['scenes'] as $scene) {
  1761. if (is_array($scene) || is_object($scene)) {
  1762. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene', '')) . ':' . htmlspecialchars(getProp($scene, 'description', '')) . '</li>';
  1763. } else {
  1764. $html .= '<li>' . htmlspecialchars($scene) . '</li>';
  1765. }
  1766. }
  1767. $html .= '</ul>';
  1768. }
  1769. // 分集内容
  1770. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1771. $html .= '<h2>分集内容</h2>';
  1772. foreach ($script['episodes'] as $episode) {
  1773. $html .= '<div class="episode">';
  1774. $html .= '<h3>第' . htmlspecialchars($episode['episode_number']) . '集';
  1775. if (!empty($episode['episode_name'])) {
  1776. $html .= ':' . htmlspecialchars($episode['episode_name']);
  1777. }
  1778. $html .= '</h3>';
  1779. // 处理分集内容
  1780. if (!empty($episode['episode_content'])) {
  1781. $html .= '<div class="segment">';
  1782. // 去掉第一行(标题行)
  1783. $content = $episode['episode_content'];
  1784. $lines = explode("\n", $content);
  1785. if (count($lines) > 1) {
  1786. array_shift($lines); // 移除第一行
  1787. $content = implode("\n", $lines);
  1788. } else {
  1789. $content = ''; // 如果只有一行,则清空
  1790. }
  1791. $html .= nl2br(htmlspecialchars($content));
  1792. $html .= '</div>';
  1793. }
  1794. $html .= '</div>';
  1795. }
  1796. }
  1797. return $html;
  1798. }
  1799. /**
  1800. * 构建PDF内容
  1801. */
  1802. private function buildPdfContent($pdf, $script) {
  1803. // 标题
  1804. $pdf->SetFont('dejavusans', 'B', 18);
  1805. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  1806. $pdf->Ln(5);
  1807. // 基本信息
  1808. $pdf->SetFont('dejavusans', '', 12);
  1809. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  1810. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  1811. $pdf->Ln(5);
  1812. // 剧本简介
  1813. if (!empty($script['intro'])) {
  1814. $pdf->SetFont('dejavusans', 'B', 14);
  1815. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  1816. $pdf->SetFont('dejavusans', '', 12);
  1817. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  1818. $pdf->Ln(3);
  1819. }
  1820. // 亮点
  1821. if (!empty($script['highlights'])) {
  1822. $pdf->SetFont('dejavusans', 'B', 14);
  1823. $pdf->Cell(0, 10, '亮点', 0, 1);
  1824. $pdf->SetFont('dejavusans', '', 12);
  1825. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  1826. $pdf->Ln(3);
  1827. }
  1828. // 核心矛盾
  1829. if (!empty($script['core_contradiction'])) {
  1830. $pdf->SetFont('dejavusans', 'B', 14);
  1831. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  1832. $pdf->SetFont('dejavusans', '', 12);
  1833. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  1834. $pdf->Ln(3);
  1835. }
  1836. // 艺术风格
  1837. if (!empty($script['art_style'])) {
  1838. $pdf->SetFont('dejavusans', 'B', 14);
  1839. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  1840. $pdf->SetFont('dejavusans', '', 12);
  1841. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  1842. $pdf->Ln(3);
  1843. }
  1844. // 备注
  1845. if (!empty($script['remark'])) {
  1846. $pdf->SetFont('dejavusans', 'B', 14);
  1847. $pdf->Cell(0, 10, '备注', 0, 1);
  1848. $pdf->SetFont('dejavusans', '', 12);
  1849. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  1850. $pdf->Ln(3);
  1851. }
  1852. // 角色列表
  1853. if (!empty($script['roles']) && is_array($script['roles'])) {
  1854. $pdf->SetFont('dejavusans', 'B', 14);
  1855. $pdf->Cell(0, 10, '角色列表', 0, 1);
  1856. $pdf->SetFont('dejavusans', '', 12);
  1857. foreach ($script['roles'] as $index => $role) {
  1858. if (is_array($role) || is_object($role)) {
  1859. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  1860. } else {
  1861. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  1862. }
  1863. }
  1864. $pdf->Ln(3);
  1865. }
  1866. // 角色关系
  1867. if (!empty($script['role_relationship'])) {
  1868. $pdf->SetFont('dejavusans', 'B', 14);
  1869. $pdf->Cell(0, 10, '角色关系', 0, 1);
  1870. $pdf->SetFont('dejavusans', '', 12);
  1871. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  1872. $pdf->Ln(3);
  1873. }
  1874. // 场景列表
  1875. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1876. $pdf->SetFont('dejavusans', 'B', 14);
  1877. $pdf->Cell(0, 10, '场景列表', 0, 1);
  1878. $pdf->SetFont('dejavusans', '', 12);
  1879. foreach ($script['scenes'] as $index => $scene) {
  1880. if (is_array($scene) || is_object($scene)) {
  1881. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  1882. } else {
  1883. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  1884. }
  1885. }
  1886. $pdf->Ln(5);
  1887. }
  1888. // 分集内容
  1889. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1890. $pdf->SetFont('dejavusans', 'B', 16);
  1891. $pdf->Cell(0, 12, '分集内容', 0, 1);
  1892. $pdf->Ln(3);
  1893. foreach ($script['episodes'] as $episode) {
  1894. // 检查是否需要新页面
  1895. if ($pdf->GetY() > 250) {
  1896. $pdf->AddPage();
  1897. }
  1898. $pdf->SetFont('dejavusans', 'B', 14);
  1899. $episodeTitle = '第' . $episode['episode_number'] . '集';
  1900. if (!empty($episode['title'])) {
  1901. $episodeTitle .= ':' . $episode['title'];
  1902. }
  1903. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  1904. // 处理分段内容
  1905. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1906. $pdf->SetFont('dejavusans', '', 12);
  1907. foreach ($episode['segments'] as $segment) {
  1908. if (!empty($segment['segment_content'])) {
  1909. // 如果有分段编号,显示分段标题
  1910. if (!empty($segment['segment_number'])) {
  1911. $pdf->SetFont('dejavusans', 'B', 12);
  1912. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  1913. $pdf->SetFont('dejavusans', '', 12);
  1914. }
  1915. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  1916. $pdf->Ln(2);
  1917. }
  1918. }
  1919. }
  1920. $pdf->Ln(5);
  1921. }
  1922. }
  1923. }
  1924. /**
  1925. * 构建剧本文本内容
  1926. */
  1927. private function buildScriptContent($script) {
  1928. $content = '';
  1929. // 剧本基本信息
  1930. if (!empty($script['intro'])) {
  1931. $content .= "###故事梗概\n" . $script['intro'] . "\n\n";
  1932. }
  1933. if (!empty($script['highlights'])) {
  1934. $content .= "###剧本亮点\n" . $script['highlights'] . "\n\n";
  1935. }
  1936. if (!empty($script['role_relationship'])) {
  1937. $content .= "###人物关系\n" . $script['role_relationship'] . "\n\n";
  1938. }
  1939. if (!empty($script['core_contradiction'])) {
  1940. $content .= "###核心矛盾\n" . $script['core_contradiction'] . "\n\n";
  1941. }
  1942. if (!empty($script['roles']) && is_array($script['roles'])) {
  1943. $content .= "###主体列表\n";
  1944. foreach ($script['roles'] as $role) {
  1945. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  1946. }
  1947. $content .= "\n\n";
  1948. }
  1949. if (!empty($script['art_style'])) {
  1950. $content .= "###美术风格\n" . $script['art_style'] . "\n\n";
  1951. }
  1952. // 场景信息
  1953. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1954. $content .= "###场景列表\n";
  1955. foreach ($script['scenes'] as $scene) {
  1956. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  1957. }
  1958. $content .= "\n\n";
  1959. }
  1960. // 分集内容
  1961. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1962. $content .= "###分集剧本\n";
  1963. foreach ($script['episodes'] as $episode) {
  1964. // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  1965. // if (!empty($episode['episode_name'])) {
  1966. // $content .= ":" . $episode['episode_name'];
  1967. // }
  1968. // $content .= "\n";
  1969. $content .= $episode['episode_content'] . "\n\n";
  1970. }
  1971. }
  1972. return $content;
  1973. }
  1974. /**
  1975. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1976. *
  1977. * @param array $data 包含以下参数:
  1978. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1979. * - question: 用户问题(可选)
  1980. * - model: 使用的模型(r1 或 v3,默认 v3)
  1981. * @return \Generator 返回生成器,用于流式输出
  1982. */
  1983. public function addChat($data) {
  1984. $uid = Site::getUid();
  1985. $anime_id = getProp($data, 'anime_id');
  1986. if (!$anime_id) Utils::throwError('20003:请选择对话');
  1987. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  1988. if (!$anime) Utils::throwError('20003:对话不存在');
  1989. $file = getProp($data, 'file');
  1990. $content = getProp($data, 'content', '');
  1991. $bid = getProp($data, 'bid', 0);
  1992. $script_id = getProp($data, 'script_id', 0);
  1993. $prompt = getProp($data, 'prompt');
  1994. // 处理文本模型
  1995. $model = getProp($data, 'model');
  1996. if (!$model) {
  1997. // 用户没有输入,从anime表获取
  1998. $model = getProp($anime, 'model');
  1999. if (!$model) {
  2000. // anime表也没有,使用默认值
  2001. $model = 'doubao-seed-2-0-mini-260215';
  2002. }
  2003. }
  2004. // 验证模型是否在可用模型表中
  2005. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2006. $model = 'doubao-seed-2-0-mini-260215';
  2007. }
  2008. $is_multi = getProp($anime, 'is_multi');
  2009. $is_single = (int)$is_multi !== 1;
  2010. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2011. // if (!$file && !$content && !$bid) {
  2012. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2013. // }
  2014. // 提取文件内容
  2015. if ($file) {
  2016. $content = $this->extractFileContent($file);
  2017. if (!$content) {
  2018. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2019. }
  2020. } elseif ($script_id) {
  2021. $content = $this->getContentByScriptId($script_id);
  2022. if (!$content) {
  2023. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2024. }
  2025. } elseif ($bid) {
  2026. $content = $this->getContentByBid($bid);
  2027. if (!$content) {
  2028. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2029. }
  2030. } elseif ($content) {
  2031. $content = filterContent($content);
  2032. } else {
  2033. $content = getProp($anime, 'content');
  2034. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2035. $need_generate_content = true;
  2036. }
  2037. }
  2038. // 美术风格
  2039. $input_art_style = getProp($data, 'art_style');
  2040. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2041. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2042. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2043. 中年女:邻居阿姨
  2044. 老年男:幽默大爷
  2045. 老年女:婆婆
  2046. 萌娃:奶气萌娃";
  2047. // 判断是否需要生成原文内容
  2048. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2049. // 如果需要生成原文内容,添加额外的要求
  2050. $content_generation_requirement = $need_generate_content
  2051. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2052. : "";
  2053. $systemPrompt = $is_single
  2054. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2055. 强制要求:
  2056. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2057. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2058. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2059. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2060. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2061. 普通要求:
  2062. 1.剧集标题必须与文档内容高度相关,剧集序号是1。
  2063. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2064. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2065. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2066. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2067. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2068. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2069. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2070. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2071. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2072. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2073. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2074. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2075. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2076. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2077. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2078. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2079. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2080. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2081. 示例如下:\n
  2082. ###剧本名:西昆仑
  2083. ###故事梗概
  2084. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2085. ###剧本亮点
  2086. 亮点1:绝境奇药,生死一线
  2087. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2088. 亮点2:结拜兄妹,化解尴尬
  2089. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2090. 亮点3:纤发夺命,情愫暗涌
  2091. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2092. ###人物关系
  2093. 阿雪与梁萧之间存在兄妹之情。
  2094. ###核心矛盾
  2095. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2096. ###主体列表
  2097. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2098. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2099. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2100. 阴阳球:天地异宝,能化生精气,救人于危难。
  2101. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2102. ###美术风格
  2103. 基础画风风格词:厚涂古风
  2104. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2105. ###场景列表
  2106. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2107. ###分镜剧本
  2108. ##第1幕:徐家老旧厨房 白天 室内
  2109. 分镜1
  2110. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2111. 场景:徐家老旧厨房
  2112. 构图设计:全景,低角度仰视
  2113. 运镜调度:手持拍摄
  2114. 配音角色:旁白
  2115. 出镜角色:许芸-校服装、徐母
  2116. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2117. 画面类型:普通画面
  2118. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2119. 分镜2
  2120. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2121. 场景:徐家老旧厨房
  2122. 构图设计:近景,徐母面部特写
  2123. 运镜调度:固定镜头
  2124. 配音角色:徐母
  2125. 出镜角色:徐母
  2126. 台词内容:问我夜不归宿死哪儿去了。
  2127. 画面类型:对口型
  2128. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2129. ##第2幕:徐家简陋客厅 黄昏 室内
  2130. 分镜3
  2131. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2132. 场景:徐家简陋客厅
  2133. 构图设计:全景,景深虚化
  2134. 运镜调度:固定镜头
  2135. 配音角色:旁白
  2136. 出镜角色:无
  2137. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2138. 画面类型:普通画面
  2139. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2140. 分镜4
  2141. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2142. 场景:徐家简陋客厅
  2143. 构图设计:特写,火车票
  2144. 运镜调度:固定镜头
  2145. 配音角色:旁白
  2146. 出镜角色:无
  2147. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2148. 画面类型:普通画面
  2149. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  2150. "
  2151. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2152. 强制要求:\n
  2153. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2154. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2155. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2156. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2157. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2158. 普通要求:\n
  2159. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2160. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  2161. 示例如下:\n
  2162. ###剧本名:西昆仑
  2163. ###故事梗概
  2164. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2165. ###剧本亮点
  2166. 亮点1:绝境奇药,生死一线
  2167. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2168. 亮点2:结拜兄妹,化解尴尬
  2169. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2170. 亮点3:纤发夺命,情愫暗涌
  2171. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2172. ###人物关系
  2173. 阿雪与梁萧之间存在兄妹之情。
  2174. ###核心矛盾
  2175. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2176. ###主体列表
  2177. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2178. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2179. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2180. 阴阳球:天地异宝,能化生精气,救人于危难。
  2181. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2182. ###美术风格
  2183. 基础画风风格词:厚涂古风
  2184. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2185. ###场景列表
  2186. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。";
  2187. // 构建消息
  2188. $messages = [
  2189. [
  2190. 'role' => 'system',
  2191. 'content' => $systemPrompt
  2192. ],
  2193. [
  2194. 'role' => 'user',
  2195. 'content' => "以下是文档内容:
  2196. {$content}
  2197. 用户问题:
  2198. {$question}"
  2199. ]
  2200. ];
  2201. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2202. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2203. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2204. if ($model === 'deepseek-chat') {
  2205. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2206. $model = 'deepseek-v4-flash';
  2207. $thinkingMode = 'disabled';
  2208. } elseif ($model === 'deepseek-reasoner') {
  2209. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2210. $model = 'deepseek-v4-flash';
  2211. $thinkingMode = 'enabled';
  2212. }
  2213. $post_data = [
  2214. 'model' => $model,
  2215. 'messages' => $messages,
  2216. // 'max_tokens' => 8192,
  2217. 'temperature' => 0.7,
  2218. 'frequency_penalty' => 0,
  2219. 'presence_penalty' => 0,
  2220. 'response_format' => ['type' => 'text'],
  2221. 'thinking' => ['type'=>$thinkingMode],
  2222. 'stream' => true // 启用流式输出
  2223. ];
  2224. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2225. // 根据模型类型选择调用方法
  2226. $fullContent = '';
  2227. $fullReasoningContent = '';
  2228. $usage = [];
  2229. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2230. // DeepSeek 官方模型使用 DeepSeek API
  2231. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2232. } else {
  2233. // 其他模型使用火山引擎API
  2234. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2235. }
  2236. // 处理流式输出
  2237. if (!is_iterable($streamGenerator)) {
  2238. dLog('deepseek')->error('addChat流式生成器无效', ['generator_type' => gettype($streamGenerator)]);
  2239. Utils::throwError('20003:接口返回数据异常,请重新请求');
  2240. }
  2241. foreach ($streamGenerator as $chunk) {
  2242. if (isset($chunk['type'])) {
  2243. if ($chunk['type'] === 'done') {
  2244. // 最终结果
  2245. $fullContent = $chunk['full_content'];
  2246. $fullReasoningContent = $chunk['full_reasoning'];
  2247. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2248. } else {
  2249. // 逐块yield数据
  2250. yield $chunk;
  2251. }
  2252. }
  2253. }
  2254. dLog('deepseek')->info('完整内容: '.$fullContent);
  2255. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  2256. // 处理完整内容并返回最终结果
  2257. $script_arr = [];
  2258. if ($fullContent) {
  2259. $script_arr = handleScriptContent($fullContent);
  2260. dLog('deepseek')->info('解析内容', $script_arr);
  2261. logDB('deepseek', 'info', '解析内容', $script_arr);
  2262. }
  2263. if (empty($script_arr['roles'])) {
  2264. // 未生成剧本相关内容,保存对话记录并返回提示
  2265. dLog('deepseek')->info('未生成剧本相关的内容');
  2266. try {
  2267. DB::beginTransaction();
  2268. $now = date('Y-m-d H:i:s');
  2269. // 保存对话记录
  2270. $records = [
  2271. [
  2272. 'uid' => $uid,
  2273. 'anime_id' => $anime_id,
  2274. 'sequence' => 0,
  2275. 'role' => 'user',
  2276. 'content' => "用户问题:\n
  2277. {$prompt}\n\n
  2278. 以下是文档内容:\n
  2279. {$content}",
  2280. 'created_at' => $now,
  2281. 'updated_at' => $now
  2282. ],
  2283. [
  2284. 'uid' => $uid,
  2285. 'anime_id' => $anime_id,
  2286. 'sequence' => 0,
  2287. 'role' => 'assistant',
  2288. 'content' => $fullContent,
  2289. 'created_at' => $now,
  2290. 'updated_at' => $now
  2291. ]
  2292. ];
  2293. DB::table('mp_anime_records')->insert($records);
  2294. DB::commit();
  2295. } catch (\Exception $e) {
  2296. DB::rollBack();
  2297. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2298. }
  2299. yield [
  2300. 'type' => 'done',
  2301. 'script' => [],
  2302. 'episode' => [],
  2303. 'answer' => $fullContent,
  2304. 'reasoning' => $fullReasoningContent,
  2305. 'usage' => $usage,
  2306. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  2307. ];
  2308. return;
  2309. }
  2310. // 如果需要生成原文内容,从script_arr中提取
  2311. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  2312. $content = $script_arr['content'];
  2313. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  2314. if (!$content) {
  2315. yield [
  2316. 'type' => 'done',
  2317. 'script' => [],
  2318. 'episode' => [],
  2319. 'answer' => $fullContent,
  2320. 'reasoning' => $fullReasoningContent,
  2321. 'usage' => $usage,
  2322. 'error' => '未生成剧本内容,请调整提示词再试'
  2323. ];
  2324. return;
  2325. }
  2326. }
  2327. // 替换美术风格
  2328. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2329. if ($mappedArtStyle !== '') {
  2330. $script_arr['art_style'] = $mappedArtStyle;
  2331. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2332. }
  2333. // 新建动漫
  2334. $anime_name = getProp($script_arr, 'script_name');
  2335. if (!$anime_name) {
  2336. // 未识别到剧本名,保存对话记录并返回提示
  2337. dLog('deepseek')->info('未能识别到剧本名称');
  2338. try {
  2339. DB::beginTransaction();
  2340. $now = date('Y-m-d H:i:s');
  2341. // 保存对话记录
  2342. $records = [
  2343. [
  2344. 'uid' => $uid,
  2345. 'anime_id' => $anime_id,
  2346. 'sequence' => 0,
  2347. 'role' => 'user',
  2348. 'content' => "用户问题:\n
  2349. {$prompt}\n\n
  2350. 以下是文档内容:\n
  2351. {$content}",
  2352. 'created_at' => $now,
  2353. 'updated_at' => $now
  2354. ],
  2355. [
  2356. 'uid' => $uid,
  2357. 'anime_id' => $anime_id,
  2358. 'sequence' => 0,
  2359. 'role' => 'assistant',
  2360. 'content' => $fullContent,
  2361. 'created_at' => $now,
  2362. 'updated_at' => $now
  2363. ]
  2364. ];
  2365. DB::table('mp_anime_records')->insert($records);
  2366. DB::commit();
  2367. } catch (\Exception $e) {
  2368. DB::rollBack();
  2369. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2370. }
  2371. yield [
  2372. 'type' => 'done',
  2373. 'script' => [],
  2374. 'episode' => [],
  2375. 'answer' => $fullContent,
  2376. 'reasoning' => $fullReasoningContent,
  2377. 'usage' => $usage,
  2378. 'error' => '未能识别到剧本名称,请调整提示词再试'
  2379. ];
  2380. return;
  2381. }
  2382. // 确认对话名称唯一性
  2383. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  2384. $anime_name = $anime_name . '_' . date('YmdHis');
  2385. }
  2386. $table_data = [
  2387. 'user_id' => $uid,
  2388. 'anime_name' => $anime_name,
  2389. 'model' => $model,
  2390. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2391. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2392. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2393. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2394. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2395. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2396. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2397. 'status' => '解析完成',
  2398. 'content' => $content,
  2399. 'is_multi' => $is_multi,
  2400. 'generate_status' => '待执行',
  2401. 'updated_at' => date('Y-m-d H:i:s')
  2402. ];
  2403. $single_episode = [];
  2404. try {
  2405. DB::beginTransaction();
  2406. $now = date('Y-m-d H:i:s');
  2407. // 更新动漫大纲
  2408. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2409. if (!$boolen) {
  2410. dLog('deepseek')->info('动漫保存失败', $table_data);
  2411. Utils::throwError('20003:动漫保存失败');
  2412. }
  2413. // 保存对话记录
  2414. $records = [
  2415. [
  2416. 'uid' => $uid,
  2417. 'anime_id' => $anime_id,
  2418. 'sequence' => 0,
  2419. 'role' => 'user',
  2420. 'content' => "用户问题:\n
  2421. {$prompt}\n\n
  2422. 以下是文档内容:\n
  2423. {$content}",
  2424. 'created_at' => date('Y-m-d H:i:s'),
  2425. 'updated_at' => date('Y-m-d H:i:s')
  2426. ],
  2427. [
  2428. 'uid' => $uid,
  2429. 'anime_id' => $anime_id,
  2430. 'sequence' => 0,
  2431. 'role' => 'assistant',
  2432. 'content' => $fullContent,
  2433. 'created_at' => date('Y-m-d H:i:s'),
  2434. 'updated_at' => date('Y-m-d H:i:s')
  2435. ]
  2436. ];
  2437. // 保存对话记录
  2438. $boolen3 = DB::table('mp_anime_records')->insert($records);
  2439. if (!$boolen3) {
  2440. Utils::throwError('20003:对话记录保存失败');
  2441. }
  2442. if ($is_single) {
  2443. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  2444. if (empty($episode_arr['acts'])) {
  2445. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  2446. }
  2447. $saveResult = $this->saveEpisodeVersionData(
  2448. $anime_id,
  2449. 1,
  2450. $episode_arr,
  2451. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  2452. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  2453. null,
  2454. null,
  2455. false,
  2456. $content,
  2457. $now
  2458. );
  2459. $single_episode = $saveResult['episode'];
  2460. $episode_id = $saveResult['episode_id'];
  2461. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  2462. 'roles' => json_encode($saveResult['merged_roles'], 256),
  2463. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  2464. 'updated_at' => $now
  2465. ]);
  2466. if ($boolen5 === false) {
  2467. Utils::throwError('20003:单剧集主表资源同步失败');
  2468. }
  2469. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  2470. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  2471. $episode_record_content = '确认分镜大纲';
  2472. if ($content !== '') {
  2473. $episode_record_content .= "\n\n###上传内容\n" . $content;
  2474. }
  2475. $episode_records = [
  2476. [
  2477. 'uid' => $uid,
  2478. 'anime_id' => $anime_id,
  2479. 'role' => 'user',
  2480. 'content' => $episode_record_content,
  2481. 'sequence' => 1,
  2482. 'episode_id' => $episode_id,
  2483. 'created_at' => $now,
  2484. 'updated_at' => $now
  2485. ],
  2486. [
  2487. 'uid' => $uid,
  2488. 'anime_id' => $anime_id,
  2489. 'role' => 'assistant',
  2490. 'content' => $fullContent,
  2491. 'sequence' => 1,
  2492. 'episode_id' => $episode_id,
  2493. 'created_at' => $now,
  2494. 'updated_at' => $now
  2495. ]
  2496. ];
  2497. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  2498. if (!$boolen4) {
  2499. Utils::throwError('20003:单剧集分镜记录保存失败');
  2500. }
  2501. }
  2502. }catch (\Exception $e) {
  2503. DB::rollBack();
  2504. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2505. yield [
  2506. 'type' => 'done',
  2507. 'answer' => $fullContent,
  2508. 'reasoning' => $fullReasoningContent,
  2509. 'usage' => $usage,
  2510. 'error' => $e->getMessage(),
  2511. ];
  2512. return;
  2513. }
  2514. DB::commit();
  2515. dLog('deepseek')->info('保存完毕');
  2516. if ($is_single && !empty($single_episode)) {
  2517. $this->batchSetGlobalRoleImg([
  2518. 'anime_id' => $anime_id,
  2519. ]);
  2520. $this->batchSetGlobalSceneImg([
  2521. 'anime_id' => $anime_id,
  2522. ]);
  2523. }
  2524. $table_data['anime_id'] = $anime_id;
  2525. $table_data['roles'] = json_decode($table_data['roles'], true);
  2526. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  2527. // $table_data['episodes'] = $script_arr['episodes'];
  2528. unset($table_data['created_at']);
  2529. unset($table_data['updated_at']);
  2530. unset($table_data['status']);
  2531. dLog('deepseek')->info('开始返回');
  2532. yield [
  2533. 'type' => 'done',
  2534. 'script' => $table_data,
  2535. 'episode' => $single_episode,
  2536. 'answer' => $fullContent,
  2537. 'reasoning' => $fullReasoningContent,
  2538. 'usage' => $usage
  2539. ];
  2540. }
  2541. public function reGenerateAnime($data) {
  2542. $uid = Site::getUid();
  2543. $file = getProp($data, 'file');
  2544. $content = getProp($data, 'content', '');
  2545. $bid = getProp($data, 'bid', 0);
  2546. $script_id = getProp($data, 'script_id', 0);
  2547. $anime_id = getProp($data, 'anime_id');
  2548. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  2549. if (!$anime) {
  2550. Utils::throwError('20003:该对话不存在');
  2551. }
  2552. $prompt = getProp($data, 'prompt');
  2553. // 处理文本模型
  2554. $model = getProp($data, 'model');
  2555. if (!$model) {
  2556. // 用户没有输入,从anime表获取
  2557. $model = getProp($anime, 'model');
  2558. if (!$model) {
  2559. // anime表也没有,使用默认值
  2560. $model = 'doubao-seed-2-0-mini-260215';
  2561. }
  2562. }
  2563. // 验证模型是否在可用模型表中
  2564. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2565. $model = 'doubao-seed-2-0-mini-260215';
  2566. }
  2567. $is_multi = getProp($anime, 'is_multi', 1);
  2568. $is_single = (int)$is_multi !== 1;
  2569. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  2570. if ($is_single) {
  2571. $episode_exists = DB::table('mp_anime_episodes')
  2572. ->where('anime_id', $anime_id)
  2573. ->where('sequence', 1)
  2574. ->exists();
  2575. if ($episode_exists) {
  2576. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  2577. }
  2578. }
  2579. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2580. // 提取文件内容
  2581. if ($file) {
  2582. $content = $this->extractFileContent($file);
  2583. if (!$content) {
  2584. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2585. }
  2586. } elseif ($script_id) {
  2587. $content = $this->getContentByScriptId($script_id);
  2588. if (!$content) {
  2589. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2590. }
  2591. } elseif ($bid) {
  2592. $content = $this->getContentByBid($bid);
  2593. if (!$content) {
  2594. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2595. }
  2596. } elseif ($content) {
  2597. $content = filterContent($content);
  2598. }else {
  2599. $content = filterContent(getProp($anime, 'content'));
  2600. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2601. $need_generate_content = true;
  2602. }
  2603. }
  2604. // 判断是否需要生成原文内容
  2605. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2606. // 如果需要生成原文内容,添加额外的要求
  2607. $content_generation_requirement = $need_generate_content
  2608. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2609. : "";
  2610. // 美术风格
  2611. $input_art_style = getProp($data, 'art_style');
  2612. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2613. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2614. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2615. 中年女:邻居阿姨
  2616. 老年男:幽默大爷
  2617. 老年女:婆婆
  2618. 萌娃:奶气萌娃";
  2619. $system_message = ['role'=>'system', 'content'=>$is_single
  2620. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2621. 强制要求:
  2622. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2623. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2624. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2625. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2626. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2627. 普通要求:
  2628. 1.剧集标题必须与文档内容高度相关,剧集序号是1。
  2629. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2630. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2631. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2632. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2633. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2634. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2635. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2636. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2637. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2638. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2639. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2640. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2641. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2642. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2643. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2644. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2645. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2646. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2647. 示例如下:\n
  2648. ###剧本名:西昆仑
  2649. ###故事梗概
  2650. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2651. ###剧本亮点
  2652. 亮点1:绝境奇药,生死一线
  2653. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2654. 亮点2:结拜兄妹,化解尴尬
  2655. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2656. 亮点3:纤发夺命,情愫暗涌
  2657. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2658. ###人物关系
  2659. 阿雪与梁萧之间存在兄妹之情。
  2660. ###核心矛盾
  2661. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2662. ###主体列表
  2663. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2664. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2665. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2666. 阴阳球:天地异宝,能化生精气,救人于危难。
  2667. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2668. ###美术风格
  2669. 基础画风风格词:厚涂古风
  2670. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2671. ###场景列表
  2672. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2673. ###分镜剧本
  2674. ##第1幕:徐家老旧厨房 白天 室内
  2675. 分镜1
  2676. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2677. 场景:徐家老旧厨房
  2678. 构图设计:全景,低角度仰视
  2679. 运镜调度:手持拍摄
  2680. 配音角色:旁白
  2681. 出镜角色:许芸-校服装、徐母
  2682. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2683. 画面类型:普通画面
  2684. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2685. 分镜2
  2686. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2687. 场景:徐家老旧厨房
  2688. 构图设计:近景,徐母面部特写
  2689. 运镜调度:固定镜头
  2690. 配音角色:徐母
  2691. 出镜角色:徐母
  2692. 台词内容:问我夜不归宿死哪儿去了。
  2693. 画面类型:对口型
  2694. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2695. ##第2幕:徐家简陋客厅 黄昏 室内
  2696. 分镜3
  2697. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2698. 场景:徐家简陋客厅
  2699. 构图设计:全景,景深虚化
  2700. 运镜调度:固定镜头
  2701. 配音角色:旁白
  2702. 出镜角色:无
  2703. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2704. 画面类型:普通画面
  2705. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2706. 分镜4
  2707. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2708. 场景:徐家简陋客厅
  2709. 构图设计:特写,火车票
  2710. 运镜调度:固定镜头
  2711. 配音角色:旁白
  2712. 出镜角色:无
  2713. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2714. 画面类型:普通画面
  2715. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  2716. "
  2717. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2718. 强制要求:\n
  2719. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2720. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2721. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2722. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2723. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2724. 普通要求:\n
  2725. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2726. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  2727. 示例如下:\n
  2728. ###剧本名:西昆仑
  2729. ###故事梗概
  2730. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2731. ###剧本亮点
  2732. 亮点1:绝境奇药,生死一线
  2733. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2734. 亮点2:结拜兄妹,化解尴尬
  2735. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2736. 亮点3:纤发夺命,情愫暗涌
  2737. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2738. ###人物关系
  2739. 阿雪与梁萧之间存在兄妹之情。
  2740. ###核心矛盾
  2741. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2742. ###主体列表
  2743. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2744. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2745. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2746. 阴阳球:天地异宝,能化生精气,救人于危难。
  2747. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2748. ###美术风格
  2749. 基础画风风格词:厚涂古风
  2750. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2751. ###场景列表
  2752. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"];
  2753. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  2754. $episode_count = $this->extractEpisodeNumber($prompt);
  2755. if ((int)getProp($anime, 'is_multi') !== 1) {
  2756. yield [
  2757. 'type' => 'done',
  2758. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  2759. 'reasoning' => '',
  2760. 'usage' => []
  2761. ];
  2762. return;
  2763. }
  2764. if ($episode_count) {
  2765. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  2766. $system_message = [
  2767. 'role' => 'system',
  2768. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2769. 强制要求:\n
  2770. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2771. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2772. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2773. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2774. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2775. 普通要求:\n
  2776. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2777. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  2778. 3.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  2779. 示例如下:\n
  2780. ###剧本名:西昆仑
  2781. ###故事梗概
  2782. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2783. ###剧本亮点
  2784. 亮点1:绝境奇药,生死一线
  2785. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2786. 亮点2:结拜兄妹,化解尴尬
  2787. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2788. 亮点3:纤发夺命,情愫暗涌
  2789. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2790. ###人物关系
  2791. 阿雪与梁萧之间存在兄妹之情。
  2792. ###核心矛盾
  2793. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2794. ###主体列表
  2795. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2796. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2797. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2798. 阴阳球:天地异宝,能化生精气,救人于危难。
  2799. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2800. ###美术风格
  2801. 基础画风风格词:厚涂古风
  2802. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2803. ###场景列表
  2804. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2805. ###分集详细内容
  2806. ##第1章 重生
  2807. 我重生了。
  2808. 源于一个男人偏执的暗恋。
  2809. ##第2章 相救
  2810. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  2811. 我眼睛扫向站在锅炉后的卞大伟。"
  2812. ];
  2813. // 构建消息
  2814. $messages = [
  2815. $system_message,
  2816. [
  2817. 'role' => 'user',
  2818. 'content' => "以下是文档内容:
  2819. {$content}
  2820. 用户问题:
  2821. {$question}"
  2822. ]
  2823. ];
  2824. }else {
  2825. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  2826. // 构建消息
  2827. $messages = [
  2828. $system_message,
  2829. [
  2830. 'role' => 'user',
  2831. 'content' => "以下是文档内容:
  2832. {$content}
  2833. 用户问题:
  2834. {$question}"
  2835. ]
  2836. ];
  2837. }else {
  2838. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  2839. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  2840. return (array)$value;
  2841. })->toArray();
  2842. array_unshift($messages, $system_message);
  2843. $messages[] = [
  2844. 'role' => 'user',
  2845. 'content' => $prompt
  2846. ];
  2847. }
  2848. }
  2849. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2850. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2851. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2852. if ($model === 'deepseek-chat') {
  2853. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2854. $model = 'deepseek-v4-flash';
  2855. $thinkingMode = 'disabled';
  2856. } elseif ($model === 'deepseek-reasoner') {
  2857. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2858. $model = 'deepseek-v4-flash';
  2859. $thinkingMode = 'enabled';
  2860. }
  2861. $post_data = [
  2862. 'model' => $model,
  2863. 'messages' => $messages,
  2864. // 'max_tokens' => 8192,
  2865. 'temperature' => 0.7,
  2866. 'frequency_penalty' => 0,
  2867. 'presence_penalty' => 0,
  2868. 'response_format' => ['type' => 'text'],
  2869. 'thinking' => ['type' => $thinkingMode],
  2870. 'stream' => true // 启用流式输出
  2871. ];
  2872. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2873. // 根据模型类型选择调用方法
  2874. $fullContent = '';
  2875. $fullReasoningContent = '';
  2876. $usage = [];
  2877. // dd($post_data);
  2878. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  2879. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2880. // DeepSeek 官方模型使用 DeepSeek API
  2881. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2882. } else {
  2883. // 其他模型使用火山引擎API
  2884. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2885. }
  2886. // 处理流式输出
  2887. foreach ($streamGenerator as $chunk) {
  2888. if (isset($chunk['type'])) {
  2889. if ($chunk['type'] === 'done') {
  2890. // 最终结果
  2891. $fullContent = $chunk['full_content'];
  2892. $fullReasoningContent = $chunk['full_reasoning'];
  2893. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2894. } else {
  2895. // 逐块yield数据
  2896. yield $chunk;
  2897. }
  2898. }
  2899. }
  2900. dLog('deepseek')->info('完整内容: '.$fullContent);
  2901. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  2902. // 处理完整内容并返回最终结果
  2903. $script_arr = [];
  2904. if ($fullContent) {
  2905. $script_arr = handleScriptContent($fullContent);
  2906. dLog('deepseek')->info('解析内容', $script_arr);
  2907. logDB('deepseek', 'info', '解析内容', $script_arr);
  2908. }
  2909. if (empty($script_arr['roles'])) {
  2910. // 未生成剧本相关内容,保存对话记录并返回提示
  2911. dLog('deepseek')->info('未生成剧本相关的内容');
  2912. try {
  2913. $now = date('Y-m-d H:i:s');
  2914. // 保存对话记录
  2915. $records = [
  2916. [
  2917. 'uid' => $uid,
  2918. 'anime_id' => $anime_id,
  2919. 'sequence' => 0,
  2920. 'role' => 'user',
  2921. 'content' => $prompt,
  2922. 'created_at' => $now,
  2923. 'updated_at' => $now
  2924. ],
  2925. [
  2926. 'uid' => $uid,
  2927. 'anime_id' => $anime_id,
  2928. 'sequence' => 0,
  2929. 'role' => 'assistant',
  2930. 'content' => $fullContent,
  2931. 'created_at' => $now,
  2932. 'updated_at' => $now
  2933. ]
  2934. ];
  2935. DB::table('mp_anime_records')->insert($records);
  2936. } catch (\Exception $e) {
  2937. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2938. }
  2939. yield [
  2940. 'type' => 'done',
  2941. 'script' => [],
  2942. 'episode' => [],
  2943. 'answer' => $fullContent,
  2944. 'reasoning' => $fullReasoningContent,
  2945. 'usage' => $usage,
  2946. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  2947. ];
  2948. return;
  2949. }
  2950. // 替换美术风格
  2951. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2952. if ($mappedArtStyle !== '') {
  2953. $script_arr['art_style'] = $mappedArtStyle;
  2954. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2955. }
  2956. $table_data = [
  2957. 'user_id' => $uid,
  2958. 'model' => $model,
  2959. 'anime_name' => isset($script_arr['script_name']) ? $script_arr['script_name'] : '',
  2960. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2961. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2962. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2963. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2964. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2965. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2966. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2967. 'status' => '解析完成',
  2968. 'generate_status' => '待执行',
  2969. 'updated_at' => date('Y-m-d H:i:s')
  2970. ];
  2971. // 如果是修改集数,则将content内容更新(会改变原文)
  2972. if (isset($episode_count) && $episode_count > 0) {
  2973. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  2974. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  2975. }else {
  2976. // 如果需要生成原文内容,从script_arr中提取
  2977. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  2978. $table_data['content'] = $script_arr['content'];
  2979. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  2980. if (!$content) {
  2981. yield [
  2982. 'type' => 'done',
  2983. 'script' => [],
  2984. 'episode' => [],
  2985. 'answer' => $fullContent,
  2986. 'reasoning' => $fullReasoningContent,
  2987. 'usage' => $usage,
  2988. 'error' => '未生成剧本内容,请调整提示词再试'
  2989. ];
  2990. return;
  2991. }
  2992. } else {
  2993. $chapters = $this->splitContent($content);
  2994. $chapter_count = count($chapters);
  2995. if ($chapter_count > 0) {
  2996. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  2997. }
  2998. }
  2999. }
  3000. $single_episode = [];
  3001. try {
  3002. DB::beginTransaction();
  3003. $now = date('Y-m-d H:i:s');
  3004. // 更新动漫大纲
  3005. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3006. if (!$boolen) {
  3007. dLog('deepseek')->info('对话修改失败', $table_data);
  3008. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  3009. Utils::throwError('20003:对话修改失败');
  3010. }
  3011. // 保存对话记录
  3012. $records = [
  3013. [
  3014. 'uid' => $uid,
  3015. 'anime_id' => $anime_id,
  3016. 'sequence' => 0,
  3017. 'role' => 'user',
  3018. 'content' => $prompt,
  3019. 'created_at' => $now,
  3020. 'updated_at' => $now
  3021. ],
  3022. [
  3023. 'uid' => $uid,
  3024. 'anime_id' => $anime_id,
  3025. 'sequence' => 0,
  3026. 'role' => 'assistant',
  3027. 'content' => $fullContent,
  3028. 'created_at' => $now,
  3029. 'updated_at' => $now
  3030. ]
  3031. ];
  3032. // 保存对话记录
  3033. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3034. if (!$boolen3) {
  3035. Utils::throwError('20003:对话记录保存失败');
  3036. }
  3037. // 单剧集模式:生成并保存剧集信息
  3038. if ($is_single) {
  3039. $anime_name = getProp($anime, 'anime_name', '未命名');
  3040. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3041. if (empty($episode_arr['acts'])) {
  3042. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3043. }
  3044. $saveResult = $this->saveEpisodeVersionData(
  3045. $anime_id,
  3046. 1,
  3047. $episode_arr,
  3048. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3049. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3050. null,
  3051. null,
  3052. false,
  3053. $content,
  3054. $now
  3055. );
  3056. $single_episode = $saveResult['episode'];
  3057. $episode_id = $saveResult['episode_id'];
  3058. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3059. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3060. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3061. 'updated_at' => $now
  3062. ]);
  3063. if ($boolen5 === false) {
  3064. Utils::throwError('20003:单剧集主表资源同步失败');
  3065. }
  3066. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3067. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3068. $episode_record_content = '确认分镜大纲';
  3069. if ($content !== '') {
  3070. $episode_record_content .= "\n\n###上传内容\n" . $content;
  3071. }
  3072. $episode_records = [
  3073. [
  3074. 'uid' => $uid,
  3075. 'anime_id' => $anime_id,
  3076. 'role' => 'user',
  3077. 'content' => $episode_record_content,
  3078. 'sequence' => 1,
  3079. 'episode_id' => $episode_id,
  3080. 'created_at' => $now,
  3081. 'updated_at' => $now
  3082. ],
  3083. [
  3084. 'uid' => $uid,
  3085. 'anime_id' => $anime_id,
  3086. 'role' => 'assistant',
  3087. 'content' => $fullContent,
  3088. 'sequence' => 1,
  3089. 'episode_id' => $episode_id,
  3090. 'created_at' => $now,
  3091. 'updated_at' => $now
  3092. ]
  3093. ];
  3094. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3095. if (!$boolen4) {
  3096. Utils::throwError('20003:单剧集分镜记录保存失败');
  3097. }
  3098. }
  3099. }catch (\Exception $e) {
  3100. DB::rollBack();
  3101. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  3102. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  3103. yield [
  3104. 'type' => 'done',
  3105. 'answer' => $fullContent,
  3106. 'reasoning' => $fullReasoningContent,
  3107. 'usage' => $usage,
  3108. 'error' => $e->getMessage(),
  3109. ];
  3110. return;
  3111. }
  3112. DB::commit();
  3113. dLog('deepseek')->info('保存完毕');
  3114. if ($is_single && !empty($single_episode)) {
  3115. $this->batchSetGlobalRoleImg([
  3116. 'anime_id' => $anime_id,
  3117. ]);
  3118. $this->batchSetGlobalSceneImg([
  3119. 'anime_id' => $anime_id,
  3120. ]);
  3121. }
  3122. $table_data['anime_id'] = $anime_id;
  3123. $table_data['roles'] = json_decode($table_data['roles'], true);
  3124. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3125. unset($table_data['updated_at']);
  3126. unset($table_data['status']);
  3127. yield [
  3128. 'type' => 'done',
  3129. 'script' => $table_data,
  3130. 'episode' => $single_episode,
  3131. 'answer' => $fullContent,
  3132. 'reasoning' => $fullReasoningContent,
  3133. 'usage' => $usage
  3134. ];
  3135. }
  3136. public function chat($data) {
  3137. $uid = Site::getUid();
  3138. $anime_id = getProp($data, 'anime_id');
  3139. $file = getProp($data, 'file');
  3140. $content = getProp($data, 'content', '');
  3141. $bid = getProp($data, 'bid', 0);
  3142. $script_id = getProp($data, 'script_id', 0);
  3143. $episode_number = getProp($data, 'episode_number', 1);
  3144. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3145. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3146. if (!$anime) Utils::throwError('20003:该对话不存在!');
  3147. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  3148. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  3149. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  3150. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  3151. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  3152. $roles = is_array($roles) ? $roles : [];
  3153. $scenes = is_array($scenes) ? $scenes : [];
  3154. // 转换主体列表和场景列表的格式
  3155. $roles_content = $this->buildEpisodeItemContent($roles, 'role');
  3156. $scenes_content = $this->buildEpisodeItemContent($scenes, 'scene');
  3157. // 获取音色列表
  3158. // $timbres = DB::table('mp_timbres')->select('timbre_name')->where('is_enabled', 1)->where('id', '<=', 15)->get()->map(function ($value) {
  3159. // $value = (array)$value;
  3160. // $value['timbre_name'] = str_replace('(多情感)', '', $value['timbre_name']);
  3161. // return $value;
  3162. // })->pluck('timbre_name')->toArray();
  3163. // $timbres_content = implode('、', $timbres);
  3164. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3165. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3166. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3167. 中年女:邻居阿姨
  3168. 老年男:幽默大爷
  3169. 老年女:婆婆
  3170. 萌娃:奶气萌娃";
  3171. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3172. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3173. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3174. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3175. // 提取文件内容
  3176. if ($file) {
  3177. $uploaded_content = $this->extractFileContent($file);
  3178. if (!$uploaded_content) {
  3179. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3180. }
  3181. } elseif ($script_id) {
  3182. $uploaded_content = $this->getContentByScriptId($script_id);
  3183. if (!$uploaded_content) {
  3184. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3185. }
  3186. } elseif ($bid) {
  3187. $uploaded_content = $this->getContentByBid($bid);
  3188. if (!$uploaded_content) {
  3189. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3190. }
  3191. } elseif ($content) {
  3192. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  3193. }
  3194. // elseif ($prompt) {
  3195. // $uploaded_content = filterContent($prompt);
  3196. // }
  3197. else {
  3198. $uploaded_content = '';
  3199. }
  3200. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3201. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  3202. 强制要求:
  3203. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3204. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3205. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3206. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3207. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3208. 普通要求:
  3209. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  3210. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):\n{$roles_content}。
  3211. 2.1如果分集内容中出现了<主体列表>中不存在的新主体,则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在主题列表中。
  3212. 2.2主体列表的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3213. 3.<场景列表>必须在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,除非出现<场景列表>中不存在的场景,否则不得自定义:\n{$scenes_content}。
  3214. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3215. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3216. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3217. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3218. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3219. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3220. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  3221. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3222. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3223. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3224. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3225. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3226. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3227. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3228. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3229. 示例格式:\n
  3230. 第1集:隐形的守护者
  3231. ###故事梗概
  3232. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  3233. ###美术风格
  3234. 基础画风风格词:韩漫二次元
  3235. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  3236. ###主体列表
  3237. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{{甜心小美}}
  3238. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{{爽快思思}}
  3239. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{{阳光青年}}
  3240. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。{{广州德哥}}
  3241. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。{{邻居阿姨}}
  3242. ###场景列表
  3243. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  3244. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  3245. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  3246. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  3247. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  3248. ###分镜剧本
  3249. ##第1幕:徐家老旧厨房 白天 室内
  3250. 分镜1
  3251. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3252. 场景:徐家老旧厨房
  3253. 构图设计:全景,低角度仰视
  3254. 运镜调度:手持拍摄
  3255. 配音角色:旁白
  3256. 出镜角色:许芸-校服装、徐母
  3257. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3258. 画面类型:普通画面
  3259. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3260. 分镜2
  3261. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3262. 场景:徐家老旧厨房
  3263. 构图设计:近景,徐母面部特写
  3264. 运镜调度:固定镜头
  3265. 配音角色:徐母
  3266. 出镜角色:徐母
  3267. 台词内容:问我夜不归宿死哪儿去了。
  3268. 画面类型:对口型
  3269. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3270. ##第2幕:徐家简陋客厅 黄昏 室内
  3271. 分镜3
  3272. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3273. 场景:徐家简陋客厅
  3274. 构图设计:全景,景深虚化
  3275. 运镜调度:固定镜头
  3276. 配音角色:旁白
  3277. 出镜角色:无
  3278. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3279. 画面类型:普通画面
  3280. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3281. 分镜4
  3282. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3283. 场景:徐家简陋客厅
  3284. 构图设计:特写,火车票
  3285. 运镜调度:固定镜头
  3286. 配音角色:旁白
  3287. 出镜角色:无
  3288. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3289. 画面类型:普通画面
  3290. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  3291. \n\n";
  3292. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3293. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  3294. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  3295. $prompt = $origin_prompt;
  3296. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  3297. // 获取章节内容
  3298. $full_content = getProp($anime, 'content');
  3299. // 根据章节内容拆分章节
  3300. $chapters = $this->splitContent($full_content);
  3301. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  3302. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  3303. $messages = [];
  3304. if ($prompt == '确认分镜大纲') {
  3305. $content = $uploaded_content ?: $chapter_content;
  3306. if ($is_single) $content = $full_content; // 单剧集使用全文
  3307. if (!$content) {
  3308. Utils::throwError('20003:章节内容无法获取,请确认');
  3309. }
  3310. $question = $is_single
  3311. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  3312. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  3313. // 构建消息
  3314. $messages[] =
  3315. [
  3316. 'role' => 'user',
  3317. 'content' => $question
  3318. ];
  3319. }else if ($prompt == '继续策划下一集') {
  3320. if ($is_single) {
  3321. Utils::throwError('20003:单剧集不支持继续策划下一集');
  3322. }
  3323. $content = $uploaded_content ?: $chapter_content;
  3324. if (!$content) {
  3325. Utils::throwError('20003:章节内容无法获取,请确认');
  3326. }
  3327. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  3328. // 获取上一集最后记录
  3329. $prev_sequence = $episode_number - 1;
  3330. $messages = $this->getEpisodeChatMessages($anime_id, $prev_sequence);
  3331. // 构建消息
  3332. $messages[] =
  3333. [
  3334. 'role' => 'user',
  3335. 'content' => $question
  3336. ];
  3337. }else {
  3338. $content = $uploaded_content ?: trim((string)getProp($base_episode, 'content'));
  3339. if (!$content) {
  3340. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  3341. }
  3342. if (!$content) {
  3343. Utils::throwError('20003:章节内容无法获取,请确认');
  3344. }
  3345. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  3346. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  3347. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。"
  3348. . "\n\n本次修改要求如下:\n{$origin_prompt}";
  3349. $messages[] =
  3350. [
  3351. 'role' => 'user',
  3352. 'content' => $question
  3353. ];
  3354. }
  3355. // 处理文本模型
  3356. $model = getProp($data, 'model');
  3357. if (!$model) {
  3358. // 用户没有输入,从anime表获取
  3359. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3360. $model = getProp($anime, 'model');
  3361. if (!$model) {
  3362. // anime表也没有,使用默认值
  3363. $model = 'doubao-seed-2-0-mini-260215';
  3364. }
  3365. }
  3366. // 验证模型是否在可用模型表中
  3367. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3368. $model = 'doubao-seed-2-0-mini-260215';
  3369. }
  3370. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3371. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3372. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3373. if ($model === 'deepseek-chat') {
  3374. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3375. $model = 'deepseek-v4-flash';
  3376. $thinkingMode = 'disabled';
  3377. } elseif ($model === 'deepseek-reasoner') {
  3378. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3379. $model = 'deepseek-v4-flash';
  3380. $thinkingMode = 'enabled';
  3381. }
  3382. $post_data = [
  3383. 'model' => $model,
  3384. 'messages' => $messages,
  3385. // 'max_tokens' => 8192,
  3386. 'temperature' => 0.7,
  3387. 'frequency_penalty' => 0,
  3388. 'presence_penalty' => 0,
  3389. 'response_format' => ['type' => 'text'],
  3390. 'thinking' => ['type' => $thinkingMode],
  3391. 'stream' => true // 启用流式输出
  3392. ];
  3393. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3394. // 根据模型类型选择调用方法
  3395. $fullContent = '';
  3396. $fullReasoningContent = '';
  3397. $usage = [];
  3398. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3399. // DeepSeek 官方模型使用 DeepSeek API
  3400. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3401. } else {
  3402. // 其他模型使用火山引擎API
  3403. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3404. }
  3405. // 处理流式输出
  3406. if (!is_iterable($streamGenerator)) {
  3407. dLog('deepseek')->error('chat流式生成器无效', ['generator_type' => gettype($streamGenerator)]);
  3408. Utils::throwError('20003:接口返回数据异常,请重新请求');
  3409. }
  3410. foreach ($streamGenerator as $chunk) {
  3411. if (isset($chunk['type'])) {
  3412. if ($chunk['type'] === 'done') {
  3413. // 最终结果
  3414. $fullContent = $chunk['full_content'];
  3415. $fullReasoningContent = $chunk['full_reasoning'];
  3416. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3417. } else {
  3418. // 逐块yield数据
  3419. yield $chunk;
  3420. }
  3421. }
  3422. }
  3423. dLog('deepseek')->info('完整内容: '.$fullContent);
  3424. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3425. // 处理完整内容并返回最终结果
  3426. $episode_arr = handleEpisodeContent($fullContent);
  3427. logDB('deepseek', 'info', '解析内容', $episode_arr);
  3428. if (empty($episode_arr['acts'])) {
  3429. // 未生成剧本相关内容,保存对话记录并返回提示
  3430. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  3431. try {
  3432. $now = date('Y-m-d H:i:s');
  3433. // 保存对话记录
  3434. $records = [
  3435. [
  3436. 'uid' => $uid,
  3437. 'anime_id' => $anime_id,
  3438. 'sequence' => $episode_number,
  3439. 'role' => 'user',
  3440. 'content' => $prompt,
  3441. 'created_at' => $now,
  3442. 'updated_at' => $now
  3443. ],
  3444. [
  3445. 'uid' => $uid,
  3446. 'anime_id' => $anime_id,
  3447. 'sequence' => $episode_number,
  3448. 'role' => 'assistant',
  3449. 'content' => $fullContent,
  3450. 'created_at' => $now,
  3451. 'updated_at' => $now
  3452. ]
  3453. ];
  3454. DB::table('mp_anime_records')->insert($records);
  3455. } catch (\Exception $e) {
  3456. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3457. }
  3458. yield [
  3459. 'type' => 'done',
  3460. 'episode' => [],
  3461. 'answer' => $fullContent,
  3462. 'reasoning' => $fullReasoningContent,
  3463. 'usage' => $usage,
  3464. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  3465. ];
  3466. return;
  3467. }
  3468. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3469. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3470. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3471. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3472. $now = date('Y-m-d H:i:s');
  3473. try {
  3474. DB::beginTransaction();
  3475. $saveResult = $this->saveEpisodeVersionData(
  3476. $anime_id,
  3477. $episode_number,
  3478. $episode_arr,
  3479. $existing_roles,
  3480. $existing_scenes,
  3481. $current_episode,
  3482. $base_episode,
  3483. $is_regenerate_version,
  3484. $content,
  3485. $now
  3486. );
  3487. $episode = $saveResult['episode'];
  3488. $episode_id = $saveResult['episode_id'];
  3489. $merged_roles = $saveResult['merged_roles'];
  3490. $merged_scenes = $saveResult['merged_scenes'];
  3491. $record_content = $origin_prompt;
  3492. if ($uploaded_content !== '') {
  3493. $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  3494. }
  3495. $records = [
  3496. [
  3497. 'uid' => $uid,
  3498. 'anime_id' => $anime_id,
  3499. 'role' => 'user',
  3500. 'content' => $record_content,
  3501. 'sequence' => $episode_number,
  3502. 'episode_id' => $episode_id,
  3503. 'created_at' => $now,
  3504. 'updated_at' => $now
  3505. ],
  3506. [
  3507. 'uid' => $uid,
  3508. 'anime_id' => $anime_id,
  3509. 'role' => 'assistant',
  3510. 'content' => $fullContent,
  3511. 'sequence' => $episode_number,
  3512. 'episode_id' => $episode_id,
  3513. 'created_at' => $now,
  3514. 'updated_at' => $now
  3515. ]
  3516. ];
  3517. $boolen4 = DB::table('mp_anime_records')->insert($records);
  3518. if (!$boolen4) {
  3519. Utils::throwError('20003:对话记录保存失败');
  3520. }
  3521. // 保存模型到anime表
  3522. DB::table('mp_animes')->where('id', $anime_id)->update([
  3523. 'model' => $model,
  3524. 'updated_at' => $now
  3525. ]);
  3526. }catch (\Exception $e) {
  3527. DB::rollBack();
  3528. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3529. yield [
  3530. 'type' => 'done',
  3531. 'answer' => $fullContent,
  3532. 'reasoning' => $fullReasoningContent,
  3533. 'usage' => $usage,
  3534. 'error' => $e->getMessage(),
  3535. ];
  3536. return;
  3537. }
  3538. DB::commit();
  3539. if ($is_global_generate_pics) {
  3540. // 批量生成全局角色图片
  3541. $this->batchSetGlobalRoleImg([
  3542. 'anime_id' => $anime_id,
  3543. ]);
  3544. // 批量生成全局场景图片
  3545. $this->batchSetGlobalSceneImg([
  3546. 'anime_id' => $anime_id,
  3547. ]);
  3548. }
  3549. $episode['episode_id'] = $episode_id;
  3550. $episode['roles'] = $merged_roles;
  3551. $episode['scenes'] = $merged_scenes;
  3552. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  3553. yield [
  3554. 'type' => 'done',
  3555. 'episode' => $episode,
  3556. 'answer' => $fullContent,
  3557. 'reasoning' => $fullReasoningContent,
  3558. 'usage' => $usage
  3559. ];
  3560. }
  3561. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  3562. {
  3563. $episode_arr = [
  3564. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  3565. 'intro' => getProp($script_arr, 'intro'),
  3566. 'art_style' => getProp($script_arr, 'art_style'),
  3567. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3568. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3569. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  3570. ];
  3571. if (empty($episode_arr['acts'])) {
  3572. $fallback_episode_arr = handleEpisodeContent($fullContent);
  3573. if (!empty($fallback_episode_arr['acts'])) {
  3574. $episode_arr = array_merge($fallback_episode_arr, [
  3575. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  3576. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  3577. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  3578. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  3579. ]);
  3580. }
  3581. }
  3582. // if (!getProp($episode_arr, 'episode_title')) {
  3583. // $episode_title = '';
  3584. // $episodes = getProp($script_arr, 'episodes', []);
  3585. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  3586. // $episode_title = '第1集:' . $episodes[0]['title'];
  3587. // }
  3588. // if (!$episode_title) {
  3589. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  3590. // }
  3591. // $episode_arr['episode_title'] = $episode_title;
  3592. // }
  3593. return $episode_arr;
  3594. }
  3595. private function saveEpisodeVersionData(
  3596. int $anime_id,
  3597. int $episode_number,
  3598. array $episode_arr,
  3599. array $existing_roles,
  3600. array $existing_scenes,
  3601. $current_episode,
  3602. $base_episode,
  3603. bool $is_regenerate_version,
  3604. string $content,
  3605. string $now
  3606. ): array {
  3607. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  3608. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  3609. $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  3610. $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  3611. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  3612. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3613. $global_roles = json_decode(getProp($anime, 'roles'), true);
  3614. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  3615. $global_roles = is_array($global_roles) ? $global_roles : [];
  3616. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  3617. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  3618. // 检查并创建 roles 的图片生成任务
  3619. $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  3620. // 检查并创建 scenes 的图片生成任务
  3621. $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  3622. $role_arr = [];
  3623. foreach ($merged_roles as $item) {
  3624. $role_arr[$item['role']] = $item;
  3625. }
  3626. $version_count = DB::table('mp_anime_episodes')
  3627. ->where('anime_id', $anime_id)
  3628. ->where('episode_number', $episode_number)
  3629. ->count('id');
  3630. $episode = [
  3631. 'anime_id' => $anime_id,
  3632. 'episode_number' => $episode_number,
  3633. 'title' => getProp($episode_arr, 'episode_title'),
  3634. 'content' => $content,
  3635. 'intro' => getProp($episode_arr, 'intro'),
  3636. 'art_style' => getProp($episode_arr, 'art_style'),
  3637. 'roles' => json_encode($merged_roles, 256),
  3638. 'scenes' => json_encode($merged_scenes, 256),
  3639. 'generate_status' => '待执行',
  3640. 'generate_at' => $now,
  3641. 'is_default' => 1,
  3642. 'updated_at' => $now,
  3643. ];
  3644. $del_flag = false;
  3645. if ($is_regenerate_version) {
  3646. DB::table('mp_anime_episodes')
  3647. ->where('anime_id', $anime_id)
  3648. ->where('episode_number', $episode_number)
  3649. ->update(['is_default' => 0, 'updated_at' => $now]);
  3650. $episode['sequence'] = $version_count + 1;
  3651. $episode['created_at'] = $now;
  3652. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  3653. if (!$episode_id) {
  3654. Utils::throwError('20003:创建剧集版本失败');
  3655. }
  3656. } else {
  3657. $target_episode = $current_episode ?: $base_episode;
  3658. if ($target_episode) {
  3659. $episode_id = getProp($target_episode, 'id');
  3660. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  3661. DB::table('mp_anime_episodes')
  3662. ->where('anime_id', $anime_id)
  3663. ->where('episode_number', $episode_number)
  3664. ->where('id', '<>', $episode_id)
  3665. ->update(['is_default' => 0, 'updated_at' => $now]);
  3666. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  3667. if ($boolen === false) {
  3668. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  3669. Utils::throwError('20003:分集内容保存失败');
  3670. }
  3671. $del_flag = true;
  3672. } else {
  3673. DB::table('mp_anime_episodes')
  3674. ->where('anime_id', $anime_id)
  3675. ->where('episode_number', $episode_number)
  3676. ->update(['is_default' => 0, 'updated_at' => $now]);
  3677. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  3678. $episode['created_at'] = $now;
  3679. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  3680. if (!$episode_id) {
  3681. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  3682. Utils::throwError('20003:分集内容保存失败');
  3683. }
  3684. }
  3685. }
  3686. $segments = [];
  3687. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  3688. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3689. $emotion_list = array_flip($emotion_list);
  3690. foreach ($acts as $act) {
  3691. $act_segments = getProp($act, 'segments', []);
  3692. if (!is_array($act_segments)) {
  3693. continue;
  3694. }
  3695. foreach ($act_segments as $segment) {
  3696. $voice_actor = getProp($segment, 'voice_actor');
  3697. $timbre_info = isset($role_arr[$voice_actor]) ? $role_arr[$voice_actor] : [];
  3698. $voice_type = getProp($timbre_info, 'voice_type');
  3699. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3700. if ($timbre_emotion) {
  3701. $timbre_emotion = explode(',', $timbre_emotion);
  3702. } else {
  3703. $timbre_emotion = [];
  3704. }
  3705. $emotion = getProp($segment, 'emotion', '中性');
  3706. if (!in_array($emotion, $timbre_emotion)) {
  3707. $emotion = '中性';
  3708. }
  3709. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3710. $segments[] = [
  3711. 'anime_id' => $anime_id,
  3712. 'episode_id' => $episode_id,
  3713. 'episode_number' => $episode_number,
  3714. 'act_number' => getProp($act, 'act_number'),
  3715. 'act_title' => getProp($act, 'act_title'),
  3716. 'segment_id' => getProp($segment, 'segment_id'),
  3717. 'segment_number' => getProp($segment, 'segment_number'),
  3718. 'segment_content' => getProp($segment, 'segment_content'),
  3719. 'description' => getProp($segment, 'description'),
  3720. 'composition' => getProp($segment, 'composition'),
  3721. 'camera_movement' => getProp($segment, 'camera_movement'),
  3722. 'voice_actor' => $voice_actor,
  3723. 'dialogue' => getProp($segment, 'dialogue'),
  3724. 'frame_type' => getProp($segment, 'frame_type'),
  3725. 'scene' => getProp($segment, 'scene'),
  3726. 'characters' => getProp($segment, 'characters'),
  3727. 'tail_frame' => getProp($segment, 'tail_frame'),
  3728. 'voice_name' => getProp($timbre_info, 'voice_name'),
  3729. 'voice_type' => $voice_type,
  3730. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  3731. 'emotion' => $emotion,
  3732. 'emotion_type' => $emotion_type,
  3733. 'gender' => getProp($segment, 'gender', '0'),
  3734. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  3735. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  3736. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  3737. 'pitch' => getProp($segment, 'pitch', 0),
  3738. 'created_at' => $now,
  3739. 'updated_at' => $now
  3740. ];
  3741. }
  3742. }
  3743. if ($segments) {
  3744. if ($del_flag) {
  3745. DB::table('mp_episode_segments')
  3746. ->where('anime_id', $anime_id)
  3747. ->where('episode_id', $episode_id)
  3748. ->delete();
  3749. }
  3750. $boolen = DB::table('mp_episode_segments')->insert($segments);
  3751. if (!$boolen) {
  3752. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  3753. Utils::throwError('20003:分镜内容保存失败');
  3754. }
  3755. }
  3756. $episode['episode_id'] = $episode_id;
  3757. $episode['roles'] = $merged_roles;
  3758. $episode['scenes'] = $merged_scenes;
  3759. $episode['acts'] = $acts;
  3760. return [
  3761. 'episode' => $episode,
  3762. 'episode_id' => $episode_id,
  3763. 'merged_roles' => $merged_roles,
  3764. 'merged_scenes' => $merged_scenes,
  3765. ];
  3766. }
  3767. private function buildEpisodeItemContent(array $items, string $nameKey): string
  3768. {
  3769. $content = '';
  3770. foreach ($items as $item) {
  3771. $name = trim((string)getProp($item, $nameKey));
  3772. if ($name === '') {
  3773. continue;
  3774. }
  3775. $description = trim((string)getProp($item, 'description'));
  3776. $content .= $name . ': ' . $description . "\n";
  3777. }
  3778. return trim($content);
  3779. }
  3780. private function getEpisodeChatMessages($animeId, $sequence): array
  3781. {
  3782. if ((int)$sequence <= 0) {
  3783. return [];
  3784. }
  3785. return DB::table('mp_anime_records')
  3786. ->where('anime_id', $animeId)
  3787. ->where('sequence', $sequence)
  3788. ->select('role', 'content')
  3789. ->orderBy('created_at')
  3790. ->orderBy('id')
  3791. ->get()
  3792. ->map(function ($value) {
  3793. return (array)$value;
  3794. })
  3795. ->toArray();
  3796. }
  3797. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  3798. {
  3799. $existingMap = [];
  3800. foreach ($existingItems as $item) {
  3801. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  3802. if ($itemKey === '') {
  3803. continue;
  3804. }
  3805. $existingMap[$itemKey] = $item;
  3806. }
  3807. if (!$generatedItems) {
  3808. return array_values($existingItems);
  3809. }
  3810. $merged = [];
  3811. foreach ($generatedItems as $item) {
  3812. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  3813. if ($itemKey === '') {
  3814. continue;
  3815. }
  3816. if (isset($existingMap[$itemKey])) {
  3817. if (trim((string)getProp($item, 'description')) === '') {
  3818. $merged[] = $existingMap[$itemKey];
  3819. continue;
  3820. }
  3821. // 检查内容是否发生变化
  3822. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  3823. if (!$isChanged) {
  3824. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  3825. $mergedItem = [
  3826. $nameKey => trim((string)getProp($item, $nameKey)),
  3827. 'description' => trim((string)getProp($item, 'description')),
  3828. ];
  3829. // 继承现有项的 URL
  3830. $existingUrl = getProp($existingMap[$itemKey], 'url');
  3831. if (!empty($existingUrl)) {
  3832. $mergedItem['url'] = $existingUrl;
  3833. }
  3834. // 继承现有项的 task_id
  3835. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  3836. if (!empty($existingTaskId)) {
  3837. $mergedItem['task_id'] = $existingTaskId;
  3838. }
  3839. // 继承现有项的 task_status
  3840. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  3841. if (!empty($existingTaskStatus)) {
  3842. $mergedItem['task_status'] = $existingTaskStatus;
  3843. }
  3844. // 保留生成项的音色字段
  3845. $voiceName = getProp($item, 'voice_name');
  3846. if (!empty($voiceName)) {
  3847. $mergedItem['voice_name'] = $voiceName;
  3848. }
  3849. $voiceType = getProp($item, 'voice_type');
  3850. if (!empty($voiceType)) {
  3851. $mergedItem['voice_type'] = $voiceType;
  3852. }
  3853. $audioUrl = getProp($item, 'voice_audio_url');
  3854. if (!empty($audioUrl)) {
  3855. $mergedItem['voice_audio_url'] = $audioUrl;
  3856. }
  3857. $merged[] = $mergedItem;
  3858. } else {
  3859. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  3860. $mergedItem = [
  3861. $nameKey => trim((string)getProp($item, $nameKey)),
  3862. 'description' => trim((string)getProp($item, 'description')),
  3863. ];
  3864. // 保留生成项的音色字段
  3865. $voiceName = getProp($item, 'voice_name');
  3866. if (!empty($voiceName)) {
  3867. $mergedItem['voice_name'] = $voiceName;
  3868. }
  3869. $voiceType = getProp($item, 'voice_type');
  3870. if (!empty($voiceType)) {
  3871. $mergedItem['voice_type'] = $voiceType;
  3872. }
  3873. $audioUrl = getProp($item, 'voice_audio_url');
  3874. if (!empty($audioUrl)) {
  3875. $mergedItem['voice_audio_url'] = $audioUrl;
  3876. }
  3877. // 不继承 URL、task_id 和 task_status(重置状态)
  3878. $merged[] = $mergedItem;
  3879. }
  3880. } else {
  3881. // 新增项,保留生成项的所有字段
  3882. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url']);
  3883. }
  3884. }
  3885. return $merged ?: array_values($existingItems);
  3886. }
  3887. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  3888. {
  3889. $resetItem = [
  3890. $nameKey => trim((string)getProp($item, $nameKey)),
  3891. 'description' => trim((string)getProp($item, 'description')),
  3892. ];
  3893. // 保留指定的字段
  3894. foreach ($preserveFields as $field) {
  3895. $value = getProp($item, $field);
  3896. if (!empty($value)) {
  3897. $resetItem[$field] = $value;
  3898. }
  3899. }
  3900. return $resetItem;
  3901. }
  3902. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  3903. {
  3904. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  3905. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  3906. if ($existingKey !== $generatedKey) {
  3907. return true;
  3908. }
  3909. return trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'));
  3910. }
  3911. private function normalizeEpisodeResourceKey($value): string
  3912. {
  3913. $value = trim((string)$value);
  3914. if ($value === '') {
  3915. return '';
  3916. }
  3917. return strtolower((string)preg_replace('/\s+/u', '', $value));
  3918. }
  3919. // 生成全局角色图片
  3920. private function batchSetGlobalRoleImg($data, $is_force=false) {
  3921. $anime_id = getProp($data, 'anime_id');
  3922. if (!$anime_id) Utils::throwError('1002:请选择对话');
  3923. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3924. $roles = json_decode(getProp($anime, 'roles'), true);
  3925. $art_style = getProp($anime, 'art_style');
  3926. $update_flag = false;
  3927. foreach ($roles as &$role) {
  3928. $role_name = getProp($role, 'role');
  3929. if ($role_name == '旁白') continue;
  3930. $description = getProp($role, 'description');
  3931. if ($art_style) $description = "美术风格:\n$art_style\n主体描述:$description";
  3932. // 参考图地址
  3933. $ref_img_url = getProp($role, 'url');
  3934. if (!$is_force && $ref_img_url) continue;
  3935. $update_flag = true;
  3936. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  3937. try {
  3938. $params = [
  3939. 'prompt' => $description,
  3940. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  3941. ];
  3942. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  3943. $task_id = $task->id;
  3944. if (!$task_id) {
  3945. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  3946. }
  3947. $role['task_id'] = $task_id;
  3948. $role['task_status'] = 'processing';
  3949. } catch (\Exception $e) {
  3950. Utils::throwError("20003:" . $e->getMessage());
  3951. }
  3952. }
  3953. if (!$update_flag) return true;
  3954. // 保存角色信息
  3955. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  3956. 'roles' => json_encode($roles, 256),
  3957. 'generate_status' => '执行中',
  3958. 'generate_at' => date('Y-m-d H:i:s'),
  3959. 'updated_at' => date('Y-m-d H:i:s')
  3960. ]);
  3961. if (!$boolen) {
  3962. Utils::throwError('20003:保存角色信息失败');
  3963. }
  3964. return $boolen;
  3965. }
  3966. // 生成全局场景图片
  3967. private function batchSetGlobalSceneImg($data, $is_force=false) {
  3968. $anime_id = getProp($data, 'anime_id');
  3969. if (!$anime_id) Utils::throwError('1002:请选择对话');
  3970. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3971. $scenes = json_decode(getProp($anime, 'scenes'), true);
  3972. $art_style = getProp($anime, 'art_style');
  3973. $update_flag = false;
  3974. foreach ($scenes as &$scene) {
  3975. $scene_name = getProp($scene, 'scene');
  3976. $description = getProp($scene, 'description');
  3977. if ($art_style) $description = "美术风格:\n$art_style\n\n场景描述:$description";
  3978. // 参考图地址
  3979. $ref_img_url = getProp($scene, 'url');
  3980. if (!$is_force && $ref_img_url) continue;
  3981. $update_flag = true;
  3982. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  3983. try {
  3984. $params = [
  3985. 'prompt' => $description,
  3986. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  3987. ];
  3988. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  3989. $task_id = $task->id;
  3990. if (!$task_id) {
  3991. Utils::throwError("20003: 角色({$scene_name})生成图片失败");
  3992. }
  3993. $scene['task_id'] = $task_id;
  3994. $scene['task_status'] = 'processing';
  3995. } catch (\Exception $e) {
  3996. Utils::throwError("20003:" . $e->getMessage());
  3997. }
  3998. }
  3999. if (!$update_flag) return true;
  4000. // 保存角色信息
  4001. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4002. 'scenes' => json_encode($scenes, 256),
  4003. 'generate_status' => '执行中',
  4004. 'generate_at' => date('Y-m-d H:i:s'),
  4005. 'updated_at' => date('Y-m-d H:i:s')
  4006. ]);
  4007. if (!$boolen) {
  4008. Utils::throwError('20003:保存角色信息失败');
  4009. }
  4010. return $boolen;
  4011. }
  4012. public function chatChangeImg($data) {
  4013. $segment = getProp($data, 'segment');
  4014. $segment_content = getProp($segment, 'segment_content');
  4015. $prompt = getProp($data, 'prompt');
  4016. $ref_img = getProp($data, 'ref_img');
  4017. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  4018. // 处理文本模型
  4019. $model = getProp($data, 'model');
  4020. if (!$model) {
  4021. // 用户没有输入,从anime表获取
  4022. $segment_id = getProp($segment, 'segment_id');
  4023. if ($segment_id) {
  4024. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  4025. if ($episode_id) {
  4026. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  4027. if ($anime_id) {
  4028. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  4029. }
  4030. }
  4031. }
  4032. if (!$model) {
  4033. // anime表也没有,使用默认值
  4034. $model = 'doubao-seed-2-0-mini-260215';
  4035. }
  4036. }
  4037. // 验证模型是否在可用模型表中
  4038. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4039. $model = 'doubao-seed-2-0-mini-260215';
  4040. }
  4041. $messages[] =
  4042. [
  4043. 'role' => 'user',
  4044. 'content' => $question
  4045. ];
  4046. $post_data = [
  4047. 'model' => $model,
  4048. 'messages' => $messages,
  4049. // 'max_tokens' => 8192,
  4050. 'temperature' => 0.7,
  4051. 'frequency_penalty' => 0,
  4052. 'presence_penalty' => 0,
  4053. 'response_format' => ['type' => 'text'],
  4054. 'stream' => false // 是否启用流式输出
  4055. ];
  4056. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4057. // DeepSeek 官方模型使用 DeepSeek API
  4058. $chatResult = $this->chatOnly($post_data);
  4059. } else {
  4060. // 其他模型使用火山引擎API
  4061. $chatResult = $this->volcEngineChatCompletion($post_data);
  4062. }
  4063. if (is_array($chatResult)) {
  4064. extract($chatResult);
  4065. }else {
  4066. Utils::throwError('20003: 接口调用失败!');
  4067. }
  4068. return [
  4069. 'type' => 'done',
  4070. // 'episode' => $episode,
  4071. 'answer' => $fullContent,
  4072. 'reasoning' => $fullReasoningContent,
  4073. 'usage' => $usage
  4074. ];
  4075. }
  4076. // 仅调用deepseek对话接口
  4077. private function chatOnly($post_data) {
  4078. $client = new Client(['timeout' => 1200, 'verify' => false]);
  4079. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  4080. $response = $result->getBody()->getContents();
  4081. $response_arr = json_decode($response, true);
  4082. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  4083. $fullContent = '';
  4084. $fullReasoningContent = [];
  4085. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  4086. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  4087. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  4088. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  4089. }
  4090. return [
  4091. 'fullContent' => $fullContent,
  4092. 'fullReasoningContent' => $fullReasoningContent,
  4093. 'usage' => $usage
  4094. ];
  4095. }
  4096. private function splitContent($content) {
  4097. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  4098. $chapters = [];
  4099. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  4100. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  4101. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  4102. foreach ($matches as $match) {
  4103. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  4104. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  4105. if (!empty($title) && !empty($chapterContent)) {
  4106. $chapters[] = [
  4107. 'title' => $title,
  4108. 'content' => $chapterContent
  4109. ];
  4110. }
  4111. }
  4112. }else {
  4113. $chapters[] = [
  4114. 'title' => '',
  4115. 'content' => $content
  4116. ];
  4117. }
  4118. return $chapters;
  4119. }
  4120. public function getContentByBid($bid) {
  4121. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  4122. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  4123. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  4124. $content = '';
  4125. foreach ($chapters as $chapter) {
  4126. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  4127. }
  4128. return $content;
  4129. }
  4130. public function getContentByScriptId($script_id) {
  4131. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  4132. if (!$content) $content = '';
  4133. return $content;
  4134. }
  4135. /**
  4136. * 根据文件类型提取文本内容
  4137. *
  4138. * @param mixed $file 文件对象或文件路径
  4139. * @return string
  4140. */
  4141. public function extractFileContent($file) {
  4142. // 获取文件路径和扩展名
  4143. if (is_string($file)) {
  4144. $filePath = $file;
  4145. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  4146. } else {
  4147. // Laravel UploadedFile 对象
  4148. $filePath = $file->getRealPath();
  4149. $extension = strtolower($file->getClientOriginalExtension());
  4150. }
  4151. $content = '';
  4152. switch ($extension) {
  4153. case 'txt':
  4154. $content = $this->extractTxtContent($filePath);
  4155. break;
  4156. case 'pdf':
  4157. $content = $this->extractPdfContent($filePath);
  4158. break;
  4159. case 'doc':
  4160. case 'docx':
  4161. $content = $this->extractWordContent($filePath);
  4162. break;
  4163. // case 'jpg':
  4164. // case 'jpeg':
  4165. // case 'png':
  4166. // case 'gif':
  4167. // case 'bmp':
  4168. // case 'webp':
  4169. // $content = $this->extractImageContent($filePath);
  4170. // break;
  4171. default:
  4172. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  4173. }
  4174. return $content;
  4175. }
  4176. /**
  4177. * 提取 TXT 文件内容
  4178. */
  4179. private function extractTxtContent($filePath) {
  4180. if (!file_exists($filePath)) {
  4181. Utils::throwError('20003:文件不存在');
  4182. }
  4183. $content = file_get_contents($filePath);
  4184. // 尝试检测并转换编码
  4185. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  4186. if ($encoding && $encoding !== 'UTF-8') {
  4187. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  4188. }
  4189. return trim($content);
  4190. }
  4191. /**
  4192. * 提取 PDF 文件内容
  4193. */
  4194. private function extractPdfContent($filePath) {
  4195. if (!file_exists($filePath)) {
  4196. Utils::throwError('20003:文件不存在');
  4197. }
  4198. try {
  4199. $parser = new PdfParser();
  4200. $pdf = $parser->parseFile($filePath);
  4201. $content = $pdf->getText();
  4202. return trim($content);
  4203. } catch (\Exception $e) {
  4204. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  4205. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  4206. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  4207. }
  4208. }
  4209. /**
  4210. * 提取 Word 文件内容(支持 doc 和 docx)
  4211. */
  4212. private function extractWordContent($filePath) {
  4213. if (!file_exists($filePath)) {
  4214. Utils::throwError('20003:文件不存在');
  4215. }
  4216. try {
  4217. $phpWord = WordIOFactory::load($filePath);
  4218. $content = '';
  4219. foreach ($phpWord->getSections() as $section) {
  4220. foreach ($section->getElements() as $element) {
  4221. $content .= $this->extractWordElementText($element);
  4222. }
  4223. }
  4224. return trim($content);
  4225. } catch (\Exception $e) {
  4226. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  4227. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  4228. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  4229. }
  4230. }
  4231. /**
  4232. * 递归提取 Word 元素中的文本
  4233. */
  4234. private function extractWordElementText($element) {
  4235. $text = '';
  4236. if (method_exists($element, 'getText')) {
  4237. $text .= $element->getText() . "\n";
  4238. } elseif (method_exists($element, 'getElements')) {
  4239. foreach ($element->getElements() as $childElement) {
  4240. $text .= $this->extractWordElementText($childElement);
  4241. }
  4242. }
  4243. return $text;
  4244. }
  4245. /**
  4246. * 提取图片内容(使用火山引擎 OCR)
  4247. */
  4248. private function extractImageContent($filePath) {
  4249. if (!file_exists($filePath)) {
  4250. Utils::throwError('20003:文件不存在');
  4251. }
  4252. try {
  4253. // 读取图片并转换为 base64
  4254. $imageData = file_get_contents($filePath);
  4255. $base64Image = base64_encode($imageData);
  4256. // 调用火山引擎 OCR 服务
  4257. $content = $this->callVolcEngineOCR($base64Image);
  4258. return trim($content);
  4259. } catch (\Exception $e) {
  4260. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  4261. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  4262. Utils::throwError('20003:图片识别失败');
  4263. }
  4264. }
  4265. /**
  4266. * 调用火山引擎 OCR 服务识别图片文字
  4267. *
  4268. * @param string $base64Image base64 编码的图片数据
  4269. * @return string 识别的文字内容
  4270. */
  4271. private function callVolcEngineOCR($base64Image) {
  4272. $method = 'POST';
  4273. $service = 'cv';
  4274. $host = 'visual.volcengineapi.com';
  4275. $region = env('VOLC_REGION', 'cn-north-1');
  4276. $access_key = env('VOLC_AK');
  4277. $secret_key = env('VOLC_SK');
  4278. $action = 'OCRNormal';
  4279. $version = '2020-08-26';
  4280. if (!$access_key || !$secret_key) {
  4281. Utils::throwError('20003:请配置火山引擎 AK/SK');
  4282. }
  4283. // 请求体
  4284. $body = json_encode([
  4285. 'image_base64' => $base64Image
  4286. ]);
  4287. // 生成签名
  4288. $headers = $this->getVolcEngineSignHeaders(
  4289. $method, $service, $host, $region,
  4290. "Action={$action}&Version={$version}",
  4291. $access_key, $secret_key, $body
  4292. );
  4293. $client = new Client(['timeout' => 60, 'verify' => false]);
  4294. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  4295. 'headers' => $headers,
  4296. 'body' => $body
  4297. ]);
  4298. $response_arr = json_decode($response->getBody()->getContents(), true);
  4299. // 提取识别的文字
  4300. $textLines = [];
  4301. if (isset($response_arr['data']['line_texts'])) {
  4302. $textLines = $response_arr['data']['line_texts'];
  4303. } elseif (isset($response_arr['data']['ocr_infos'])) {
  4304. foreach ($response_arr['data']['ocr_infos'] as $info) {
  4305. if (isset($info['text'])) {
  4306. $textLines[] = $info['text'];
  4307. }
  4308. }
  4309. }
  4310. if (empty($textLines)) {
  4311. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  4312. return '';
  4313. }
  4314. return implode("\n", $textLines);
  4315. }
  4316. /**
  4317. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  4318. */
  4319. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  4320. $contentType = 'application/json';
  4321. $accept = 'application/json';
  4322. // 获取当前UTC时间
  4323. $t = new DateTime('now', new DateTimeZone('UTC'));
  4324. $xDate = $t->format('Ymd\THis\Z');
  4325. $dateStamp = $t->format('Ymd');
  4326. // 计算 body 的 sha256 哈希
  4327. $payloadHash = hash('sha256', $body);
  4328. // 1. 拼接规范请求串
  4329. $canonicalUri = '/';
  4330. $canonicalQueryString = $queryString;
  4331. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  4332. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  4333. $canonicalRequest = implode("\n", [
  4334. $method,
  4335. $canonicalUri,
  4336. $canonicalQueryString,
  4337. $canonicalHeaders,
  4338. $signedHeaders,
  4339. $payloadHash
  4340. ]);
  4341. // 2. 拼接待签名字符串
  4342. $algorithm = 'HMAC-SHA256';
  4343. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  4344. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  4345. $stringToSign = implode("\n", [
  4346. $algorithm,
  4347. $xDate,
  4348. $credentialScope,
  4349. $hashedCanonicalRequest
  4350. ]);
  4351. // 3. 计算签名
  4352. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  4353. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  4354. // 4. 添加签名到请求头
  4355. $authorizationHeader = sprintf(
  4356. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4357. $algorithm,
  4358. $access_key,
  4359. $credentialScope,
  4360. $signedHeaders,
  4361. $signature
  4362. );
  4363. return [
  4364. 'Accept' => $accept,
  4365. 'Content-Type' => $contentType,
  4366. 'Host' => $host,
  4367. 'X-Date' => $xDate,
  4368. 'X-Content-Sha256'=> $payloadHash,
  4369. 'Authorization' => $authorizationHeader
  4370. ];
  4371. }
  4372. public function generateScriptWords($cid, $model = 'r1') {
  4373. ini_set('max_execution_time', 0);
  4374. if (!$cid) Utils::throwError('20003: 请选择章节!');
  4375. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  4376. // 模型兼容性处理和思考模式设置
  4377. $thinkingMode = 'disabled';
  4378. $reasoningEffort = 'high';
  4379. if ($model == 'r1') {
  4380. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  4381. $thinkingMode = 'enabled';
  4382. } else {
  4383. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  4384. $thinkingMode = 'disabled';
  4385. }
  4386. $messages = [
  4387. [
  4388. 'role' => 'system',
  4389. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  4390. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  4391. 2.非对话部分请全部用旁白角色代替
  4392. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  4393. ],
  4394. [
  4395. 'role' => 'user',
  4396. 'content' => $content
  4397. ]
  4398. ];
  4399. $post_data = [
  4400. 'model' => $model,
  4401. 'messages' => $messages,
  4402. // 'max_tokens' => 8192,
  4403. 'temperature' => 1,
  4404. 'frequency_penalty' => 0,
  4405. 'presence_penalty' => 0,
  4406. 'thinking' => ['type' => $thinkingMode],
  4407. 'response_format' => [
  4408. 'type' => 'text'
  4409. ],
  4410. 'stream' => false
  4411. ];
  4412. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4413. // 根据模型类型选择调用方法
  4414. $fullContent = '';
  4415. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4416. // DeepSeek 官方模型使用 DeepSeek API
  4417. $chatResult = $this->chatOnly($post_data);
  4418. } else {
  4419. // 其他模型使用火山引擎API
  4420. $chatResult = $this->volcEngineChatCompletion($post_data);
  4421. }
  4422. if (is_array($chatResult)) {
  4423. $fullContent = $chatResult['fullContent'];
  4424. }
  4425. return $fullContent;
  4426. }
  4427. /**
  4428. * 智能化解析集数信息
  4429. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  4430. *
  4431. * @param string $prompt 用户输入的提示词
  4432. * @return int|null 解析出的集数,如果没有找到则返回null
  4433. */
  4434. private function extractEpisodeNumber($prompt)
  4435. {
  4436. if (empty($prompt)) {
  4437. return null;
  4438. }
  4439. // 定义各种可能的表达模式
  4440. $patterns = [
  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集、打算N集
  4450. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  4451. // 需要模式:需要N集、要N集
  4452. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  4453. // 中文数字模式:改成三集、调整成五集等
  4454. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  4455. // 英文数字模式
  4456. '/(?: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',
  4457. ];
  4458. // 中文数字转阿拉伯数字的映射
  4459. $chineseNumbers = [
  4460. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  4461. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  4462. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  4463. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  4464. ];
  4465. // 逐个尝试匹配模式
  4466. foreach ($patterns as $pattern) {
  4467. if (preg_match($pattern, $prompt, $matches)) {
  4468. $number = trim($matches[1]);
  4469. // 如果是中文数字,转换为阿拉伯数字
  4470. if (isset($chineseNumbers[$number])) {
  4471. return $chineseNumbers[$number];
  4472. }
  4473. // 如果是阿拉伯数字,直接返回
  4474. if (is_numeric($number)) {
  4475. $episodeNum = intval($number);
  4476. // 合理性检查:集数应该在1-100之间
  4477. if ($episodeNum >= 1 && $episodeNum <= 100) {
  4478. return $episodeNum;
  4479. }
  4480. }
  4481. }
  4482. }
  4483. return null;
  4484. }
  4485. /**
  4486. * 调用火山引擎对话(Chat) API
  4487. *
  4488. * @param array $params 包含以下参数:
  4489. * - model: 模型ID(必填)
  4490. * - messages: 消息列表(必填)
  4491. * - stream: 是否流式输出(可选,默认false)
  4492. * - max_tokens: 最大输出token数(可选)
  4493. * - temperature: 采样温度(可选,默认1)
  4494. * - top_p: 核采样概率(可选,默认0.7)
  4495. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  4496. * - presence_penalty: 存在惩罚系数(可选,默认0)
  4497. * - stop: 停止词(可选)
  4498. * - tools: 工具列表(可选)
  4499. * @return array|Generator 非流式返回数组,流式返回生成器
  4500. */
  4501. public function volcEngineChatCompletion(array $params)
  4502. {
  4503. $apiKey = env('VOLC_AI_API_KEY');
  4504. if (empty($apiKey)) {
  4505. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  4506. }
  4507. // 构建请求参数
  4508. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  4509. $requestData = [
  4510. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  4511. 'messages' => $params['messages'] ?? [],
  4512. ];
  4513. if (!in_array($originalModel, $this->valid_text_models)) {
  4514. Utils::throwError('20003:该模型不支持!');
  4515. }
  4516. // 添加可选参数
  4517. if (isset($params['stream'])) {
  4518. $requestData['stream'] = $params['stream'];
  4519. }
  4520. if (isset($params['stream_options'])) {
  4521. $requestData['stream_options'] = $params['stream_options'];
  4522. }
  4523. if (isset($params['max_tokens'])) {
  4524. $requestData['max_tokens'] = $params['max_tokens'];
  4525. }
  4526. if (isset($params['max_completion_tokens'])) {
  4527. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  4528. }
  4529. if (isset($params['temperature'])) {
  4530. $requestData['temperature'] = $params['temperature'];
  4531. }
  4532. if (isset($params['top_p'])) {
  4533. $requestData['top_p'] = $params['top_p'];
  4534. }
  4535. if (isset($params['frequency_penalty'])) {
  4536. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  4537. }
  4538. if (isset($params['presence_penalty'])) {
  4539. $requestData['presence_penalty'] = $params['presence_penalty'];
  4540. }
  4541. if (isset($params['stop'])) {
  4542. $requestData['stop'] = $params['stop'];
  4543. }
  4544. if (isset($params['tools'])) {
  4545. $requestData['tools'] = $params['tools'];
  4546. }
  4547. if (isset($params['tool_choice'])) {
  4548. $requestData['tool_choice'] = $params['tool_choice'];
  4549. }
  4550. if (isset($params['response_format'])) {
  4551. $requestData['response_format'] = $params['response_format'];
  4552. }
  4553. if (isset($params['thinking'])) {
  4554. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  4555. if (is_array($params['thinking'])) {
  4556. $requestData['thinking'] = $params['thinking'];
  4557. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  4558. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  4559. }
  4560. } else {
  4561. $requestData['thinking'] = ['type' => $params['thinking']];
  4562. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  4563. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  4564. }
  4565. }
  4566. } else {
  4567. $requestData['thinking'] = ['type' => 'disabled'];
  4568. }
  4569. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  4570. $client = new Client(['verify' => false, 'timeout' => 1200]);
  4571. try {
  4572. // 判断是否为流式输出
  4573. $isStream = isset($params['stream']) && $params['stream'] === true;
  4574. if ($isStream) {
  4575. // 流式输出
  4576. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  4577. } else {
  4578. // 非流式输出
  4579. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  4580. 'headers' => [
  4581. 'Authorization' => 'Bearer ' . $apiKey,
  4582. 'Content-Type' => 'application/json',
  4583. ],
  4584. 'json' => $requestData
  4585. ]);
  4586. $responseData = json_decode($response->getBody(), true);
  4587. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  4588. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  4589. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  4590. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  4591. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  4592. }
  4593. return [
  4594. 'fullContent' => $fullContent,
  4595. 'fullReasoningContent' => $fullReasoningContent,
  4596. 'usage' => $usage
  4597. ];
  4598. }
  4599. } catch (\Exception $e) {
  4600. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  4601. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  4602. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  4603. }
  4604. }
  4605. /**
  4606. * 火山引擎对话API流式输出
  4607. *
  4608. * @param Client $client HTTP客户端
  4609. * @param string $apiKey API密钥
  4610. * @param array $requestData 请求数据
  4611. * @return Generator
  4612. */
  4613. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  4614. {
  4615. try {
  4616. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  4617. 'headers' => [
  4618. 'Authorization' => 'Bearer ' . $apiKey,
  4619. 'Content-Type' => 'application/json',
  4620. ],
  4621. 'json' => $requestData,
  4622. 'stream' => true
  4623. ]);
  4624. $body = $response->getBody();
  4625. $buffer = '';
  4626. $fullContent = '';
  4627. $fullReasoningContent = '';
  4628. $usage = [];
  4629. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  4630. // 逐行读取流式响应
  4631. while (!$body->eof()) {
  4632. $chunk = $body->read(1024);
  4633. $buffer .= $chunk;
  4634. // 按行分割
  4635. $lines = explode("\n", $buffer);
  4636. $buffer = array_pop($lines);
  4637. foreach ($lines as $line) {
  4638. $line = trim($line);
  4639. if (empty($line)) {
  4640. continue;
  4641. }
  4642. // 检查是否是SSE数据行
  4643. if (strpos($line, 'data: ') !== 0) {
  4644. continue;
  4645. }
  4646. $data = substr($line, 6);
  4647. if ($data === '[DONE]') {
  4648. dLog('deepseek')->info('收到结束标记');
  4649. break 2;
  4650. }
  4651. try {
  4652. $json = json_decode($data, true);
  4653. if (json_last_error() !== JSON_ERROR_NONE) {
  4654. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  4655. continue;
  4656. }
  4657. if (isset($json['choices'][0]['delta'])) {
  4658. $delta = $json['choices'][0]['delta'];
  4659. // 处理思维链内容
  4660. if (isset($delta['reasoning_content'])) {
  4661. $fullReasoningContent .= $delta['reasoning_content'];
  4662. yield [
  4663. 'type' => 'reasoning',
  4664. 'content' => $delta['reasoning_content'],
  4665. 'full_reasoning' => $fullReasoningContent
  4666. ];
  4667. }
  4668. // 处理回答内容
  4669. if (isset($delta['content'])) {
  4670. $fullContent .= $delta['content'];
  4671. yield [
  4672. 'type' => 'content',
  4673. 'content' => $delta['content'],
  4674. ];
  4675. }
  4676. }
  4677. // 获取使用统计信息
  4678. if (isset($json['usage'])) {
  4679. $usage = $json['usage'];
  4680. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  4681. }
  4682. } catch (\Exception $e) {
  4683. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  4684. continue;
  4685. }
  4686. }
  4687. }
  4688. dLog('deepseek')->info('流式读取完成', [
  4689. 'content_length' => strlen($fullContent),
  4690. 'reasoning_length' => strlen($fullReasoningContent)
  4691. ]);
  4692. yield [
  4693. 'type' => 'done',
  4694. 'full_content' => $fullContent,
  4695. 'full_reasoning' => $fullReasoningContent,
  4696. 'usage' => $usage
  4697. ];
  4698. } catch (\Exception $e) {
  4699. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  4700. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  4701. throw $e;
  4702. }
  4703. }
  4704. /**
  4705. * 检查并创建图片生成任务
  4706. *
  4707. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  4708. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  4709. * @param string $nameKey 资源名称字段('role' 或 'scene')
  4710. * @param string $art_style 美术风格
  4711. * @return array 更新后的资源列表
  4712. */
  4713. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  4714. {
  4715. // 构建全局资源映射表,用于快速查找
  4716. $global_map = [];
  4717. foreach ($global_items as $item) {
  4718. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4719. if ($itemKey === '') {
  4720. continue;
  4721. }
  4722. $global_map[$itemKey] = $item;
  4723. }
  4724. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  4725. foreach ($merged_items as &$item) {
  4726. $item_name = getProp($item, $nameKey);
  4727. $item_description = getProp($item, 'description');
  4728. // $item_url = getProp($item, 'url');
  4729. // // 如果已有图片URL,跳过
  4730. // if (!empty($item_url)) {
  4731. // continue;
  4732. // }
  4733. // 如果是旁白角色,跳过
  4734. if ($nameKey === 'role' && $item_name === '旁白') {
  4735. continue;
  4736. }
  4737. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  4738. if ($itemKey === '') {
  4739. continue;
  4740. }
  4741. $need_create_task = false;
  4742. // 条件1:在全局资源中找不到匹配的名称
  4743. if (!isset($global_map[$itemKey])) {
  4744. $need_create_task = true;
  4745. } else {
  4746. // 条件2:名称匹配但描述不一致
  4747. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  4748. $current_description = trim((string)$item_description);
  4749. if ($global_description !== $current_description) {
  4750. $need_create_task = true;
  4751. }
  4752. }
  4753. // 如果需要创建任务,调用图片生成服务
  4754. if ($need_create_task) {
  4755. try {
  4756. $description = $item_description;
  4757. // 添加美术风格前缀
  4758. if ($art_style) {
  4759. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  4760. $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  4761. }
  4762. $params = [
  4763. 'prompt' => $description,
  4764. 'ref_img_urls' => []
  4765. ];
  4766. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4767. $task_id = $task->id;
  4768. if ($task_id) {
  4769. $item['task_id'] = $task_id;
  4770. $item['task_status'] = 'processing';
  4771. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  4772. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  4773. }
  4774. } catch (\Exception $e) {
  4775. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  4776. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  4777. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  4778. // 不抛出异常,继续处理其他资源
  4779. }
  4780. }
  4781. }
  4782. return $merged_items;
  4783. }
  4784. /**
  4785. * 解析分镜内容的公开方法
  4786. */
  4787. public function parseSegmentContent($segment_content, $model = null) {
  4788. if (!$model) {
  4789. $model = DB::table('mp_text_models')->where('is_enabled', 1)->orderBy('id')->value('model');
  4790. if (!$model) {
  4791. return $segment_content;
  4792. }
  4793. }
  4794. // 构建系统提示词
  4795. $systemPrompt = "你是一个专业的分镜内容解析助手。请将用户提供的分镜内容解析成标准格式,包含以下字段:
  4796. 画面描述:详细描述画面内容
  4797. 构图设计:镜头构图方式
  4798. 运镜调度:摄影机运动方式
  4799. 配音角色:配音的角色名称
  4800. 台词内容:角色说的话
  4801. 画面类型:普通画面或对口型
  4802. 场景:拍摄场景
  4803. 出镜角色:画面中出现的角色
  4804. 尾帧描述:镜头结束时的画面描述
  4805. 情感:配音情感(开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦)
  4806. 性别:1(男)、2(女)、0(中性)
  4807. 语速:-50到100之间的整数
  4808. 音量:-50到100之间的整数
  4809. 情感强度:1到5之间的整数
  4810. 音调:-12到12之间的整数
  4811. 请严格按照上述格式输出,如果某个字段无法确定,请设置合理的默认值。";
  4812. // 构建消息
  4813. $messages = [
  4814. [
  4815. 'role' => 'system',
  4816. 'content' => $systemPrompt
  4817. ],
  4818. [
  4819. 'role' => 'user',
  4820. 'content' => $segment_content
  4821. ]
  4822. ];
  4823. $post_data = [
  4824. 'model' => $model,
  4825. 'messages' => $messages,
  4826. // 'max_tokens' => 2048,
  4827. 'temperature' => 0.7,
  4828. 'frequency_penalty' => 0,
  4829. 'presence_penalty' => 0,
  4830. 'response_format' => ['type' => 'text'],
  4831. 'stream' => false
  4832. ];
  4833. try {
  4834. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4835. // 使用DeepSeek API
  4836. $chatResult = $this->chatOnly($post_data);
  4837. } else {
  4838. // 使用火山引擎API
  4839. $chatResult = $this->volcEngineChatCompletion($post_data);
  4840. }
  4841. if (is_array($chatResult) && !empty($chatResult['fullContent'])) {
  4842. return $chatResult['fullContent'];
  4843. }
  4844. } catch (\Exception $e) {
  4845. dLog('deepseek')->error('解析分镜内容失败: ' . $e->getMessage());
  4846. logDB('deepseek', 'error', '解析分镜内容失败', ['error' => $e->getMessage()]);
  4847. }
  4848. return $segment_content;
  4849. }
  4850. }