DeepSeekService.php 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999
  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';
  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. $this->valid_text_models = ['doubao-seed-2-0-pro-260215', 'doubao-seed-2-0-lite-260215', 'deepseek-v3-2-251201'];
  36. $this->sys_message = [
  37. 'role' => 'system',
  38. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  39. 强制要求:\n
  40. 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出\n
  41. 普通要求:\n
  42. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  43. 2.<分集剧本>要求包含“分集序号”、“分集标题”以及分镜信息,分镜信息需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。\n\n
  44. 示例如下:\n
  45. ###剧本名:西昆仑
  46. ###故事梗概
  47. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  48. ###剧本亮点
  49. 亮点1:绝境奇药,生死一线
  50. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  51. 亮点2:结拜兄妹,化解尴尬
  52. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  53. 亮点3:纤发夺命,情愫暗涌
  54. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  55. ###人物关系
  56. 阿雪与梁萧之间存在兄妹之情。
  57. ###核心矛盾
  58. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  59. ###主体列表
  60. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  61. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  62. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  63. 阴阳球:天地异宝,能化生精气,救人于危难。
  64. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  65. ###美术风格
  66. 基础画风风格词:厚涂古风
  67. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  68. ###场景列表
  69. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  70. ###分集剧本
  71. ##分集01
  72. 分集名: 第一集
  73. 分镜01-1
  74. 场景描述:地点、时间、场景
  75. 运镜:固定近距离
  76. 出场角色:男主、女主
  77. 台词内容:
  78. 女主: 女主对话
  79. 男主:男主对话
  80. 女主: 女主对话
  81. 男主: 男主对话
  82. 分镜01-2
  83. 场景描述:地点、时间、场景
  84. 运镜:从近到远
  85. 出场角色:男主、女主
  86. 台词内容:
  87. 女主: 女主对话
  88. 男主:男主对话
  89. 女主: 女主对话
  90. 男主: 男主对话
  91. 分镜01-3
  92. 场景描述:地点、时间、场景
  93. 运镜:快速拉近
  94. 出场角色:男主、女主
  95. 台词内容:
  96. 女主: 女主对话
  97. 男主:男主对话
  98. 女主: 女主对话
  99. 男主: 男主对话
  100. ##分集02
  101. 分集名: 第二集
  102. 分镜02-1
  103. 场景描述:地点、时间、场景
  104. 运镜:从近到远
  105. 出场角色:男主、女主
  106. 台词内容:
  107. 女主: 女主对话
  108. 男主:男主对话
  109. 女主: 女主对话
  110. 男主: 男主对话
  111. 分镜02-2
  112. 场景描述:地点、时间、场景
  113. 运镜:从近到远
  114. 出场角色:男主、女主
  115. 台词内容:
  116. 女主: 女主对话
  117. 男主:男主对话
  118. 女主: 女主对话
  119. 男主: 男主对话"
  120. ];
  121. }
  122. private function getArtStylePromptMappings(): array
  123. {
  124. return [
  125. '日系动漫风格' => [
  126. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  127. 'prompt' => "日系动漫风格,线条干净流畅,色彩明亮柔和,人物精致,光影细腻,画面统一稳定"
  128. ],
  129. '国漫风格' => [
  130. 'aliases' => ['国漫风格', '国漫'],
  131. 'prompt' => "国漫风格,线条硬朗,人物成熟大气,色彩浓郁,光影对比强烈,整体画风统一,适合漫剧叙事"
  132. ],
  133. 'Q版卡通风格' => [
  134. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  135. 'prompt' => "Q版卡通风格,头大身小造型可爱,线条简洁,色彩明快,无复杂阴影,整体萌系干净统一"
  136. ],
  137. '简约扁平风格' => [
  138. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  139. 'prompt' => "简约扁平风格,大块纯色无渐变,线条简洁现代,画面干净清爽,不出现复杂纹理与光影"
  140. ],
  141. '古风仙侠风格' => [
  142. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  143. 'prompt' => "古风仙侠风格,汉服飘逸,云雾缭绕仙气空灵,色调清雅,光影柔和,国风氛围统一"
  144. ],
  145. '武侠风格' => [
  146. 'aliases' => ['武侠风格', '武侠'],
  147. 'prompt' => "武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态自然,色调沉稳大气"
  148. ],
  149. '新中式水墨风格' => [
  150. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  151. 'prompt' => "新中式水墨风格,淡墨渲染笔触自然,留白有意境,色调清雅,国风质感统一不杂乱"
  152. ],
  153. '写实插画风格' => [
  154. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  155. 'prompt' => "写实插画风格,真实人体比例,光影自然细腻,画面质感真实,不卡通不崩坏"
  156. ],
  157. '3D卡通风格' => [
  158. 'aliases' => ['3D卡通风格', '3D卡通'],
  159. 'prompt' => "3D卡通风格,立体建模质感柔和,造型圆润光滑,光影干净,整体风格统一不穿模"
  160. ],
  161. '条漫风格' => [
  162. 'aliases' => ['条漫风格', '条漫'],
  163. 'prompt' => "条漫风格,纵向分镜简洁,色彩清淡,适合上下滑动阅读,画面轻量化且整体统一"
  164. ],
  165. '赛博朋克风格' => [
  166. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  167. 'prompt' => "赛博朋克风格,霓虹灯光未来都市,暗色调科技感强,高对比光影,风格统一强烈"
  168. ],
  169. '暗黑悬疑风格' => [
  170. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  171. 'prompt' => "暗黑悬疑风格,低饱和冷色调,强阴影光线昏暗,氛围神秘压抑,整体色调统一"
  172. ],
  173. '治愈清新风格' => [
  174. 'aliases' => ['治愈清新风格', '治愈清新'],
  175. 'prompt' => "治愈清新风格,马卡龙柔和色系,柔光暖调,画面干净舒适,氛围温暖不杂乱"
  176. ],
  177. ];
  178. }
  179. private function getArtStylePromptByInput($inputArtStyle): string
  180. {
  181. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  182. if ($normalizedInput === '') {
  183. return '';
  184. }
  185. foreach ($this->getArtStylePromptMappings() as $mapping) {
  186. foreach ($mapping['aliases'] as $alias) {
  187. $normalizedAlias = $this->normalizeArtStyleInput($alias);
  188. if ($normalizedAlias === '') {
  189. continue;
  190. }
  191. if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  192. return $mapping['prompt'];
  193. }
  194. }
  195. }
  196. return '';
  197. }
  198. private function normalizeArtStyleInput($value): string
  199. {
  200. $value = trim((string)$value);
  201. if ($value === '') {
  202. return '';
  203. }
  204. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  205. return mb_strtolower($value, 'UTF-8');
  206. }
  207. private function replaceArtStyleSection(string $content, string $artStyle): string
  208. {
  209. if ($content === '' || $artStyle === '') {
  210. return $content;
  211. }
  212. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  213. if (!preg_match($pattern, $content)) {
  214. return $content;
  215. }
  216. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  217. }
  218. /**
  219. * DeepSeek流式输出处理方法
  220. *
  221. * @param array $post_data DeepSeek API请求参数
  222. * @return \Generator 返回生成器,用于流式输出
  223. */
  224. private function deepSeekStreamResponse($post_data) {
  225. $client = new Client(['timeout' => 1200, 'verify' => false]);
  226. $response = $client->post($this->url, [
  227. 'json' => $post_data,
  228. 'headers' => $this->headers,
  229. 'stream' => true // 启用流式响应
  230. ]);
  231. $body = $response->getBody();
  232. $fullContent = '';
  233. $fullReasoningContent = '';
  234. $usage = [];
  235. $buffer = '';
  236. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  237. // 逐行读取流式响应
  238. while (!$body->eof()) {
  239. $chunk = $body->read(1024); // 每次读取 1KB
  240. $buffer .= $chunk;
  241. // 按行分割
  242. $lines = explode("\n", $buffer);
  243. // 保留最后一个不完整的行
  244. $buffer = array_pop($lines);
  245. foreach ($lines as $line) {
  246. $line = trim($line);
  247. // 跳过空行
  248. if (empty($line)) {
  249. continue;
  250. }
  251. // 检查是否是 SSE 数据行
  252. if (strpos($line, 'data: ') !== 0) {
  253. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  254. continue;
  255. }
  256. $data = substr($line, 6); // 移除 "data: " 前缀
  257. if ($data === '[DONE]') {
  258. dLog('deepseek')->info('收到结束标记');
  259. break 2; // 跳出两层循环
  260. }
  261. try {
  262. $json = json_decode($data, true);
  263. if (json_last_error() !== JSON_ERROR_NONE) {
  264. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  265. continue;
  266. }
  267. if (isset($json['choices'][0]['delta'])) {
  268. $delta = $json['choices'][0]['delta'];
  269. // 处理思维链内容(仅 deepseek-reasoner 模型)
  270. if (isset($delta['reasoning_content'])) {
  271. $fullReasoningContent .= $delta['reasoning_content'];
  272. yield [
  273. 'type' => 'reasoning',
  274. 'content' => $delta['reasoning_content'],
  275. 'full_reasoning' => $fullReasoningContent
  276. ];
  277. }
  278. // 处理最终回答内容
  279. if (isset($delta['content'])) {
  280. $fullContent .= $delta['content'];
  281. yield [
  282. 'type' => 'content',
  283. 'content' => $delta['content'],
  284. ];
  285. }
  286. }
  287. // 获取使用统计信息
  288. if (isset($json['usage'])) {
  289. $usage = $json['usage'];
  290. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  291. }
  292. } catch (\Exception $e) {
  293. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  294. continue;
  295. }
  296. }
  297. }
  298. dLog('deepseek')->info('流式读取完成', [
  299. 'content_length' => strlen($fullContent),
  300. 'reasoning_length' => strlen($fullReasoningContent)
  301. ]);
  302. yield [
  303. 'type' => 'done',
  304. 'full_content' => $fullContent,
  305. 'full_reasoning' => $fullReasoningContent,
  306. 'usage' => $usage
  307. ];
  308. }
  309. // 与推理模型对话
  310. public function chatWithReasoner($data) {
  311. $content = getProp($data, 'content');
  312. $model = getProp($data, 'model', 'r1');
  313. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  314. // 获取可选情感(根据音色可支持情感选)
  315. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  316. $emotion_list = [];
  317. foreach ($timbre_emotion as $emotion) {
  318. $tmp = explode(',', $emotion);
  319. $emotion_list = array_merge($emotion_list, $tmp);
  320. }
  321. $emotion_list = array_unique($emotion_list);
  322. $emotion_str = implode('、', $emotion_list);
  323. // // 获取可选情感
  324. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  325. // $emotion_str = implode('、', $emotion_list);
  326. // 是否启用情感
  327. $enable_emotion = getProp($data, 'enable_emotion', 0);
  328. if ($enable_emotion) {
  329. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  330. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  331. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  332. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  333. }else {
  334. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  335. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  336. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  337. }
  338. $messages = [
  339. [
  340. 'role' => 'system',
  341. 'content' => $sys_content
  342. ],
  343. [
  344. 'role' => 'user',
  345. 'content' => $content
  346. ]
  347. ];
  348. $post_data = [
  349. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  350. 'messages' => $messages,
  351. 'max_tokens' => 8192,
  352. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  353. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  354. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  355. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  356. 'response_format' => [
  357. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  358. ],
  359. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  360. ];
  361. $client = new Client(['timeout' => 1200, 'verify' => false]);
  362. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  363. $response = $result->getBody()->getContents();
  364. $response_arr = json_decode($response, true);
  365. $update_data = [];
  366. $content = '';
  367. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  368. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  369. $update_data = [
  370. 'role' => 'assistant',
  371. 'content' => $response_arr['choices'][0]['message']['content'],
  372. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  373. ];
  374. }
  375. // 处理获取到的剧本数据
  376. $script_content = handleScriptWords($content, $enable_emotion);
  377. $result = [
  378. 'origin_content' => $content,
  379. 'roles' => getProp($script_content, 'roles'),
  380. 'words' => getProp($script_content, 'words'),
  381. ];
  382. return $result;
  383. }
  384. public function resetParagraphAudio($data) {
  385. $bid = getProp($data, 'bid');
  386. $cid = getProp($data, 'cid');
  387. $version_id = getProp($data, 'version_id');
  388. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  389. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  390. 'generate_status' => '待制作',
  391. 'updated_at' => date('Y-m-d H:i:s')
  392. ]);
  393. }
  394. public function saveParagraphAudio($data) {
  395. $bid = getProp($data, 'bid');
  396. $cid = getProp($data, 'cid');
  397. $version_id = getProp($data, 'version_id');
  398. $sequence = getProp($data, 'sequence');
  399. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  400. // 获取所有情感
  401. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  402. $emotion_list = array_flip($emotion_list);
  403. // 获取音色支持情感
  404. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  405. $timbre_emotion = explode(',', $timbre_emotion);
  406. $emotion = getProp($data, 'emotion');
  407. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  408. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  409. $list = [
  410. 'bid' => $bid,
  411. 'cid' => $cid,
  412. 'version_id' => $version_id,
  413. 'sequence' => $sequence,
  414. 'role' => getProp($data, 'role'),
  415. 'gender' => getProp($data, 'gender'),
  416. 'text' => trim(getProp($data, 'text')),
  417. 'emotion' => $emotion,
  418. 'emotion_type' => $emotion_type,
  419. 'voice_type' => getProp($data, 'voice_type'),
  420. 'voice_name' => getProp($data, 'voice_name'),
  421. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  422. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  423. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  424. 'pitch' => getProp($data, 'pitch', 0),
  425. // 'paragraph_audio_url' => '',
  426. 'generate_status' => '制作中',
  427. 'error_msg' => '',
  428. 'updated_at' => date('Y-m-d H:i:s')
  429. ];
  430. $continue = false;
  431. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  432. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  433. $list['generate_status'] = '制作成功';
  434. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  435. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  436. $continue = true;
  437. }
  438. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  439. if ($id) {
  440. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  441. }else {
  442. $list['created_at'] = date('Y-m-d H:i:s');
  443. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  444. $boolen = $id ? true : false;
  445. }
  446. // 如果更新成功则加入查询队列
  447. if ($boolen) {
  448. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  449. Redis::sadd($redis_key, $id);
  450. }
  451. if ($boolen && !$continue) {
  452. $boolen = false;
  453. $client = new Client(['timeout' => 300, 'verify' => false]);
  454. // 根据ID通过API通知合成音频
  455. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  456. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  457. $response = $result->getBody()->getContents();
  458. $response_arr = json_decode($response, true);
  459. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  460. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  461. Log::info('通知火山生成段落音频失败: '.$error_msg);
  462. Utils::throwError('20003:通知火山生成段落音频失败');
  463. }
  464. $boolen = true;
  465. }
  466. return $boolen;
  467. }
  468. public function insertAudioEffect($data) {
  469. $audio_id = getProp($data, 'audio_id');
  470. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  471. $bid = getProp($chapter_audio, 'bid');
  472. $version_id = getProp($chapter_audio, 'version_id');
  473. $cid = getProp($chapter_audio, 'cid');
  474. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  475. $audio_effect_json = getProp($data, 'audio_effect_json');
  476. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  477. try {
  478. DB::beginTransaction();
  479. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  480. if (!$count) {
  481. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  482. }else {
  483. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  484. }
  485. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  486. 'audio_effect_status' => '添加中',
  487. 'audio_effect_json' => $audio_effect_json,
  488. 'updated_at' => date('Y-m-d H:i:s')
  489. ]);
  490. if (!$boolen1) {
  491. DB::rollBack();
  492. Utils::throwError('20003:更新生成数据失败');
  493. }
  494. $id = DB::table('mp_audio_tasks')->insertGetId([
  495. 'audio_id' => $audio_id,
  496. 'generate_status' => '执行中',
  497. 'generate_json' => json_encode([], 256),
  498. 'bid' => $bid,
  499. 'book_name' => getProp($chapter_audio, 'book_name'),
  500. 'version_id' => $version_id,
  501. 'version_name' => getProp($chapter_audio, 'version_name'),
  502. 'cid' => $cid,
  503. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  504. 'task_name' => $task_name,
  505. 'created_at' => date('Y-m-d H:i:s'),
  506. 'updated_at' => date('Y-m-d H:i:s')
  507. ]);
  508. if (!$id) {
  509. DB::rollBack();
  510. Utils::throwError('20003:创建任务失败');
  511. }
  512. }catch (\Exception $e) {
  513. DB::rollBack();
  514. Utils::throwError('20003:'.$e->getMessage());
  515. }
  516. DB::commit();
  517. $client = new Client(['timeout' => 300, 'verify' => false]);
  518. // 根据ID通过API通知合成音频
  519. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  520. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  521. $response = $result->getBody()->getContents();
  522. $response_arr = json_decode($response, true);
  523. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  524. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  525. Log::info('通知火山插入音效失败: '.$error_msg);
  526. Utils::throwError('20003:通知火山插入音效失败');
  527. }
  528. return true;
  529. }
  530. public function insertBgm($data) {
  531. $audio_id = getProp($data, 'audio_id');
  532. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  533. $bid = getProp($chapter_audio, 'bid');
  534. $version_id = getProp($chapter_audio, 'version_id');
  535. $cid = getProp($chapter_audio, 'cid');
  536. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  537. $bgm_json = getProp($data, 'bgm_json');
  538. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  539. if (!$bgm_json) {
  540. $bgm_json = getProp($data, 'audio_effect_json');
  541. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  542. }
  543. try {
  544. DB::beginTransaction();
  545. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  546. if (!$count) {
  547. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  548. }else {
  549. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  550. }
  551. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  552. 'bgm_status' => '添加中',
  553. 'bgm_json' => $bgm_json,
  554. 'updated_at' => date('Y-m-d H:i:s')
  555. ]);
  556. if (!$boolen1) {
  557. DB::rollBack();
  558. Utils::throwError('20003:更新生成数据失败');
  559. }
  560. $id = DB::table('mp_audio_tasks')->insertGetId([
  561. 'audio_id' => $audio_id,
  562. 'generate_status' => '执行中',
  563. 'generate_json' => json_encode([], 256),
  564. 'bid' => $bid,
  565. 'book_name' => getProp($chapter_audio, 'book_name'),
  566. 'version_id' => $version_id,
  567. 'version_name' => getProp($chapter_audio, 'version_name'),
  568. 'cid' => $cid,
  569. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  570. 'task_name' => $task_name,
  571. 'created_at' => date('Y-m-d H:i:s'),
  572. 'updated_at' => date('Y-m-d H:i:s')
  573. ]);
  574. if (!$id) {
  575. DB::rollBack();
  576. Utils::throwError('20003:创建任务失败');
  577. }
  578. }catch (\Exception $e) {
  579. DB::rollBack();
  580. Utils::throwError('20003:'.$e->getMessage());
  581. }
  582. DB::commit();
  583. $client = new Client(['timeout' => 300, 'verify' => false]);
  584. // 根据ID通过API通知合成音频
  585. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  586. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  587. $response = $result->getBody()->getContents();
  588. $response_arr = json_decode($response, true);
  589. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  590. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  591. Log::info('通知火山插入bgm失败: '.$error_msg);
  592. Utils::throwError('20003:通知火山插入bgm失败');
  593. }
  594. return true;
  595. }
  596. public function getParagraphAudios($data) {
  597. $bid = getProp($data, 'bid');
  598. $cid = getProp($data, 'cid');
  599. $version_id = getProp($data, 'version_id');
  600. $sequence = getProp($data, 'sequence');
  601. // 获取已生成的音频
  602. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  603. if ($sequence) $query->where('sequence', $sequence);
  604. $paragraph_audios = $query->orderBy('sequence')->get();
  605. $result = [];
  606. foreach($paragraph_audios as $item) {
  607. $result[] = [
  608. 'sequence' => getProp($item, 'sequence'),
  609. 'role' => getProp($item, 'role'),
  610. 'gender' => getProp($item, 'gender'),
  611. 'text' => trim(getProp($item, 'text')),
  612. 'emotion' => getProp($item, 'emotion'),
  613. 'emotion_type' => getProp($item, 'emotion_type'),
  614. 'voice_type' => getProp($item, 'voice_type'),
  615. 'voice_name' => getProp($item, 'voice_name'),
  616. 'speed_ratio' => getProp($item, 'speed_ratio'),
  617. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  618. 'emotion_scale' => getProp($item, 'emotion_scale'),
  619. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  620. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  621. ];
  622. }
  623. return $result;
  624. }
  625. // 新增合成任务
  626. public function addGenerateTask($data) {
  627. $bid = getProp($data, 'bid');
  628. $cid = getProp($data, 'cid');
  629. $version_id = getProp($data, 'version_id');
  630. $generate_json = getProp($data, 'generate_json');
  631. // 获取已生成的音频
  632. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  633. $paragraph_list = [];
  634. foreach($paragraph_audios as $item) {
  635. $paragraph_list[getProp($item, 'sequence')] = [
  636. 'role' => getProp($item, 'role'),
  637. 'gender' => getProp($item, 'gender'),
  638. 'text' => trim(getProp($item, 'text')),
  639. 'emotion' => getProp($item, 'emotion'),
  640. 'emotion_type' => getProp($item, 'emotion_type'),
  641. 'voice_type' => getProp($item, 'voice_type'),
  642. 'voice_name' => getProp($item, 'voice_name'),
  643. 'speed_ratio' => getProp($item, 'speed_ratio'),
  644. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  645. 'emotion_scale' => getProp($item, 'emotion_scale'),
  646. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  647. ];
  648. }
  649. // 更新角色-音色信息
  650. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  651. $existed_role_info = json_decode($existed_role_info, true);
  652. if (!$existed_role_info) $existed_role_info = [];
  653. // 获取情感信息
  654. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  655. $emotion_list = array_flip($emotion_list);
  656. // 获取音色对应情感组
  657. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  658. $timbre_emotion_list = [];
  659. foreach($timbre_emotions as $item) {
  660. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  661. }
  662. // 构造生成音频的json
  663. $words = json_decode($generate_json, true);
  664. // 最终合成前的参数组
  665. $mp_chapter_paragraph_audios = [];
  666. $sequence = 1;
  667. $complete_paragraph_sequences = [];
  668. foreach($words as &$word) {
  669. 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:参数格式有误');
  670. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  671. $role = getProp($word, 'role');
  672. $word['gender'] = (int)$word['gender'];
  673. // 判断音色对应情感是否支持,不支持则调整为中性
  674. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  675. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  676. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  677. if (isset($emotion_list[getProp($word, 'emotion')])) {
  678. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  679. }else {
  680. $word['emotion'] = '中性';
  681. $word['emotion_type'] = 'neutral';
  682. }
  683. $existed_role_info[$role] = [
  684. 'timbre_type' => $word['voice_type'],
  685. 'timbre_name' => $word['voice_name'],
  686. 'emotion' => $word['emotion'],
  687. 'emotion_type' => $word['emotion_type'],
  688. 'speed_ratio' => $word['speed_ratio'],
  689. 'loudness_ratio'=> $word['loudness_ratio'],
  690. 'emotion_scale' => $word['emotion_scale'],
  691. 'pitch' => $word['pitch']
  692. ];
  693. $word['paragraph_audio_url'] = '';
  694. // 判断生成参数是否相同,相同则直接使用已生成的音频
  695. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  696. // 如果音频存在并且参数都未改变则使用已生成的音频
  697. if (getProp($paragraph, 'paragraph_audio_url')) {
  698. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  699. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  700. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  701. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  702. // {
  703. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  704. // }
  705. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  706. }
  707. $tmp = $word;
  708. // 组装章节分句音频数据
  709. // $tmp['sequence'] = getProp($word, 'sequence');
  710. // $tmp['text'] = getProp($word, 'text');
  711. // $tmp['emotion'] = getProp($word, 'emotion');
  712. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  713. // $tmp['voice_name'] = getProp($word, 'voice_name');
  714. // $tmp['voice_type'] = getProp($word, 'voice_type');
  715. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  716. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  717. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  718. $tmp['bid'] = $bid;
  719. $tmp['version_id'] = $version_id;
  720. $tmp['cid'] = $cid;
  721. $tmp['sequence'] = $sequence;
  722. $tmp['created_at'] = date('Y-m-d H:i:s');
  723. $tmp['updated_at'] = date('Y-m-d H:i:s');
  724. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  725. $mp_chapter_paragraph_audios[] = $tmp;
  726. $complete_paragraph_sequences[] = $sequence;
  727. $sequence++;
  728. }
  729. $generate_json = json_encode($words, 256);
  730. // 判断是否有未生成字幕的段落
  731. $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();
  732. if ($no_subtitle_sequences) {
  733. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  734. }
  735. try {
  736. DB::beginTransaction();
  737. $role_info = json_encode($existed_role_info, 256);
  738. $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')]);
  739. if (!$boolen) {
  740. DB::rollBack();
  741. Utils::throwError('20003:更新角色信息失败');
  742. }
  743. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  744. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  745. if (!$count) {
  746. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  747. }else {
  748. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  749. }
  750. $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')]);
  751. if (!$boolen1) {
  752. DB::rollBack();
  753. Utils::throwError('20003:更新生成数据失败');
  754. }
  755. $id = DB::table('mp_audio_tasks')->insertGetId([
  756. 'audio_id' => getProp($chapter_audio, 'id'),
  757. 'generate_status' => '执行中',
  758. 'generate_json' => $generate_json,
  759. 'bid' => $bid,
  760. 'book_name' => getProp($chapter_audio, 'book_name'),
  761. 'version_id' => $version_id,
  762. 'version_name' => getProp($chapter_audio, 'version_name'),
  763. 'cid' => $cid,
  764. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  765. 'task_name' => $task_name,
  766. 'created_at' => date('Y-m-d H:i:s'),
  767. 'updated_at' => date('Y-m-d H:i:s')
  768. ]);
  769. if (!$id) {
  770. DB::rollBack();
  771. Utils::throwError('20003:创建任务失败');
  772. }
  773. // 删除不在段落序号范围内的其他数据
  774. if ($complete_paragraph_sequences) {
  775. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  776. }
  777. // // 删除章节分句音频数据并重新插入
  778. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  779. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  780. // if (!$boolen3) {
  781. // DB::rollBack();
  782. // Utils::throwError('20003:更新章节分句音频失败');
  783. // }
  784. } catch (\Exception $e) {
  785. DB::rollBack();
  786. Utils::throwError('20003:'.$e->getMessage());
  787. }
  788. DB::commit();
  789. // 通知火山生成音频
  790. $client = new Client(['timeout' => 300, 'verify' => false]);
  791. // 根据ID通过API通知合成音频
  792. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  793. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  794. $response = $result->getBody()->getContents();
  795. $response_arr = json_decode($response, true);
  796. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  797. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  798. Log::info('通知火山生成音频失败: '.$error_msg);
  799. Utils::throwError('20003:通知火山生成音频失败');
  800. }
  801. return true;
  802. }
  803. public function timbreList($data) {
  804. $gender = getProp($data, 'gender');
  805. $timbre_name = getProp($data, 'voice_name');
  806. $category_id = getProp($data, 'category_id');
  807. $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');
  808. if ($gender) {
  809. $query->where('gender', $gender);
  810. }
  811. if ($timbre_name) {
  812. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  813. }
  814. if ($category_id) {
  815. $query->where(function ($query) use ($category_id) {
  816. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  817. });
  818. }
  819. $list = $query->get()->map(function ($value) {
  820. $value = (array)$value;
  821. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  822. return $value;
  823. })->toArray();
  824. return $list;
  825. }
  826. // 生成火山临时token
  827. public function setStsToken() {
  828. // ************* 配置参数 *************
  829. $method = 'GET';
  830. $service = 'sts';
  831. $host = 'open.volcengineapi.com';
  832. $region = env('VOLC_REGION');
  833. $endpoint = 'https://open.volcengineapi.com';
  834. // $endpoint = 'https://tos-cn-beijing.volces.com';
  835. $access_key = env('VOLC_AK');
  836. $secret_key = env('VOLC_SK');
  837. // 获取缓存中的token,如果没有则请求接口
  838. $token = Redis::get('volc_sts_token');
  839. if (!$token) {
  840. // 查询参数
  841. $query_parameters = [
  842. 'Action' => 'AssumeRole',
  843. 'RoleSessionName' => 'user@zw',
  844. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  845. 'Version' => '2018-01-01'
  846. ];
  847. // 生成URL编码的查询字符串
  848. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  849. // 获取签名头信息
  850. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  851. // 构建完整URL
  852. $request_url = $endpoint . '?' . $request_parameters;
  853. $client = new Client(['verify' => false]);
  854. $response = $client->get($request_url, ['headers' => $headers]);
  855. $response_arr = json_decode($response->getBody()->getContents(), true);
  856. $result = [
  857. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  858. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  859. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  860. 'Region' => env('VOLC_REGION'),
  861. 'Endpoint' => env('VOLC_END_POINT'),
  862. 'Bucket' => env('VOLC_BUCKET'),
  863. ];
  864. // 缓存token
  865. Redis::setex('volc_sts_token', 3000, json_encode($result));
  866. return $result;
  867. } else {
  868. return json_decode($token, true);
  869. }
  870. // $response = $response['Response'];
  871. // $access_key = $response['Credentials']['AccessKeyId'];
  872. // $secret_key = $response['Credentials']['AccessKeySecret'];
  873. // $security_token = $response['Credentials']['SecurityToken'];
  874. // $expiration = $response['Credentials']['Expiration'];
  875. // dd($response_arr);
  876. }
  877. public function emotionGroups($data) {
  878. $id = getProp($data, 'group_id');
  879. $group_name = getProp($data, 'group_name');
  880. $voice_type = getProp($data, 'voice_type');
  881. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  882. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  883. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  884. if ($group_name) {
  885. $query->where('group_name', 'like', "%{$group_name}%");
  886. }
  887. if ($id) {
  888. $query->where('id', $id);
  889. }
  890. if ($voice_type) {
  891. $query->where('voice_type', $voice_type);
  892. }
  893. return $query->orderBy('id')->get()->map(function ($value) {
  894. return (array)$value;
  895. })->toArray();
  896. }
  897. private function sign($key, $msg) {
  898. return hash_hmac('sha256', $msg, $key, true);
  899. }
  900. // 生成签名密钥
  901. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  902. $kDate = $this->sign($key, $dateStamp);
  903. $kRegion = $this->sign($kDate, $regionName);
  904. $kService = $this->sign($kRegion, $serviceName);
  905. $kSigning = $this->sign($kService, 'request');
  906. return $kSigning;
  907. }
  908. // 获取签名头信息
  909. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  910. $contenttype = 'application/x-www-form-urlencoded';
  911. $accept = 'application/json';
  912. // 获取当前UTC时间
  913. $t = new DateTime('now', new DateTimeZone('UTC'));
  914. $xdate = $t->format('Ymd\THis\Z');
  915. $datestamp = $t->format('Ymd');
  916. // 1. 拼接规范请求串
  917. $canonical_uri = '/';
  918. $canonical_querystring = $request_parameters;
  919. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  920. $signed_headers = 'content-type;host;x-date';
  921. // 空请求体的SHA256哈希
  922. $payload_hash = hash('sha256', '');
  923. $canonical_request = implode("\n", [
  924. $method,
  925. $canonical_uri,
  926. $canonical_querystring,
  927. $canonical_headers,
  928. $signed_headers,
  929. $payload_hash
  930. ]);
  931. // 2. 拼接待签名字符串
  932. $algorithm = 'HMAC-SHA256';
  933. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  934. $hashed_canonical_request = hash('sha256', $canonical_request);
  935. $string_to_sign = implode("\n", [
  936. $algorithm,
  937. $xdate,
  938. $credential_scope,
  939. $hashed_canonical_request
  940. ]);
  941. // 3. 计算签名
  942. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  943. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  944. // 4. 添加签名到请求头
  945. $authorization_header = sprintf(
  946. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  947. $algorithm,
  948. $access_key,
  949. $credential_scope,
  950. $signed_headers,
  951. $signature
  952. );
  953. return [
  954. 'Accept' => $accept,
  955. 'Content-Type' => $contenttype,
  956. 'X-Date' => $xdate,
  957. 'Authorization' => $authorization_header
  958. ];
  959. }
  960. // 文字合成语音(火山引擎)
  961. public function tts($data) {
  962. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  963. $headers = [
  964. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  965. 'Content-Type' => 'application/json; charset=UTF-8'
  966. ];
  967. $post_data = [
  968. 'app' => [
  969. 'appid' => env('VOLC_APPID'),
  970. 'token' => env('VOLC_TOKEN'),
  971. 'cluster' => 'volcano_tts'
  972. ],
  973. 'user' => [
  974. 'uid' => 'mp_audio'
  975. ],
  976. // 'audio' => [
  977. // 'voice_type' =>
  978. // ],
  979. ];
  980. }
  981. public function scriptList($data) {
  982. $script_id = getProp($data, 'script_id');
  983. $script_name = getProp($data, 'script_name');
  984. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  985. if ($script_id) {
  986. $query->where('id', $script_id);
  987. }
  988. if ($script_name) {
  989. $query->where('script_name', 'like', "%{$script_name}%");
  990. }
  991. return $query->orderBy('created_at', 'desc')->paginate(12);
  992. }
  993. public function scriptInfo($data) {
  994. $script_id = getProp($data, 'script_id');
  995. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  996. ->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();
  997. if (!$script) Utils::throwError('20003:该剧本不存在!');
  998. $script = (array)$script;
  999. $script['roles'] = json_decode($script['roles']);
  1000. $script['scenes'] = json_decode($script['scenes']);
  1001. // 获取分集信息
  1002. $episodes = DB::table('mp_script_episodes')->where('script_id', $script_id)->orderBy('episode_number')
  1003. ->select('id', 'episode_number', 'title', 'content', 'segment_number', 'segment_content')
  1004. ->orderBy('episode_number')->orderBy('segment_number')->get()->map(function ($value) {
  1005. return (array)$value;
  1006. })->toArray();
  1007. $return_episodes = [];
  1008. foreach($episodes as $episode) {
  1009. $episode_number = getProp($episode, 'episode_number');
  1010. if (isset($return_episodes[$episode_number])) {
  1011. $return_episodes[$episode_number]['segments'][] = [
  1012. 'segment_number' => getProp($episode, 'segment_number'),
  1013. 'segment_content' => getProp($episode, 'segment_content')
  1014. ];
  1015. }else {
  1016. $return_episodes[$episode_number] = [
  1017. 'episode_number' => $episode_number,
  1018. 'title' => getProp($episode, 'title'),
  1019. 'segments' => [
  1020. [
  1021. 'segment_number' => getProp($episode, 'segment_number'),
  1022. 'segment_content' => getProp($episode, 'segment_content')
  1023. ]
  1024. ]
  1025. ];
  1026. }
  1027. }
  1028. $script['episodes'] = array_values($return_episodes);
  1029. return $script;
  1030. }
  1031. public function createScript($data) {
  1032. $script_name = getProp($data, 'script_name');
  1033. $uid = Site::getUid(); // 获取当前用户ID
  1034. if (!$script_name) Utils::throwError('20001:剧本名称不能为空');
  1035. return DB::table('mp_scripts')->insertGetId([
  1036. 'script_name' => $script_name,
  1037. 'user_id' => $uid,
  1038. 'created_at' => date('Y-m-d H:i:s'),
  1039. 'updated_at' => date('Y-m-d H:i:s')
  1040. ]);
  1041. }
  1042. /**
  1043. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1044. *
  1045. * @param array $data 包含以下参数:
  1046. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1047. * - question: 用户问题(可选)
  1048. * - model: 使用的模型(r1 或 v3,默认 v3)
  1049. * @return \Generator 返回生成器,用于流式输出
  1050. */
  1051. public function chatWithFileStream($data) {
  1052. $script_id = getProp($data, 'script_id');
  1053. $file = getProp($data, 'file');
  1054. $content = getProp($data, 'content', '');
  1055. $bid = getProp($data, 'bid', 0);
  1056. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1057. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1058. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1059. $model = getProp($data, 'model', 'v3');
  1060. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1061. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1062. if (!$script) {
  1063. Utils::throwError('20003:剧本不存在');
  1064. }
  1065. if (!$file && !$content && !$bid) {
  1066. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1067. }
  1068. // 提取文件内容
  1069. if ($file) {
  1070. $content = $this->extractFileContent($file);
  1071. if (!$content) {
  1072. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1073. }
  1074. } elseif ($bid) {
  1075. $content = $this->getContentByBid($bid);
  1076. if (!$content) {
  1077. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1078. }
  1079. } elseif ($content) {
  1080. $content = filterContent($content);
  1081. } else {
  1082. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1083. }
  1084. // 构建消息
  1085. $messages = [
  1086. $this->sys_message,
  1087. [
  1088. 'role' => 'user',
  1089. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1090. ]
  1091. ];
  1092. $post_data = [
  1093. 'model' => $model,
  1094. 'messages' => $messages,
  1095. 'max_tokens' => 8192,
  1096. 'temperature' => 0.7,
  1097. 'frequency_penalty' => 0,
  1098. 'presence_penalty' => 0,
  1099. 'response_format' => ['type' => 'text'],
  1100. 'stream' => true // 启用流式输出
  1101. ];
  1102. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1103. $response = $client->post($this->url, [
  1104. 'json' => $post_data,
  1105. 'headers' => $this->headers,
  1106. 'stream' => true // 启用流式响应
  1107. ]);
  1108. $body = $response->getBody();
  1109. $fullContent = '';
  1110. $fullReasoningContent = '';
  1111. $usage = [];
  1112. $buffer = '';
  1113. Log::info('开始读取 DeepSeek 流式响应');
  1114. // 逐行读取流式响应
  1115. while (!$body->eof()) {
  1116. $chunk = $body->read(1024); // 每次读取 1KB
  1117. $buffer .= $chunk;
  1118. // 按行分割
  1119. $lines = explode("\n", $buffer);
  1120. // 保留最后一个不完整的行
  1121. $buffer = array_pop($lines);
  1122. foreach ($lines as $line) {
  1123. $line = trim($line);
  1124. // 跳过空行
  1125. if (empty($line)) {
  1126. continue;
  1127. }
  1128. // Log::info('收到原始行数据', ['line' => $line]);
  1129. // 检查是否是 SSE 数据行
  1130. if (strpos($line, 'data: ') !== 0) {
  1131. Log::warning('非 SSE 数据行', ['line' => $line]);
  1132. continue;
  1133. }
  1134. $data = substr($line, 6); // 移除 "data: " 前缀
  1135. if ($data === '[DONE]') {
  1136. Log::info('收到结束标记');
  1137. break 2; // 跳出两层循环
  1138. }
  1139. try {
  1140. $json = json_decode($data, true);
  1141. if (json_last_error() !== JSON_ERROR_NONE) {
  1142. Log::warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1143. continue;
  1144. }
  1145. // Log::info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1146. if (isset($json['choices'][0]['delta'])) {
  1147. $delta = $json['choices'][0]['delta'];
  1148. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1149. // 注释掉以下内容则不返回d思维链内容
  1150. if (isset($delta['reasoning_content'])) {
  1151. $fullReasoningContent .= $delta['reasoning_content'];
  1152. // Log::info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1153. yield [
  1154. 'type' => 'reasoning',
  1155. 'content' => $delta['reasoning_content'],
  1156. 'full_reasoning' => $fullReasoningContent
  1157. ];
  1158. }
  1159. // 处理最终回答内容
  1160. if (isset($delta['content'])) {
  1161. $fullContent .= $delta['content'];
  1162. // Log::info('输出回答内容', ['length' => strlen($delta['content'])]);
  1163. yield [
  1164. 'type' => 'content',
  1165. 'content' => $delta['content'],
  1166. // 'full_content' => $fullContent
  1167. ];
  1168. }
  1169. }
  1170. // 获取使用统计信息
  1171. if (isset($json['usage'])) {
  1172. $usage = $json['usage'];
  1173. Log::info('收到使用统计', ['usage' => $usage]);
  1174. }
  1175. } catch (\Exception $e) {
  1176. Log::error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1177. continue;
  1178. }
  1179. }
  1180. }
  1181. Log::info('流式读取完成', [
  1182. 'content_length' => strlen($fullContent),
  1183. 'reasoning_length' => strlen($fullReasoningContent)
  1184. ]);
  1185. // 处理完整内容并返回最终结果
  1186. $script_arr = [];
  1187. if ($fullContent) {
  1188. $script_arr = handleScriptContent($fullContent);
  1189. }
  1190. yield [
  1191. 'type' => 'done',
  1192. 'script' => $script_arr,
  1193. 'answer' => $fullContent,
  1194. 'reasoning' => $fullReasoningContent,
  1195. 'usage' => $usage
  1196. ];
  1197. }
  1198. /**
  1199. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1200. *
  1201. * @param array $data 包含以下参数:
  1202. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1203. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1204. * - model: 使用的模型(r1 或 v3,默认 v3)
  1205. * @return array
  1206. */
  1207. public function chatWithFile($data) {
  1208. // dd(handleScriptContent(''));
  1209. $script_id = getProp($data, 'script_id');
  1210. $file = getProp($data, 'file');
  1211. $content = getProp($data, 'content', '');
  1212. $bid = getProp($data, 'bid', 0);
  1213. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1214. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1215. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1216. $model = getProp($data, 'model', 'v3');
  1217. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1218. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1219. if (!$script) {
  1220. Utils::throwError('20003:剧本不存在');
  1221. }
  1222. if (!$file && !$content && !$bid) {
  1223. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1224. }
  1225. // 提取文件内容
  1226. if ($file) {
  1227. $content = $this->extractFileContent($file);
  1228. if (!$content) {
  1229. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1230. }
  1231. } elseif ($bid) {
  1232. $content = $this->getContentByBid($bid);
  1233. if (!$content) {
  1234. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1235. }
  1236. } elseif ($content) {
  1237. $content = filterContent($content);
  1238. } else {
  1239. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1240. }
  1241. // 构建消息
  1242. $messages = [
  1243. $this->sys_message,
  1244. [
  1245. 'role' => 'user',
  1246. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1247. ]
  1248. ];
  1249. $post_data = [
  1250. 'model' => $model,
  1251. 'messages' => $messages,
  1252. 'max_tokens' => 8192,
  1253. 'temperature' => 0.7,
  1254. 'frequency_penalty' => 0,
  1255. 'presence_penalty' => 0,
  1256. 'response_format' => ['type' => 'text'],
  1257. 'stream' => false
  1258. ];
  1259. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1260. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  1261. $response = $result->getBody()->getContents();
  1262. $response_arr = json_decode($response, true);
  1263. $content = '';
  1264. $usage = [];
  1265. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  1266. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  1267. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  1268. }
  1269. // \Log::info('返回值内容: '.$content);
  1270. $script_arr = [];
  1271. // 处理结果
  1272. if ($content) {
  1273. $script_arr = handleScriptContent($content);
  1274. }
  1275. return [
  1276. 'script' => $script_arr,
  1277. 'answer' => $content,
  1278. 'usage' => $usage
  1279. ];
  1280. }
  1281. public function saveScript($data) {
  1282. $script_arr =getProp($data, 'script', []);
  1283. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1284. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1285. $script_id = getProp($data, 'script_id');
  1286. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1287. try {
  1288. DB::beginTransaction();
  1289. $update_data = [
  1290. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1291. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1292. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1293. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1294. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1295. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1296. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1297. 'status' => 3,
  1298. 'start_episode_sequence' => $start_episode_sequence,
  1299. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1300. 'episode_num' => count($script_arr['episodes']),
  1301. 'updated_at' => date('Y-m-d H:i:s')
  1302. ];
  1303. // 保存剧本内容
  1304. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1305. if (!$boolen) {
  1306. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1307. Utils::throwError('20003:剧本内容保存失败');
  1308. }
  1309. // 保存分集内容
  1310. // 删除历史分集内容
  1311. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1312. $episodes = [];
  1313. $sequence = 1;
  1314. foreach ($script_arr['episodes'] as $episode) {
  1315. $segment_number = 1;
  1316. foreach($episode['segments'] as $segment) {
  1317. $episodes[] = [
  1318. 'script_id' => $script_id,
  1319. 'episode_number' => $episode['episode_number'],
  1320. 'title' => $episode['title'],
  1321. // 'content' => $episode['content'],
  1322. 'content' => '',
  1323. 'segment_number' => $segment_number,
  1324. 'segment_content' => $segment['segment_content'],
  1325. 'sequence' => $sequence,
  1326. 'created_at' => date('Y-m-d H:i:s'),
  1327. 'updated_at' => date('Y-m-d H:i:s')
  1328. ];
  1329. $sequence++;
  1330. $segment_number++;
  1331. }
  1332. }
  1333. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1334. if (!$boolen2) {
  1335. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1336. Utils::throwError('20003:分集内容保存失败');
  1337. }
  1338. } catch (\Exception $e) {
  1339. DB::rollBack();
  1340. Utils::throwError('20003:'.$e->getMessage());
  1341. }
  1342. DB::commit();
  1343. return true;
  1344. }
  1345. public function exportScript($data) {
  1346. $script = $this->scriptInfo($data);
  1347. $export_type = getProp($data, 'export_type', 'txt');
  1348. // 生成文件名
  1349. $filename = $script['script_name'] . '_' . date('YmdHis');
  1350. // 根据导出类型生成不同格式的文件
  1351. switch ($export_type) {
  1352. case 'txt':
  1353. return $this->exportScriptAsTxt($script, $filename);
  1354. case 'pdf':
  1355. return $this->exportScriptAsPdf($script, $filename);
  1356. default:
  1357. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  1358. }
  1359. }
  1360. /**
  1361. * 导出剧本为TXT格式
  1362. */
  1363. private function exportScriptAsTxt($script, $filename) {
  1364. // 构建TXT内容
  1365. $content = $this->buildScriptContent($script);
  1366. // 设置响应头,直接下载
  1367. header('Content-Type: text/plain; charset=utf-8');
  1368. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  1369. header('Content-Length: ' . strlen($content));
  1370. // 输出内容并结束
  1371. echo $content;
  1372. exit();
  1373. }
  1374. /**
  1375. * 导出剧本为PDF格式
  1376. */
  1377. private function exportScriptAsPdf($script, $filename) {
  1378. // 使用HTML转PDF的方式来更好地支持中文
  1379. $htmlContent = $this->buildScriptHtmlForPdf($script);
  1380. // 创建PDF实例
  1381. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1382. // 设置文档信息
  1383. $pdf->SetCreator('剧本导出系统');
  1384. $pdf->SetAuthor('系统');
  1385. $pdf->SetTitle($script['script_name']);
  1386. $pdf->SetSubject('剧本导出');
  1387. // 设置边距
  1388. $pdf->SetMargins(15, 15, 15);
  1389. $pdf->SetAutoPageBreak(TRUE, 15);
  1390. // 添加页面
  1391. $pdf->AddPage();
  1392. // 注册并使用 simsun.ttf 字体
  1393. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  1394. // 使用HTML内容生成PDF
  1395. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  1396. // 直接输出PDF文件供下载
  1397. header('Content-Type: application/pdf');
  1398. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  1399. // 直接输出PDF内容
  1400. $pdf->Output($filename . '.pdf', 'D');
  1401. exit();
  1402. }
  1403. /**
  1404. * 构建用于PDF的HTML内容
  1405. */
  1406. private function buildScriptHtmlForPdf($script) {
  1407. $html = '<style>
  1408. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  1409. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  1410. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  1411. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  1412. .info { margin-bottom: 8px; }
  1413. .episode { margin-bottom: 20px; page-break-inside: avoid; }
  1414. .segment { margin-bottom: 10px; margin-left: 20px; }
  1415. </style>';
  1416. // 标题
  1417. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  1418. // 剧本简介
  1419. if (!empty($script['intro'])) {
  1420. $html .= '<h2>剧本简介</h2>';
  1421. $html .= '<p>' . nl2br(htmlspecialchars($script['intro'])) . '</p>';
  1422. }
  1423. // 亮点
  1424. if (!empty($script['highlights'])) {
  1425. $html .= '<h2>亮点</h2>';
  1426. $html .= '<p>' . nl2br(htmlspecialchars($script['highlights'])) . '</p>';
  1427. }
  1428. // 核心矛盾
  1429. if (!empty($script['core_contradiction'])) {
  1430. $html .= '<h2>核心矛盾</h2>';
  1431. $html .= '<p>' . nl2br(htmlspecialchars($script['core_contradiction'])) . '</p>';
  1432. }
  1433. // 艺术风格
  1434. if (!empty($script['art_style'])) {
  1435. $html .= '<h2>艺术风格</h2>';
  1436. $html .= '<p>' . nl2br(htmlspecialchars($script['art_style'])) . '</p>';
  1437. }
  1438. // 角色列表
  1439. if (!empty($script['roles']) && is_array($script['roles'])) {
  1440. $html .= '<h2>角色列表</h2>';
  1441. $html .= '<ul>';
  1442. foreach ($script['roles'] as $role) {
  1443. if (is_array($role) || is_object($role)) {
  1444. $html .= '<li>' . htmlspecialchars(getProp($role, 'role', '')) . ':' . htmlspecialchars(getProp($role, 'description', '')) . '</li>';
  1445. } else {
  1446. $html .= '<li>' . htmlspecialchars($role) . '</li>';
  1447. }
  1448. }
  1449. $html .= '</ul>';
  1450. }
  1451. // 角色关系
  1452. if (!empty($script['role_relationship'])) {
  1453. $html .= '<h2>角色关系</h2>';
  1454. $html .= '<p>' . nl2br(htmlspecialchars($script['role_relationship'])) . '</p>';
  1455. }
  1456. // 场景列表
  1457. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1458. $html .= '<h2>场景列表</h2>';
  1459. $html .= '<ul>';
  1460. foreach ($script['scenes'] as $scene) {
  1461. if (is_array($scene) || is_object($scene)) {
  1462. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene', '')) . ':' . htmlspecialchars(getProp($scene, 'description', '')) . '</li>';
  1463. } else {
  1464. $html .= '<li>' . htmlspecialchars($scene) . '</li>';
  1465. }
  1466. }
  1467. $html .= '</ul>';
  1468. }
  1469. // 分集内容
  1470. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1471. $html .= '<h2>分集内容</h2>';
  1472. foreach ($script['episodes'] as $episode) {
  1473. $html .= '<div class="episode">';
  1474. $html .= '<h3>第' . htmlspecialchars($episode['episode_number']) . '集';
  1475. if (!empty($episode['title'])) {
  1476. $html .= ':' . htmlspecialchars($episode['title']);
  1477. }
  1478. $html .= '</h3>';
  1479. // 处理分段内容
  1480. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1481. foreach ($episode['segments'] as $segment) {
  1482. if (!empty($segment['segment_content'])) {
  1483. $html .= '<div class="segment">';
  1484. if (!empty($segment['segment_number'])) {
  1485. $html .= '<strong>第' . htmlspecialchars($segment['segment_number']) . '段</strong><br>';
  1486. }
  1487. $html .= nl2br(htmlspecialchars($segment['segment_content']));
  1488. $html .= '</div>';
  1489. }
  1490. }
  1491. }
  1492. $html .= '</div>';
  1493. }
  1494. }
  1495. return $html;
  1496. }
  1497. /**
  1498. * 构建PDF内容
  1499. */
  1500. private function buildPdfContent($pdf, $script) {
  1501. // 标题
  1502. $pdf->SetFont('dejavusans', 'B', 18);
  1503. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  1504. $pdf->Ln(5);
  1505. // 基本信息
  1506. $pdf->SetFont('dejavusans', '', 12);
  1507. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  1508. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  1509. $pdf->Ln(5);
  1510. // 剧本简介
  1511. if (!empty($script['intro'])) {
  1512. $pdf->SetFont('dejavusans', 'B', 14);
  1513. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  1514. $pdf->SetFont('dejavusans', '', 12);
  1515. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  1516. $pdf->Ln(3);
  1517. }
  1518. // 亮点
  1519. if (!empty($script['highlights'])) {
  1520. $pdf->SetFont('dejavusans', 'B', 14);
  1521. $pdf->Cell(0, 10, '亮点', 0, 1);
  1522. $pdf->SetFont('dejavusans', '', 12);
  1523. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  1524. $pdf->Ln(3);
  1525. }
  1526. // 核心矛盾
  1527. if (!empty($script['core_contradiction'])) {
  1528. $pdf->SetFont('dejavusans', 'B', 14);
  1529. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  1530. $pdf->SetFont('dejavusans', '', 12);
  1531. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  1532. $pdf->Ln(3);
  1533. }
  1534. // 艺术风格
  1535. if (!empty($script['art_style'])) {
  1536. $pdf->SetFont('dejavusans', 'B', 14);
  1537. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  1538. $pdf->SetFont('dejavusans', '', 12);
  1539. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  1540. $pdf->Ln(3);
  1541. }
  1542. // 备注
  1543. if (!empty($script['remark'])) {
  1544. $pdf->SetFont('dejavusans', 'B', 14);
  1545. $pdf->Cell(0, 10, '备注', 0, 1);
  1546. $pdf->SetFont('dejavusans', '', 12);
  1547. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  1548. $pdf->Ln(3);
  1549. }
  1550. // 角色列表
  1551. if (!empty($script['roles']) && is_array($script['roles'])) {
  1552. $pdf->SetFont('dejavusans', 'B', 14);
  1553. $pdf->Cell(0, 10, '角色列表', 0, 1);
  1554. $pdf->SetFont('dejavusans', '', 12);
  1555. foreach ($script['roles'] as $index => $role) {
  1556. if (is_array($role) || is_object($role)) {
  1557. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  1558. } else {
  1559. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  1560. }
  1561. }
  1562. $pdf->Ln(3);
  1563. }
  1564. // 角色关系
  1565. if (!empty($script['role_relationship'])) {
  1566. $pdf->SetFont('dejavusans', 'B', 14);
  1567. $pdf->Cell(0, 10, '角色关系', 0, 1);
  1568. $pdf->SetFont('dejavusans', '', 12);
  1569. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  1570. $pdf->Ln(3);
  1571. }
  1572. // 场景列表
  1573. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1574. $pdf->SetFont('dejavusans', 'B', 14);
  1575. $pdf->Cell(0, 10, '场景列表', 0, 1);
  1576. $pdf->SetFont('dejavusans', '', 12);
  1577. foreach ($script['scenes'] as $index => $scene) {
  1578. if (is_array($scene) || is_object($scene)) {
  1579. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  1580. } else {
  1581. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  1582. }
  1583. }
  1584. $pdf->Ln(5);
  1585. }
  1586. // 分集内容
  1587. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1588. $pdf->SetFont('dejavusans', 'B', 16);
  1589. $pdf->Cell(0, 12, '分集内容', 0, 1);
  1590. $pdf->Ln(3);
  1591. foreach ($script['episodes'] as $episode) {
  1592. // 检查是否需要新页面
  1593. if ($pdf->GetY() > 250) {
  1594. $pdf->AddPage();
  1595. }
  1596. $pdf->SetFont('dejavusans', 'B', 14);
  1597. $episodeTitle = '第' . $episode['episode_number'] . '集';
  1598. if (!empty($episode['title'])) {
  1599. $episodeTitle .= ':' . $episode['title'];
  1600. }
  1601. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  1602. // 处理分段内容
  1603. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1604. $pdf->SetFont('dejavusans', '', 12);
  1605. foreach ($episode['segments'] as $segment) {
  1606. if (!empty($segment['segment_content'])) {
  1607. // 如果有分段编号,显示分段标题
  1608. if (!empty($segment['segment_number'])) {
  1609. $pdf->SetFont('dejavusans', 'B', 12);
  1610. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  1611. $pdf->SetFont('dejavusans', '', 12);
  1612. }
  1613. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  1614. $pdf->Ln(2);
  1615. }
  1616. }
  1617. }
  1618. $pdf->Ln(5);
  1619. }
  1620. }
  1621. }
  1622. /**
  1623. * 构建剧本文本内容
  1624. */
  1625. private function buildScriptContent($script) {
  1626. $content = '';
  1627. // 剧本基本信息
  1628. if (!empty($script['intro'])) {
  1629. $content .= "###故事梗概\n" . $script['intro'] . "\n\n";
  1630. }
  1631. if (!empty($script['highlights'])) {
  1632. $content .= "###剧本亮点\n" . $script['highlights'] . "\n\n";
  1633. }
  1634. if (!empty($script['role_relationship'])) {
  1635. $content .= "###人物关系\n" . $script['role_relationship'] . "\n\n";
  1636. }
  1637. if (!empty($script['core_contradiction'])) {
  1638. $content .= "###核心矛盾\n" . $script['core_contradiction'] . "\n\n";
  1639. }
  1640. if (!empty($script['roles']) && is_array($script['roles'])) {
  1641. $content .= "###主体列表\n";
  1642. foreach ($script['roles'] as $role) {
  1643. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  1644. }
  1645. $content .= "\n\n";
  1646. }
  1647. if (!empty($script['art_style'])) {
  1648. $content .= "###美术风格\n" . $script['art_style'] . "\n\n";
  1649. }
  1650. // 场景信息
  1651. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1652. $content .= "###场景列表\n";
  1653. foreach ($script['scenes'] as $scene) {
  1654. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  1655. }
  1656. $content .= "\n\n";
  1657. }
  1658. // 分集内容
  1659. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1660. $content .= "###分集剧本\n";
  1661. foreach ($script['episodes'] as $episode) {
  1662. $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  1663. if (!empty($episode['title'])) {
  1664. $content .= ":" . $episode['title'];
  1665. }
  1666. $content .= "\n";
  1667. // 处理分镜
  1668. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1669. foreach ($episode['segments'] as $segment) {
  1670. $content .= "分镜" . $episode['episode_number'] . '-' . $segment['segment_number'] . "\n";
  1671. $content .= $segment['segment_content'] . "\n\n";
  1672. }
  1673. }
  1674. }
  1675. }
  1676. return $content;
  1677. }
  1678. /**
  1679. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1680. *
  1681. * @param array $data 包含以下参数:
  1682. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1683. * - question: 用户问题(可选)
  1684. * - model: 使用的模型(r1 或 v3,默认 v3)
  1685. * @return \Generator 返回生成器,用于流式输出
  1686. */
  1687. public function addChat($data) {
  1688. $uid = Site::getUid();
  1689. $file = getProp($data, 'file');
  1690. $content = getProp($data, 'content', '');
  1691. $bid = getProp($data, 'bid', 0);
  1692. $question =getProp($data, 'question', "请根据实例格式完成剧本大纲");
  1693. $prompt = getProp($data, 'prompt');
  1694. $model = getProp($data, 'model', 'v3');
  1695. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1696. $is_multi = getProp($data, 'is_multi', 1);
  1697. // if (!$file && !$content && !$bid) {
  1698. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1699. // }
  1700. // 提取文件内容
  1701. if ($file) {
  1702. $content = $this->extractFileContent($file);
  1703. if (!$content) {
  1704. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1705. }
  1706. } elseif ($bid) {
  1707. $content = $this->getContentByBid($bid);
  1708. if (!$content) {
  1709. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1710. }
  1711. } elseif ($content) {
  1712. $content = filterContent($content);
  1713. } elseif ($prompt) {
  1714. $content = $prompt;
  1715. }else {
  1716. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1717. }
  1718. // 美术风格
  1719. $input_art_style = getProp($data, 'art_style');
  1720. // 构建消息
  1721. $messages = [
  1722. [
  1723. 'role' => 'system',
  1724. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1725. 强制要求:\n
  1726. 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出\n
  1727. 普通要求:\n
  1728. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  1729. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  1730. 示例如下:\n
  1731. ###剧本名:西昆仑
  1732. ###故事梗概
  1733. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1734. ###剧本亮点
  1735. 亮点1:绝境奇药,生死一线
  1736. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1737. 亮点2:结拜兄妹,化解尴尬
  1738. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1739. 亮点3:纤发夺命,情愫暗涌
  1740. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1741. ###人物关系
  1742. 阿雪与梁萧之间存在兄妹之情。
  1743. ###核心矛盾
  1744. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1745. ###主体列表
  1746. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1747. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1748. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1749. 阴阳球:天地异宝,能化生精气,救人于危难。
  1750. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1751. ###美术风格
  1752. 基础画风风格词:厚涂古风
  1753. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1754. ###场景列表
  1755. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"
  1756. ],
  1757. [
  1758. 'role' => 'user',
  1759. 'content' => "以下是文档内容:
  1760. {$content}
  1761. 用户问题:
  1762. {$question}"
  1763. ]
  1764. ];
  1765. $post_data = [
  1766. 'model' => $model,
  1767. 'messages' => $messages,
  1768. 'max_tokens' => 8192,
  1769. 'temperature' => 0.7,
  1770. 'frequency_penalty' => 0,
  1771. 'presence_penalty' => 0,
  1772. 'response_format' => ['type' => 'text'],
  1773. 'stream' => true // 启用流式输出
  1774. ];
  1775. // 根据模型类型选择调用方法
  1776. $fullContent = '';
  1777. $fullReasoningContent = '';
  1778. $usage = [];
  1779. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat'])) {
  1780. // R1模型使用DeepSeek API
  1781. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1782. } else {
  1783. // V3模型使用火山引擎API
  1784. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1785. }
  1786. // 处理流式输出
  1787. foreach ($streamGenerator as $chunk) {
  1788. if (isset($chunk['type'])) {
  1789. if ($chunk['type'] === 'done') {
  1790. // 最终结果
  1791. $fullContent = $chunk['full_content'];
  1792. $fullReasoningContent = $chunk['full_reasoning'];
  1793. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1794. } else {
  1795. // 逐块yield数据
  1796. yield $chunk;
  1797. }
  1798. }
  1799. }
  1800. dLog('deepseek')->info('完整内容: '.$fullContent);
  1801. // 处理完整内容并返回最终结果
  1802. $script_arr = [];
  1803. if ($fullContent) {
  1804. $script_arr = handleScriptContent($fullContent);
  1805. }
  1806. // 替换美术风格
  1807. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  1808. if ($mappedArtStyle !== '') {
  1809. $script_arr['art_style'] = $mappedArtStyle;
  1810. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  1811. }
  1812. // 新建动漫
  1813. $anime_name = getProp($script_arr, 'script_name');
  1814. if (!$anime_name) {
  1815. yield [
  1816. 'type' => 'done',
  1817. 'answer' => $fullContent,
  1818. 'reasoning' => $fullReasoningContent,
  1819. 'usage' => $usage,
  1820. 'error' => '未能识别到剧本名称,请确认内容是否符合要求'
  1821. ];
  1822. }
  1823. // 确认对话名称唯一性
  1824. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  1825. $anime_name = $anime_name . '_' . date('YmdHis');
  1826. }
  1827. $table_data = [
  1828. 'user_id' => $uid,
  1829. 'anime_name' => $anime_name,
  1830. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1831. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1832. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1833. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1834. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1835. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1836. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1837. 'status' => '解析完成',
  1838. 'content' => $content,
  1839. // 'start_episode_sequence' => 1,
  1840. // 'end_episode_sequence' => count($script_arr['episodes']),
  1841. // 'episode_num' => count($script_arr['episodes']),
  1842. 'is_multi' => $is_multi,
  1843. 'generate_status' => '待执行',
  1844. 'created_at' => date('Y-m-d H:i:s'),
  1845. 'updated_at' => date('Y-m-d H:i:s')
  1846. ];
  1847. try {
  1848. DB::beginTransaction();
  1849. // 新建动漫大纲
  1850. $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  1851. if (!$anime_id) {
  1852. dLog('deepseek')->info('对话保存失败', $table_data);
  1853. Utils::throwError('20003:对话保存失败');
  1854. }
  1855. // 保存对话记录
  1856. $records = [
  1857. [
  1858. 'uid' => $uid,
  1859. 'anime_id' => $anime_id,
  1860. 'sequence' => 0,
  1861. 'role' => 'user',
  1862. 'content' => "用户问题:\n
  1863. {$prompt}\n\n
  1864. 以下是文档内容:\n
  1865. {$content}",
  1866. 'created_at' => date('Y-m-d H:i:s'),
  1867. 'updated_at' => date('Y-m-d H:i:s')
  1868. ],
  1869. [
  1870. 'uid' => $uid,
  1871. 'anime_id' => $anime_id,
  1872. 'sequence' => 0,
  1873. 'role' => 'assistant',
  1874. 'content' => $fullContent,
  1875. 'created_at' => date('Y-m-d H:i:s'),
  1876. 'updated_at' => date('Y-m-d H:i:s')
  1877. ]
  1878. ];
  1879. // 保存对话记录
  1880. $boolen3 = DB::table('mp_anime_records')->insert($records);
  1881. if (!$boolen3) {
  1882. Utils::throwError('20003:对话记录保存失败');
  1883. }
  1884. }catch (\Exception $e) {
  1885. DB::rollBack();
  1886. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  1887. yield [
  1888. 'type' => 'done',
  1889. 'answer' => $fullContent,
  1890. 'reasoning' => $fullReasoningContent,
  1891. 'usage' => $usage,
  1892. 'error' => $e->getMessage(),
  1893. ];
  1894. }
  1895. DB::commit();
  1896. $table_data['anime_id'] = $anime_id;
  1897. $table_data['roles'] = json_decode($table_data['roles'], true);
  1898. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  1899. // $table_data['episodes'] = $script_arr['episodes'];
  1900. unset($table_data['created_at']);
  1901. unset($table_data['updated_at']);
  1902. unset($table_data['status']);
  1903. yield [
  1904. 'type' => 'done',
  1905. 'script' => $table_data,
  1906. 'answer' => $fullContent,
  1907. 'reasoning' => $fullReasoningContent,
  1908. 'usage' => $usage
  1909. ];
  1910. }
  1911. public function reGenerateAnime($data) {
  1912. $uid = Site::getUid();
  1913. $file = getProp($data, 'file');
  1914. $content = getProp($data, 'content', '');
  1915. $bid = getProp($data, 'bid', 0);
  1916. $anime_id = getProp($data, 'anime_id');
  1917. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1918. if (!$anime) {
  1919. Utils::throwError('20003:该对话不存在');
  1920. }
  1921. $question =getProp($data, 'question', "请根据实例格式完成剧本大纲");
  1922. $prompt = getProp($data, 'prompt', '帮我根据给出的内容生成短剧大纲');
  1923. $model = getProp($data, 'model', 'v3');
  1924. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1925. // 提取文件内容
  1926. if ($file) {
  1927. $content = $this->extractFileContent($file);
  1928. if (!$content) {
  1929. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1930. }
  1931. } elseif ($bid) {
  1932. $content = $this->getContentByBid($bid);
  1933. if (!$content) {
  1934. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1935. }
  1936. } elseif ($content) {
  1937. $content = filterContent($content);
  1938. } else {
  1939. $content = filterContent(getProp($anime, 'content'));
  1940. }
  1941. // 美术风格
  1942. $input_art_style = getProp($data, 'art_style');
  1943. $system_message = [
  1944. 'role' => 'system',
  1945. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1946. 强制要求:\n
  1947. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出\n
  1948. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答\n
  1949. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等\n
  1950. 普通要求:\n
  1951. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  1952. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  1953. 示例如下:\n
  1954. ###剧本名:西昆仑
  1955. ###故事梗概
  1956. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1957. ###剧本亮点
  1958. 亮点1:绝境奇药,生死一线
  1959. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1960. 亮点2:结拜兄妹,化解尴尬
  1961. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1962. 亮点3:纤发夺命,情愫暗涌
  1963. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1964. ###人物关系
  1965. 阿雪与梁萧之间存在兄妹之情。
  1966. ###核心矛盾
  1967. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1968. ###主体列表
  1969. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1970. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1971. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1972. 阴阳球:天地异宝,能化生精气,救人于危难。
  1973. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1974. ###美术风格
  1975. 基础画风风格词:厚涂古风
  1976. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1977. ###场景列表
  1978. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"
  1979. ];
  1980. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  1981. $episode_count = $this->extractEpisodeNumber($prompt);
  1982. if ((int)getProp($anime, 'is_multi') !== 1) {
  1983. yield [
  1984. 'type' => 'done',
  1985. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  1986. 'reasoning' => '',
  1987. 'usage' => []
  1988. ];
  1989. return;
  1990. }
  1991. if ($episode_count) {
  1992. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  1993. $system_message = [
  1994. 'role' => 'system',
  1995. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1996. 强制要求:\n
  1997. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出\n
  1998. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答\n
  1999. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等\n
  2000. 普通要求:\n
  2001. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2002. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  2003. 3.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  2004. 示例如下:\n
  2005. ###剧本名:西昆仑
  2006. ###故事梗概
  2007. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2008. ###剧本亮点
  2009. 亮点1:绝境奇药,生死一线
  2010. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2011. 亮点2:结拜兄妹,化解尴尬
  2012. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2013. 亮点3:纤发夺命,情愫暗涌
  2014. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2015. ###人物关系
  2016. 阿雪与梁萧之间存在兄妹之情。
  2017. ###核心矛盾
  2018. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2019. ###主体列表
  2020. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2021. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2022. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2023. 阴阳球:天地异宝,能化生精气,救人于危难。
  2024. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2025. ###美术风格
  2026. 基础画风风格词:厚涂古风
  2027. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2028. ###场景列表
  2029. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2030. ###分集详细内容
  2031. ##第1章 重生
  2032. 我重生了。
  2033. 源于一个男人偏执的暗恋。
  2034. ##第2章 相救
  2035. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  2036. 我眼睛扫向站在锅炉后的卞大伟。"
  2037. ];
  2038. // 构建消息
  2039. $messages = [
  2040. $system_message,
  2041. [
  2042. 'role' => 'user',
  2043. 'content' => "以下是文档内容:
  2044. {$content}
  2045. 用户问题:
  2046. {$question}"
  2047. ]
  2048. ];
  2049. }else {
  2050. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  2051. // 构建消息
  2052. $messages = [
  2053. $system_message,
  2054. [
  2055. 'role' => 'user',
  2056. 'content' => "以下是文档内容:
  2057. {$content}
  2058. 用户问题:
  2059. {$question}"
  2060. ]
  2061. ];
  2062. }else {
  2063. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  2064. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  2065. return (array)$value;
  2066. })->toArray();
  2067. array_unshift($messages, $system_message);
  2068. $messages[] = [
  2069. 'role' => 'user',
  2070. 'content' => $prompt
  2071. ];
  2072. }
  2073. }
  2074. $post_data = [
  2075. 'model' => $model,
  2076. 'messages' => $messages,
  2077. 'max_tokens' => 8192,
  2078. 'temperature' => 0.7,
  2079. 'frequency_penalty' => 0,
  2080. 'presence_penalty' => 0,
  2081. 'response_format' => ['type' => 'text'],
  2082. 'stream' => true // 启用流式输出
  2083. ];
  2084. // 根据模型类型选择调用方法
  2085. $fullContent = '';
  2086. $fullReasoningContent = '';
  2087. $usage = [];
  2088. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat'])) {
  2089. // R1模型使用DeepSeek API
  2090. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2091. } else {
  2092. // V3模型使用火山引擎API
  2093. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2094. }
  2095. // 处理流式输出
  2096. foreach ($streamGenerator as $chunk) {
  2097. if (isset($chunk['type'])) {
  2098. if ($chunk['type'] === 'done') {
  2099. // 最终结果
  2100. $fullContent = $chunk['full_content'];
  2101. $fullReasoningContent = $chunk['full_reasoning'];
  2102. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2103. } else {
  2104. // 逐块yield数据
  2105. yield $chunk;
  2106. }
  2107. }
  2108. }
  2109. dLog('deepseek')->info('完整内容: '.$fullContent);
  2110. // 处理完整内容并返回最终结果
  2111. $script_arr = [];
  2112. if ($fullContent) {
  2113. $script_arr = handleScriptContent($fullContent);
  2114. }
  2115. // 替换美术风格
  2116. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2117. if ($mappedArtStyle !== '') {
  2118. $script_arr['art_style'] = $mappedArtStyle;
  2119. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2120. }
  2121. $table_data = [
  2122. 'user_id' => $uid,
  2123. // 'anime_name' => $anime_name,
  2124. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2125. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2126. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2127. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2128. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2129. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2130. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2131. 'status' => '解析完成',
  2132. 'generate_status' => '待执行',
  2133. 'updated_at' => date('Y-m-d H:i:s')
  2134. ];
  2135. // 如果是修改集数,则将content内容更新(会改变原文)
  2136. if (isset($episode_count) && $episode_count > 0) {
  2137. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  2138. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  2139. }else {
  2140. $chapters = $this->splitContent($content);
  2141. $chapter_count = count($chapters);
  2142. if ($chapter_count > 0) {
  2143. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  2144. }
  2145. }
  2146. try {
  2147. DB::beginTransaction();
  2148. // 新建动漫大纲
  2149. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2150. if (!$boolen) {
  2151. dLog('deepseek')->info('对话修改失败', $table_data);
  2152. Utils::throwError('20003:对话修改失败');
  2153. }
  2154. // 保存对话记录
  2155. $records = [
  2156. [
  2157. 'uid' => $uid,
  2158. 'anime_id' => $anime_id,
  2159. 'sequence' => 0,
  2160. 'role' => 'user',
  2161. 'content' => $prompt,
  2162. 'created_at' => date('Y-m-d H:i:s'),
  2163. 'updated_at' => date('Y-m-d H:i:s')
  2164. ],
  2165. [
  2166. 'uid' => $uid,
  2167. 'anime_id' => $anime_id,
  2168. 'sequence' => 0,
  2169. 'role' => 'assistant',
  2170. 'content' => $fullContent,
  2171. 'created_at' => date('Y-m-d H:i:s'),
  2172. 'updated_at' => date('Y-m-d H:i:s')
  2173. ]
  2174. ];
  2175. // 保存对话记录
  2176. $boolen3 = DB::table('mp_anime_records')->insert($records);
  2177. if (!$boolen3) {
  2178. Utils::throwError('20003:对话记录保存失败');
  2179. }
  2180. }catch (\Exception $e) {
  2181. DB::rollBack();
  2182. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2183. yield [
  2184. 'type' => 'done',
  2185. 'answer' => $fullContent,
  2186. 'reasoning' => $fullReasoningContent,
  2187. 'usage' => $usage,
  2188. 'error' => $e->getMessage(),
  2189. ];
  2190. }
  2191. DB::commit();
  2192. $table_data['anime_id'] = $anime_id;
  2193. $table_data['roles'] = json_decode($table_data['roles'], true);
  2194. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  2195. unset($table_data['updated_at']);
  2196. unset($table_data['status']);
  2197. yield [
  2198. 'type' => 'done',
  2199. 'script' => $table_data,
  2200. 'answer' => $fullContent,
  2201. 'reasoning' => $fullReasoningContent,
  2202. 'usage' => $usage
  2203. ];
  2204. }
  2205. public function chat($data) {
  2206. $uid = Site::getUid();
  2207. $anime_id = getProp($data, 'anime_id');
  2208. $file = getProp($data, 'file');
  2209. $content = getProp($data, 'content', '');
  2210. $bid = getProp($data, 'bid', 0);
  2211. $episode_number = getProp($data, 'episode_number', 1);
  2212. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  2213. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  2214. if (!$anime) Utils::throwError('20003:该对话不存在!');
  2215. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  2216. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  2217. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  2218. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  2219. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  2220. $roles = is_array($roles) ? $roles : [];
  2221. $scenes = is_array($scenes) ? $scenes : [];
  2222. // 转换主体列表和场景列表的格式
  2223. $roles_content = $this->buildEpisodeItemContent($roles, 'role');
  2224. $scenes_content = $this->buildEpisodeItemContent($scenes, 'scene');
  2225. // 获取音色列表
  2226. // $timbres = DB::table('mp_timbres')->select('timbre_name')->where('is_enabled', 1)->where('id', '<=', 15)->get()->map(function ($value) {
  2227. // $value = (array)$value;
  2228. // $value['timbre_name'] = str_replace('(多情感)', '', $value['timbre_name']);
  2229. // return $value;
  2230. // })->pluck('timbre_name')->toArray();
  2231. // $timbres_content = implode('、', $timbres);
  2232. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2233. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2234. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2235. 中年女:邻居阿姨
  2236. 老年男:幽默大爷
  2237. 老年女:婆婆
  2238. 萌娃:奶气萌娃";
  2239. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  2240. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  2241. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  2242. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  2243. // 提取文件内容
  2244. if ($file) {
  2245. $uploaded_content = $this->extractFileContent($file);
  2246. if (!$uploaded_content) {
  2247. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2248. }
  2249. } elseif ($bid) {
  2250. $uploaded_content = $this->getContentByBid($bid);
  2251. if (!$uploaded_content) {
  2252. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2253. }
  2254. }elseif ($content) {
  2255. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  2256. }else {
  2257. $uploaded_content = '';
  2258. }
  2259. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  2260. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2261. 强制要求:
  2262. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2263. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2264. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等\n
  2265. 普通要求:
  2266. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}
  2267. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):\n{$roles_content}
  2268. 2.1如果分集内容中出现了<主体列表>中不存在的新主体,则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在主题列表中
  2269. 2.2主体列表的音色必须在以下音色中($timbres_content)选择,需要根据:符号前面的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来
  2270. 3.<场景列表>必须在以下场景中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):\n{$scenes_content}
  2271. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2272. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2273. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音音色”、“台词内容”和“画面类型”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2274. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2275. 4.4“分镜信息”中的“台词内容”需与原文中的台词完全一致,不得修改或添加任何内容。
  2276. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2277. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)
  2278. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无
  2279. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面\n
  2280. 示例格式:\n
  2281. 第1集:隐形的守护者
  2282. ###故事梗概
  2283. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  2284. ###美术风格
  2285. 基础画风风格词:韩漫二次元
  2286. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  2287. ###主体列表
  2288. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{{甜心小美}}
  2289. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{{爽快思思}}
  2290. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{{阳光青年}}
  2291. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。{{广州德哥}}
  2292. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。{{邻居阿姨}}
  2293. ###场景列表
  2294. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  2295. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  2296. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  2297. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  2298. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  2299. ###分镜剧本
  2300. ##第1幕:徐家老旧厨房 白天 室内
  2301. 分镜1
  2302. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2303. 场景:徐家老旧厨房
  2304. 构图设计:全景,低角度仰视
  2305. 运镜调度:手持拍摄
  2306. 配音角色:旁白
  2307. 出镜角色:许芸-校服装、徐母
  2308. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2309. 画面类型:普通画面
  2310. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2311. 分镜2
  2312. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2313. 场景:徐家老旧厨房
  2314. 构图设计:近景,徐母面部特写
  2315. 运镜调度:固定镜头
  2316. 配音角色:徐母
  2317. 出镜角色:徐母
  2318. 台词内容:问我夜不归宿死哪儿去了。
  2319. 画面类型:对口型
  2320. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2321. ##第2幕:徐家简陋客厅 黄昏 室内
  2322. 分镜3
  2323. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2324. 场景:徐家简陋客厅
  2325. 构图设计:全景,景深虚化
  2326. 运镜调度:固定镜头
  2327. 配音角色:旁白
  2328. 出镜角色:无
  2329. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2330. 画面类型:普通画面
  2331. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2332. 分镜4
  2333. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2334. 场景:徐家简陋客厅
  2335. 构图设计:特写,火车票
  2336. 运镜调度:固定镜头
  2337. 配音角色:旁白
  2338. 出镜角色:无
  2339. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2340. 画面类型:普通画面
  2341. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  2342. \n\n";
  2343. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  2344. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  2345. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  2346. $prompt = $origin_prompt;
  2347. // 获取章节内容
  2348. $full_content = getProp($anime, 'content');
  2349. // 根据章节内容拆分章节
  2350. $chapters = $this->splitContent($full_content);
  2351. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2352. $messages = [];
  2353. if ($prompt == '确认分镜大纲') {
  2354. $content = $uploaded_content ?: $chapter_content;
  2355. if ((int)getProp($anime, 'is_multi') !== 1) $content = $full_content; // 单剧集使用全文
  2356. if (!$content) {
  2357. Utils::throwError('20003:章节内容无法获取,请确认');
  2358. }
  2359. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  2360. // 构建消息
  2361. $messages[] =
  2362. [
  2363. 'role' => 'user',
  2364. 'content' => $question
  2365. ];
  2366. }else if ($prompt == '继续策划下一集') {
  2367. $content = $uploaded_content ?: $chapter_content;
  2368. if (!$content) {
  2369. Utils::throwError('20003:章节内容无法获取,请确认');
  2370. }
  2371. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  2372. // 获取上一集最后记录
  2373. $prev_sequence = $episode_number - 1;
  2374. $messages = $this->getEpisodeChatMessages($anime_id, $prev_sequence);
  2375. // 构建消息
  2376. $messages[] =
  2377. [
  2378. 'role' => 'user',
  2379. 'content' => $question
  2380. ];
  2381. }else {
  2382. $content = $uploaded_content ?: trim((string)getProp($base_episode, 'content'));
  2383. if (!$content) {
  2384. $content = $chapter_content ?: $full_content;
  2385. }
  2386. if (!$content) {
  2387. Utils::throwError('20003:章节内容无法获取,请确认');
  2388. }
  2389. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  2390. $question = $demo . "\n请基于以上历史对话记录,重新生成第{$episode_number}集完整的新版本剧集,并严格按示例格式输出完整内容。"
  2391. . "\n\n本次修改要求如下:\n{$origin_prompt}";
  2392. $messages[] =
  2393. [
  2394. 'role' => 'user',
  2395. 'content' => $question
  2396. ];
  2397. }
  2398. $model = getProp($data, 'model', 'v3');
  2399. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2400. $post_data = [
  2401. 'model' => $model,
  2402. 'messages' => $messages,
  2403. 'max_tokens' => 8192,
  2404. 'temperature' => 0.7,
  2405. 'frequency_penalty' => 0,
  2406. 'presence_penalty' => 0,
  2407. 'response_format' => ['type' => 'text'],
  2408. 'stream' => true // 启用流式输出
  2409. ];
  2410. // 根据模型类型选择调用方法
  2411. $fullContent = '';
  2412. $fullReasoningContent = '';
  2413. $usage = [];
  2414. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat'])) {
  2415. // R1模型使用DeepSeek API
  2416. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2417. } else {
  2418. // V3模型使用火山引擎API
  2419. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2420. }
  2421. // 处理流式输出
  2422. foreach ($streamGenerator as $chunk) {
  2423. if (isset($chunk['type'])) {
  2424. if ($chunk['type'] === 'done') {
  2425. // 最终结果
  2426. $fullContent = $chunk['full_content'];
  2427. $fullReasoningContent = $chunk['full_reasoning'];
  2428. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2429. } else {
  2430. // 逐块yield数据
  2431. yield $chunk;
  2432. }
  2433. }
  2434. }
  2435. dLog('deepseek')->info('完整内容: '.$fullContent);
  2436. // 处理完整内容并返回最终结果
  2437. $episode_arr = handleEpisodeContent($fullContent);
  2438. if (empty($episode_arr['acts'])) {
  2439. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  2440. yield [
  2441. 'type' => 'done',
  2442. 'episode' => [],
  2443. 'answer' => $fullContent,
  2444. 'reasoning' => $fullReasoningContent,
  2445. 'usage' => $usage
  2446. ];
  2447. return;
  2448. }
  2449. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  2450. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  2451. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  2452. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  2453. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  2454. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  2455. $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  2456. $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  2457. dLog('deepseek')->info('修改后的数据: ', $merged_roles);
  2458. exit();
  2459. $now = date('Y-m-d H:i:s');
  2460. $del_flag = false;
  2461. try {
  2462. DB::beginTransaction();
  2463. $version_count = DB::table('mp_anime_episodes')
  2464. ->where('anime_id', $anime_id)
  2465. ->where('episode_number', $episode_number)
  2466. ->count('id');
  2467. $episode = [
  2468. 'anime_id' => $anime_id,
  2469. 'episode_number' => $episode_number,
  2470. 'title' => getProp($episode_arr, 'episode_title'),
  2471. 'content' => $content,
  2472. 'intro' => getProp($episode_arr, 'intro'),
  2473. 'art_style' => getProp($episode_arr, 'art_style'),
  2474. 'roles' => json_encode($merged_roles, 256),
  2475. 'scenes' => json_encode($merged_scenes, 256),
  2476. 'generate_status' => '待执行',
  2477. 'generate_at' => $now,
  2478. 'is_default' => 1,
  2479. 'updated_at' => $now,
  2480. ];
  2481. if ($is_regenerate_version) {
  2482. DB::table('mp_anime_episodes')
  2483. ->where('anime_id', $anime_id)
  2484. ->where('episode_number', $episode_number)
  2485. ->update(['is_default' => 0, 'updated_at' => $now]);
  2486. $episode['sequence'] = $version_count + 1;
  2487. $episode['created_at'] = $now;
  2488. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  2489. if (!$episode_id) {
  2490. Utils::throwError('20003:创建剧集版本失败');
  2491. }
  2492. } else {
  2493. $target_episode = $current_episode ?: $base_episode;
  2494. if ($target_episode) {
  2495. $episode_id = getProp($target_episode, 'id');
  2496. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  2497. DB::table('mp_anime_episodes')
  2498. ->where('anime_id', $anime_id)
  2499. ->where('episode_number', $episode_number)
  2500. ->where('id', '<>', $episode_id)
  2501. ->update(['is_default' => 0, 'updated_at' => $now]);
  2502. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  2503. if ($boolen2 === false) {
  2504. Utils::throwError('20003:分集内容保存失败');
  2505. }
  2506. $del_flag = true;
  2507. } else {
  2508. DB::table('mp_anime_episodes')
  2509. ->where('anime_id', $anime_id)
  2510. ->where('episode_number', $episode_number)
  2511. ->update(['is_default' => 0, 'updated_at' => $now]);
  2512. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  2513. $episode['created_at'] = $now;
  2514. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  2515. if (!$episode_id) {
  2516. Utils::throwError('20003:分集内容保存失败');
  2517. }
  2518. }
  2519. }
  2520. $segments = [];
  2521. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  2522. foreach ($acts as $act) {
  2523. $act_segments = getProp($act, 'segments', []);
  2524. if (!is_array($act_segments)) {
  2525. continue;
  2526. }
  2527. foreach ($act_segments as $segment) {
  2528. $segments[] = [
  2529. 'anime_id' => $anime_id,
  2530. 'episode_id' => $episode_id,
  2531. 'episode_number' => $episode_number,
  2532. 'act_number' => getProp($act, 'act_number'),
  2533. 'act_title' => getProp($act, 'act_title'),
  2534. 'segment_id' => getProp($segment, 'segment_id'),
  2535. 'segment_number' => getProp($segment, 'segment_number'),
  2536. 'segment_content' => getProp($segment, 'segment_content'),
  2537. 'description' => getProp($segment, 'description'),
  2538. 'composition' => getProp($segment, 'composition'),
  2539. 'camera_movement' => getProp($segment, 'camera_movement'),
  2540. 'voice_actor' => getProp($segment, 'voice_actor'),
  2541. 'dialogue' => getProp($segment, 'dialogue'),
  2542. 'frame_type' => getProp($segment, 'frame_type'),
  2543. 'scene' => getProp($segment, 'scene'),
  2544. 'characters' => getProp($segment, 'characters'),
  2545. 'tail_frame' => getProp($segment, 'tail_frame'),
  2546. 'created_at' => $now,
  2547. 'updated_at' => $now
  2548. ];
  2549. }
  2550. }
  2551. if ($segments) {
  2552. // 如果是更新剧集则需删除所有剧集分镜
  2553. if ($del_flag) DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->delete();
  2554. $boolen3 = DB::table('mp_episode_segments')->insert($segments);
  2555. if (!$boolen3) {
  2556. Utils::throwError('20003:分镜内容保存失败');
  2557. }
  2558. }
  2559. $record_content = $origin_prompt;
  2560. if ($uploaded_content !== '') {
  2561. $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  2562. }
  2563. $records = [
  2564. [
  2565. 'uid' => $uid,
  2566. 'anime_id' => $anime_id,
  2567. 'role' => 'user',
  2568. 'content' => $record_content,
  2569. 'sequence' => $episode_number,
  2570. 'episode_id' => $episode_id,
  2571. 'created_at' => $now,
  2572. 'updated_at' => $now
  2573. ],
  2574. [
  2575. 'uid' => $uid,
  2576. 'anime_id' => $anime_id,
  2577. 'role' => 'assistant',
  2578. 'content' => $fullContent,
  2579. 'sequence' => $episode_number,
  2580. 'episode_id' => $episode_id,
  2581. 'created_at' => $now,
  2582. 'updated_at' => $now
  2583. ]
  2584. ];
  2585. $boolen4 = DB::table('mp_anime_records')->insert($records);
  2586. if (!$boolen4) {
  2587. Utils::throwError('20003:对话记录保存失败');
  2588. }
  2589. }catch (\Exception $e) {
  2590. DB::rollBack();
  2591. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2592. yield [
  2593. 'type' => 'done',
  2594. 'answer' => $fullContent,
  2595. 'reasoning' => $fullReasoningContent,
  2596. 'usage' => $usage,
  2597. 'error' => $e->getMessage(),
  2598. ];
  2599. return;
  2600. }
  2601. DB::commit();
  2602. if ($is_global_generate_pics) {
  2603. // 批量生成全局角色图片
  2604. $this->batchSetGlobalRoleImg([
  2605. 'anime_id' => $anime_id,
  2606. ]);
  2607. // 批量生成全局场景图片
  2608. $this->batchSetGlobalSceneImg([
  2609. 'anime_id' => $anime_id,
  2610. ]);
  2611. }
  2612. $episode['episode_id'] = $episode_id;
  2613. $episode['roles'] = $merged_roles;
  2614. $episode['scenes'] = $merged_scenes;
  2615. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  2616. yield [
  2617. 'type' => 'done',
  2618. 'episode' => $episode,
  2619. 'answer' => $fullContent,
  2620. 'reasoning' => $fullReasoningContent,
  2621. 'usage' => $usage
  2622. ];
  2623. }
  2624. private function buildEpisodeItemContent(array $items, string $nameKey): string
  2625. {
  2626. $content = '';
  2627. foreach ($items as $item) {
  2628. $name = trim((string)getProp($item, $nameKey));
  2629. if ($name === '') {
  2630. continue;
  2631. }
  2632. $description = trim((string)getProp($item, 'description'));
  2633. $content .= $name . ': ' . $description . "\n";
  2634. }
  2635. return trim($content);
  2636. }
  2637. private function getEpisodeChatMessages($animeId, $sequence): array
  2638. {
  2639. if ((int)$sequence <= 0) {
  2640. return [];
  2641. }
  2642. return DB::table('mp_anime_records')
  2643. ->where('anime_id', $animeId)
  2644. ->where('sequence', $sequence)
  2645. ->select('role', 'content')
  2646. ->orderBy('created_at')
  2647. ->orderBy('id')
  2648. ->get()
  2649. ->map(function ($value) {
  2650. return (array)$value;
  2651. })
  2652. ->toArray();
  2653. }
  2654. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  2655. {
  2656. $existingMap = [];
  2657. foreach ($existingItems as $item) {
  2658. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  2659. if ($itemKey === '') {
  2660. continue;
  2661. }
  2662. $existingMap[$itemKey] = $item;
  2663. }
  2664. if (!$generatedItems) {
  2665. return array_values($existingItems);
  2666. }
  2667. $merged = [];
  2668. foreach ($generatedItems as $item) {
  2669. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  2670. if ($itemKey === '') {
  2671. continue;
  2672. }
  2673. if (isset($existingMap[$itemKey])) {
  2674. if (trim((string)getProp($item, 'description')) === '') {
  2675. $merged[] = $existingMap[$itemKey];
  2676. continue;
  2677. }
  2678. // 检查内容是否发生变化
  2679. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  2680. if (!$isChanged) {
  2681. // nameKey 和 description 一致,继承现有项的 URL
  2682. $mergedItem = [
  2683. $nameKey => trim((string)getProp($item, $nameKey)),
  2684. 'description' => trim((string)getProp($item, 'description')),
  2685. ];
  2686. // 继承现有项的 URL
  2687. $existingUrl = getProp($existingMap[$itemKey], 'url');
  2688. if (!empty($existingUrl)) {
  2689. $mergedItem['url'] = $existingUrl;
  2690. }
  2691. // 保留生成项的音色字段
  2692. $timbreName = getProp($item, 'timbre_name');
  2693. if (!empty($timbreName)) {
  2694. $mergedItem['timbre_name'] = $timbreName;
  2695. }
  2696. $timbreType = getProp($item, 'timbre_type');
  2697. if (!empty($timbreType)) {
  2698. $mergedItem['timbre_type'] = $timbreType;
  2699. }
  2700. $audioUrl = getProp($item, 'audio_url');
  2701. if (!empty($audioUrl)) {
  2702. $mergedItem['audio_url'] = $audioUrl;
  2703. }
  2704. $merged[] = $mergedItem;
  2705. } else {
  2706. // nameKey 或 description 不一致,重置 URL 但保留音色字段
  2707. $mergedItem = [
  2708. $nameKey => trim((string)getProp($item, $nameKey)),
  2709. 'description' => trim((string)getProp($item, 'description')),
  2710. ];
  2711. // 保留生成项的音色字段
  2712. $timbreName = getProp($item, 'timbre_name');
  2713. if (!empty($timbreName)) {
  2714. $mergedItem['timbre_name'] = $timbreName;
  2715. }
  2716. $timbreType = getProp($item, 'timbre_type');
  2717. if (!empty($timbreType)) {
  2718. $mergedItem['timbre_type'] = $timbreType;
  2719. }
  2720. $audioUrl = getProp($item, 'audio_url');
  2721. if (!empty($audioUrl)) {
  2722. $mergedItem['audio_url'] = $audioUrl;
  2723. }
  2724. // 不继承 URL(重置状态)
  2725. $merged[] = $mergedItem;
  2726. }
  2727. } else {
  2728. // 新增项,保留生成项的所有字段
  2729. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['timbre_name', 'timbre_type', 'audio_url']);
  2730. }
  2731. }
  2732. return $merged ?: array_values($existingItems);
  2733. }
  2734. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  2735. {
  2736. $resetItem = [
  2737. $nameKey => trim((string)getProp($item, $nameKey)),
  2738. 'description' => trim((string)getProp($item, 'description')),
  2739. ];
  2740. // 如果生成项本身有URL,保留它
  2741. $url = getProp($item, 'url');
  2742. if (!empty($url)) {
  2743. $resetItem['url'] = $url;
  2744. }
  2745. // 保留指定的字段
  2746. foreach ($preserveFields as $field) {
  2747. $value = getProp($item, $field);
  2748. if (!empty($value)) {
  2749. $resetItem[$field] = $value;
  2750. }
  2751. }
  2752. return $resetItem;
  2753. }
  2754. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  2755. {
  2756. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  2757. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  2758. if ($existingKey !== $generatedKey) {
  2759. return true;
  2760. }
  2761. return trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'));
  2762. }
  2763. private function normalizeEpisodeResourceKey($value): string
  2764. {
  2765. $value = trim((string)$value);
  2766. if ($value === '') {
  2767. return '';
  2768. }
  2769. return strtolower((string)preg_replace('/\s+/u', '', $value));
  2770. }
  2771. // 生成全局角色图片
  2772. private function batchSetGlobalRoleImg($data, $is_force=false) {
  2773. $anime_id = getProp($data, 'anime_id');
  2774. if (!$anime_id) Utils::throwError('1002:请选择对话');
  2775. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2776. $roles = json_decode(getProp($anime, 'roles'), true);
  2777. $art_style = getProp($anime, 'art_style');
  2778. $update_flag = false;
  2779. foreach ($roles as &$role) {
  2780. $role_name = getProp($role, 'role');
  2781. if ($role_name == '旁白') continue;
  2782. $description = getProp($role, 'description');
  2783. if ($art_style) $description = "美术风格:\n$art_style\n主体描述:$description";
  2784. // 参考图地址
  2785. $ref_img_url = getProp($role, 'url');
  2786. if (!$is_force && $ref_img_url) continue;
  2787. $update_flag = true;
  2788. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  2789. try {
  2790. $params = [
  2791. 'prompt' => $description,
  2792. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  2793. ];
  2794. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2795. $task_id = $task->id;
  2796. if (!$task_id) {
  2797. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  2798. }
  2799. $role['task_id'] = $task_id;
  2800. $role['task_status'] = 'processing';
  2801. } catch (\Exception $e) {
  2802. Utils::throwError("20003:" . $e->getMessage());
  2803. }
  2804. }
  2805. if (!$update_flag) return true;
  2806. // 保存角色信息
  2807. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  2808. 'roles' => json_encode($roles, 256),
  2809. 'generate_status' => '执行中',
  2810. 'generate_at' => date('Y-m-d H:i:s'),
  2811. 'updated_at' => date('Y-m-d H:i:s')
  2812. ]);
  2813. if (!$boolen) {
  2814. Utils::throwError('20003:保存角色信息失败');
  2815. }
  2816. return $boolen;
  2817. }
  2818. // 生成全局场景图片
  2819. private function batchSetGlobalSceneImg($data, $is_force=false) {
  2820. $anime_id = getProp($data, 'anime_id');
  2821. if (!$anime_id) Utils::throwError('1002:请选择对话');
  2822. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2823. $scenes = json_decode(getProp($anime, 'scenes'), true);
  2824. $art_style = getProp($anime, 'art_style');
  2825. $update_flag = false;
  2826. foreach ($scenes as &$scene) {
  2827. $scene_name = getProp($scene, 'scene');
  2828. $description = getProp($scene, 'description');
  2829. if ($art_style) $description = "美术风格:\n$art_style\n\n场景描述:$description";
  2830. // 参考图地址
  2831. $ref_img_url = getProp($scene, 'url');
  2832. if (!$is_force && $ref_img_url) continue;
  2833. $update_flag = true;
  2834. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  2835. try {
  2836. $params = [
  2837. 'prompt' => $description,
  2838. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  2839. ];
  2840. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2841. $task_id = $task->id;
  2842. if (!$task_id) {
  2843. Utils::throwError("20003: 角色({$scene_name})生成图片失败");
  2844. }
  2845. $scene['task_id'] = $task_id;
  2846. $scene['task_status'] = 'processing';
  2847. } catch (\Exception $e) {
  2848. Utils::throwError("20003:" . $e->getMessage());
  2849. }
  2850. }
  2851. if (!$update_flag) return true;
  2852. // 保存角色信息
  2853. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  2854. 'scenes' => json_encode($scenes, 256),
  2855. 'generate_status' => '执行中',
  2856. 'generate_at' => date('Y-m-d H:i:s'),
  2857. 'updated_at' => date('Y-m-d H:i:s')
  2858. ]);
  2859. if (!$boolen) {
  2860. Utils::throwError('20003:保存角色信息失败');
  2861. }
  2862. return $boolen;
  2863. }
  2864. public function chatChangeImg($data) {
  2865. $segment = getProp($data, 'segment');
  2866. $segment_content = getProp($segment, 'segment_content');
  2867. $prompt = getProp($data, 'prompt');
  2868. $ref_img = getProp($data, 'ref_img');
  2869. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  2870. $model = getProp($data, 'model', 'v3');
  2871. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2872. $messages[] =
  2873. [
  2874. 'role' => 'user',
  2875. 'content' => $question
  2876. ];
  2877. $post_data = [
  2878. 'model' => $model,
  2879. 'messages' => $messages,
  2880. 'max_tokens' => 8192,
  2881. 'temperature' => 0.7,
  2882. 'frequency_penalty' => 0,
  2883. 'presence_penalty' => 0,
  2884. 'response_format' => ['type' => 'text'],
  2885. 'stream' => false // 是否启用流式输出
  2886. ];
  2887. // 调用流式输出的deepseek
  2888. $chatResult = $this->chatOnly($post_data);
  2889. if (is_array($chatResult)) {
  2890. extract($chatResult);
  2891. }else {
  2892. Utils::throwError('20003: 接口调用失败!');
  2893. }
  2894. return [
  2895. 'type' => 'done',
  2896. // 'episode' => $episode,
  2897. 'answer' => $fullContent,
  2898. 'reasoning' => $fullReasoningContent,
  2899. 'usage' => $usage
  2900. ];
  2901. }
  2902. // 仅调用deepseek对话接口
  2903. private function chatOnly($post_data) {
  2904. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2905. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2906. $response = $result->getBody()->getContents();
  2907. $response_arr = json_decode($response, true);
  2908. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  2909. $fullContent = '';
  2910. $fullReasoningContent = [];
  2911. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  2912. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2913. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2914. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  2915. }
  2916. return [
  2917. 'fullContent' => $fullContent,
  2918. 'fullReasoningContent' => $fullReasoningContent,
  2919. 'usage' => $usage
  2920. ];
  2921. }
  2922. private function splitContent($content) {
  2923. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  2924. $chapters = [];
  2925. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  2926. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  2927. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  2928. foreach ($matches as $match) {
  2929. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  2930. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  2931. if (!empty($title) && !empty($chapterContent)) {
  2932. $chapters[] = [
  2933. 'title' => $title,
  2934. 'content' => $chapterContent
  2935. ];
  2936. }
  2937. }
  2938. }
  2939. return $chapters;
  2940. }
  2941. public function getContentByBid($bid) {
  2942. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  2943. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  2944. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  2945. $content = '';
  2946. foreach ($chapters as $chapter) {
  2947. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  2948. }
  2949. return $content;
  2950. }
  2951. /**
  2952. * 根据文件类型提取文本内容
  2953. *
  2954. * @param mixed $file 文件对象或文件路径
  2955. * @return string
  2956. */
  2957. public function extractFileContent($file) {
  2958. // 获取文件路径和扩展名
  2959. if (is_string($file)) {
  2960. $filePath = $file;
  2961. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  2962. } else {
  2963. // Laravel UploadedFile 对象
  2964. $filePath = $file->getRealPath();
  2965. $extension = strtolower($file->getClientOriginalExtension());
  2966. }
  2967. $content = '';
  2968. switch ($extension) {
  2969. case 'txt':
  2970. $content = $this->extractTxtContent($filePath);
  2971. break;
  2972. case 'pdf':
  2973. $content = $this->extractPdfContent($filePath);
  2974. break;
  2975. case 'doc':
  2976. case 'docx':
  2977. $content = $this->extractWordContent($filePath);
  2978. break;
  2979. // case 'jpg':
  2980. // case 'jpeg':
  2981. // case 'png':
  2982. // case 'gif':
  2983. // case 'bmp':
  2984. // case 'webp':
  2985. // $content = $this->extractImageContent($filePath);
  2986. // break;
  2987. default:
  2988. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  2989. }
  2990. return $content;
  2991. }
  2992. /**
  2993. * 提取 TXT 文件内容
  2994. */
  2995. private function extractTxtContent($filePath) {
  2996. if (!file_exists($filePath)) {
  2997. Utils::throwError('20003:文件不存在');
  2998. }
  2999. $content = file_get_contents($filePath);
  3000. // 尝试检测并转换编码
  3001. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  3002. if ($encoding && $encoding !== 'UTF-8') {
  3003. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  3004. }
  3005. return trim($content);
  3006. }
  3007. /**
  3008. * 提取 PDF 文件内容
  3009. */
  3010. private function extractPdfContent($filePath) {
  3011. if (!file_exists($filePath)) {
  3012. Utils::throwError('20003:文件不存在');
  3013. }
  3014. try {
  3015. $parser = new PdfParser();
  3016. $pdf = $parser->parseFile($filePath);
  3017. $content = $pdf->getText();
  3018. return trim($content);
  3019. } catch (\Exception $e) {
  3020. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  3021. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  3022. }
  3023. }
  3024. /**
  3025. * 提取 Word 文件内容(支持 doc 和 docx)
  3026. */
  3027. private function extractWordContent($filePath) {
  3028. if (!file_exists($filePath)) {
  3029. Utils::throwError('20003:文件不存在');
  3030. }
  3031. try {
  3032. $phpWord = WordIOFactory::load($filePath);
  3033. $content = '';
  3034. foreach ($phpWord->getSections() as $section) {
  3035. foreach ($section->getElements() as $element) {
  3036. $content .= $this->extractWordElementText($element);
  3037. }
  3038. }
  3039. return trim($content);
  3040. } catch (\Exception $e) {
  3041. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  3042. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  3043. }
  3044. }
  3045. /**
  3046. * 递归提取 Word 元素中的文本
  3047. */
  3048. private function extractWordElementText($element) {
  3049. $text = '';
  3050. if (method_exists($element, 'getText')) {
  3051. $text .= $element->getText() . "\n";
  3052. } elseif (method_exists($element, 'getElements')) {
  3053. foreach ($element->getElements() as $childElement) {
  3054. $text .= $this->extractWordElementText($childElement);
  3055. }
  3056. }
  3057. return $text;
  3058. }
  3059. /**
  3060. * 提取图片内容(使用火山引擎 OCR)
  3061. */
  3062. private function extractImageContent($filePath) {
  3063. if (!file_exists($filePath)) {
  3064. Utils::throwError('20003:文件不存在');
  3065. }
  3066. try {
  3067. // 读取图片并转换为 base64
  3068. $imageData = file_get_contents($filePath);
  3069. $base64Image = base64_encode($imageData);
  3070. // 调用火山引擎 OCR 服务
  3071. $content = $this->callVolcEngineOCR($base64Image);
  3072. return trim($content);
  3073. } catch (\Exception $e) {
  3074. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  3075. Utils::throwError('20003:图片识别失败');
  3076. }
  3077. }
  3078. /**
  3079. * 调用火山引擎 OCR 服务识别图片文字
  3080. *
  3081. * @param string $base64Image base64 编码的图片数据
  3082. * @return string 识别的文字内容
  3083. */
  3084. private function callVolcEngineOCR($base64Image) {
  3085. $method = 'POST';
  3086. $service = 'cv';
  3087. $host = 'visual.volcengineapi.com';
  3088. $region = env('VOLC_REGION', 'cn-north-1');
  3089. $access_key = env('VOLC_AK');
  3090. $secret_key = env('VOLC_SK');
  3091. $action = 'OCRNormal';
  3092. $version = '2020-08-26';
  3093. if (!$access_key || !$secret_key) {
  3094. Utils::throwError('20003:请配置火山引擎 AK/SK');
  3095. }
  3096. // 请求体
  3097. $body = json_encode([
  3098. 'image_base64' => $base64Image
  3099. ]);
  3100. // 生成签名
  3101. $headers = $this->getVolcEngineSignHeaders(
  3102. $method, $service, $host, $region,
  3103. "Action={$action}&Version={$version}",
  3104. $access_key, $secret_key, $body
  3105. );
  3106. $client = new Client(['timeout' => 60, 'verify' => false]);
  3107. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  3108. 'headers' => $headers,
  3109. 'body' => $body
  3110. ]);
  3111. $response_arr = json_decode($response->getBody()->getContents(), true);
  3112. // 提取识别的文字
  3113. $textLines = [];
  3114. if (isset($response_arr['data']['line_texts'])) {
  3115. $textLines = $response_arr['data']['line_texts'];
  3116. } elseif (isset($response_arr['data']['ocr_infos'])) {
  3117. foreach ($response_arr['data']['ocr_infos'] as $info) {
  3118. if (isset($info['text'])) {
  3119. $textLines[] = $info['text'];
  3120. }
  3121. }
  3122. }
  3123. if (empty($textLines)) {
  3124. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  3125. return '';
  3126. }
  3127. return implode("\n", $textLines);
  3128. }
  3129. /**
  3130. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  3131. */
  3132. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  3133. $contentType = 'application/json';
  3134. $accept = 'application/json';
  3135. // 获取当前UTC时间
  3136. $t = new DateTime('now', new DateTimeZone('UTC'));
  3137. $xDate = $t->format('Ymd\THis\Z');
  3138. $dateStamp = $t->format('Ymd');
  3139. // 计算 body 的 sha256 哈希
  3140. $payloadHash = hash('sha256', $body);
  3141. // 1. 拼接规范请求串
  3142. $canonicalUri = '/';
  3143. $canonicalQueryString = $queryString;
  3144. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  3145. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  3146. $canonicalRequest = implode("\n", [
  3147. $method,
  3148. $canonicalUri,
  3149. $canonicalQueryString,
  3150. $canonicalHeaders,
  3151. $signedHeaders,
  3152. $payloadHash
  3153. ]);
  3154. // 2. 拼接待签名字符串
  3155. $algorithm = 'HMAC-SHA256';
  3156. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  3157. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  3158. $stringToSign = implode("\n", [
  3159. $algorithm,
  3160. $xDate,
  3161. $credentialScope,
  3162. $hashedCanonicalRequest
  3163. ]);
  3164. // 3. 计算签名
  3165. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  3166. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  3167. // 4. 添加签名到请求头
  3168. $authorizationHeader = sprintf(
  3169. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3170. $algorithm,
  3171. $access_key,
  3172. $credentialScope,
  3173. $signedHeaders,
  3174. $signature
  3175. );
  3176. return [
  3177. 'Accept' => $accept,
  3178. 'Content-Type' => $contentType,
  3179. 'Host' => $host,
  3180. 'X-Date' => $xDate,
  3181. 'X-Content-Sha256'=> $payloadHash,
  3182. 'Authorization' => $authorizationHeader
  3183. ];
  3184. }
  3185. public function generateScriptWords($cid, $model = 'r1') {
  3186. ini_set('max_execution_time', 0);
  3187. if (!$cid) Utils::throwError('20003: 请选择章节!');
  3188. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  3189. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  3190. $messages = [
  3191. [
  3192. 'role' => 'system',
  3193. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  3194. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  3195. 2.非对话部分请全部用旁白角色代替
  3196. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  3197. ],
  3198. [
  3199. 'role' => 'user',
  3200. 'content' => $content
  3201. ]
  3202. ];
  3203. $post_data = [
  3204. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  3205. 'messages' => $messages,
  3206. 'max_tokens' => 8192,
  3207. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  3208. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  3209. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  3210. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  3211. 'response_format' => [
  3212. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  3213. ],
  3214. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  3215. ];
  3216. $client = new Client(['timeout' => 1200, 'verify' => false]);
  3217. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  3218. $response = $result->getBody()->getContents();
  3219. $response_arr = json_decode($response, true);
  3220. $update_data = [];
  3221. $content = '';
  3222. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  3223. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  3224. $update_data = [
  3225. 'role' => 'assistant',
  3226. 'content' => $response_arr['choices'][0]['message']['content'],
  3227. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  3228. ];
  3229. }
  3230. return $content;
  3231. }
  3232. /**
  3233. * 智能化解析集数信息
  3234. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  3235. *
  3236. * @param string $prompt 用户输入的提示词
  3237. * @return int|null 解析出的集数,如果没有找到则返回null
  3238. */
  3239. private function extractEpisodeNumber($prompt)
  3240. {
  3241. if (empty($prompt)) {
  3242. return null;
  3243. }
  3244. // 定义各种可能的表达模式
  3245. $patterns = [
  3246. // 基本模式:改成N集、调整成N集、修改成N集
  3247. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  3248. // 扩展模式:分成N集、拆分成N集、分割成N集
  3249. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  3250. // 数量模式:N集、共N集、总共N集
  3251. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  3252. // 制作模式:制作N集、生成N集、创建N集
  3253. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  3254. // 计划模式:计划N集、预计N集、打算N集
  3255. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  3256. // 需要模式:需要N集、要N集
  3257. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  3258. // 中文数字模式:改成三集、调整成五集等
  3259. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  3260. // 英文数字模式
  3261. '/(?: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',
  3262. ];
  3263. // 中文数字转阿拉伯数字的映射
  3264. $chineseNumbers = [
  3265. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  3266. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  3267. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  3268. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  3269. ];
  3270. // 逐个尝试匹配模式
  3271. foreach ($patterns as $pattern) {
  3272. if (preg_match($pattern, $prompt, $matches)) {
  3273. $number = trim($matches[1]);
  3274. // 如果是中文数字,转换为阿拉伯数字
  3275. if (isset($chineseNumbers[$number])) {
  3276. return $chineseNumbers[$number];
  3277. }
  3278. // 如果是阿拉伯数字,直接返回
  3279. if (is_numeric($number)) {
  3280. $episodeNum = intval($number);
  3281. // 合理性检查:集数应该在1-100之间
  3282. if ($episodeNum >= 1 && $episodeNum <= 100) {
  3283. return $episodeNum;
  3284. }
  3285. }
  3286. }
  3287. }
  3288. return null;
  3289. }
  3290. /**
  3291. * 调用火山引擎对话(Chat) API
  3292. *
  3293. * @param array $params 包含以下参数:
  3294. * - model: 模型ID(必填)
  3295. * - messages: 消息列表(必填)
  3296. * - stream: 是否流式输出(可选,默认false)
  3297. * - max_tokens: 最大输出token数(可选)
  3298. * - temperature: 采样温度(可选,默认1)
  3299. * - top_p: 核采样概率(可选,默认0.7)
  3300. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  3301. * - presence_penalty: 存在惩罚系数(可选,默认0)
  3302. * - stop: 停止词(可选)
  3303. * - tools: 工具列表(可选)
  3304. * @return array|Generator 非流式返回数组,流式返回生成器
  3305. */
  3306. public function volcEngineChatCompletion(array $params)
  3307. {
  3308. $apiKey = env('VOLC_AI_API_KEY');
  3309. if (empty($apiKey)) {
  3310. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  3311. }
  3312. // 构建请求参数
  3313. $requestData = [
  3314. 'model' => $params['model'] ?? 'deepseek-v3-2-251201',
  3315. 'messages' => $params['messages'] ?? [],
  3316. ];
  3317. if (!in_array($requestData['model'], $this->valid_text_models)) {
  3318. Utils::throwError('20003:该模型不支持!');
  3319. }
  3320. // 添加可选参数
  3321. if (isset($params['stream'])) {
  3322. $requestData['stream'] = $params['stream'];
  3323. }
  3324. if (isset($params['stream_options'])) {
  3325. $requestData['stream_options'] = $params['stream_options'];
  3326. }
  3327. if (isset($params['max_tokens'])) {
  3328. $requestData['max_tokens'] = $params['max_tokens'];
  3329. }
  3330. if (isset($params['max_completion_tokens'])) {
  3331. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  3332. }
  3333. if (isset($params['temperature'])) {
  3334. $requestData['temperature'] = $params['temperature'];
  3335. }
  3336. if (isset($params['top_p'])) {
  3337. $requestData['top_p'] = $params['top_p'];
  3338. }
  3339. if (isset($params['frequency_penalty'])) {
  3340. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  3341. }
  3342. if (isset($params['presence_penalty'])) {
  3343. $requestData['presence_penalty'] = $params['presence_penalty'];
  3344. }
  3345. if (isset($params['stop'])) {
  3346. $requestData['stop'] = $params['stop'];
  3347. }
  3348. if (isset($params['tools'])) {
  3349. $requestData['tools'] = $params['tools'];
  3350. }
  3351. if (isset($params['tool_choice'])) {
  3352. $requestData['tool_choice'] = $params['tool_choice'];
  3353. }
  3354. if (isset($params['response_format'])) {
  3355. $requestData['response_format'] = $params['response_format'];
  3356. }
  3357. if (isset($params['thinking'])) {
  3358. $requestData['thinking'] = $params['thinking'];
  3359. }
  3360. if (isset($params['reasoning_effort'])) {
  3361. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  3362. }
  3363. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  3364. $client = new Client(['verify' => false, 'timeout' => 1200]);
  3365. try {
  3366. // 判断是否为流式输出
  3367. $isStream = isset($params['stream']) && $params['stream'] === true;
  3368. if ($isStream) {
  3369. // 流式输出
  3370. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  3371. } else {
  3372. // 非流式输出
  3373. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  3374. 'headers' => [
  3375. 'Authorization' => 'Bearer ' . $apiKey,
  3376. 'Content-Type' => 'application/json',
  3377. ],
  3378. 'json' => $requestData
  3379. ]);
  3380. $responseData = json_decode($response->getBody(), true);
  3381. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  3382. return $responseData;
  3383. }
  3384. } catch (\Exception $e) {
  3385. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  3386. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  3387. }
  3388. }
  3389. /**
  3390. * 火山引擎对话API流式输出
  3391. *
  3392. * @param Client $client HTTP客户端
  3393. * @param string $apiKey API密钥
  3394. * @param array $requestData 请求数据
  3395. * @return Generator
  3396. */
  3397. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  3398. {
  3399. try {
  3400. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  3401. 'headers' => [
  3402. 'Authorization' => 'Bearer ' . $apiKey,
  3403. 'Content-Type' => 'application/json',
  3404. ],
  3405. 'json' => $requestData,
  3406. 'stream' => true
  3407. ]);
  3408. $body = $response->getBody();
  3409. $buffer = '';
  3410. $fullContent = '';
  3411. $fullReasoningContent = '';
  3412. $usage = [];
  3413. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  3414. // 逐行读取流式响应
  3415. while (!$body->eof()) {
  3416. $chunk = $body->read(1024);
  3417. $buffer .= $chunk;
  3418. // 按行分割
  3419. $lines = explode("\n", $buffer);
  3420. $buffer = array_pop($lines);
  3421. foreach ($lines as $line) {
  3422. $line = trim($line);
  3423. if (empty($line)) {
  3424. continue;
  3425. }
  3426. // 检查是否是SSE数据行
  3427. if (strpos($line, 'data: ') !== 0) {
  3428. continue;
  3429. }
  3430. $data = substr($line, 6);
  3431. if ($data === '[DONE]') {
  3432. dLog('deepseek')->info('收到结束标记');
  3433. break 2;
  3434. }
  3435. try {
  3436. $json = json_decode($data, true);
  3437. if (json_last_error() !== JSON_ERROR_NONE) {
  3438. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  3439. continue;
  3440. }
  3441. if (isset($json['choices'][0]['delta'])) {
  3442. $delta = $json['choices'][0]['delta'];
  3443. // 处理思维链内容
  3444. if (isset($delta['reasoning_content'])) {
  3445. $fullReasoningContent .= $delta['reasoning_content'];
  3446. yield [
  3447. 'type' => 'reasoning',
  3448. 'content' => $delta['reasoning_content'],
  3449. 'full_reasoning' => $fullReasoningContent
  3450. ];
  3451. }
  3452. // 处理回答内容
  3453. if (isset($delta['content'])) {
  3454. $fullContent .= $delta['content'];
  3455. yield [
  3456. 'type' => 'content',
  3457. 'content' => $delta['content'],
  3458. ];
  3459. }
  3460. }
  3461. // 获取使用统计信息
  3462. if (isset($json['usage'])) {
  3463. $usage = $json['usage'];
  3464. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3465. }
  3466. } catch (\Exception $e) {
  3467. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  3468. continue;
  3469. }
  3470. }
  3471. }
  3472. dLog('deepseek')->info('流式读取完成', [
  3473. 'content_length' => strlen($fullContent),
  3474. 'reasoning_length' => strlen($fullReasoningContent)
  3475. ]);
  3476. yield [
  3477. 'type' => 'done',
  3478. 'full_content' => $fullContent,
  3479. 'full_reasoning' => $fullReasoningContent,
  3480. 'usage' => $usage
  3481. ];
  3482. } catch (\Exception $e) {
  3483. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  3484. throw $e;
  3485. }
  3486. }
  3487. }