DeepSeekService.php 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012
  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 Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Redis;
  12. use OSS\Core\OssException;
  13. use OSS\OssClient;
  14. use Smalot\PdfParser\Parser as PdfParser;
  15. use TCPDF;
  16. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  17. class DeepSeekService
  18. {
  19. private $url;
  20. private $api_key;
  21. private $sys_message;
  22. private $test_content;
  23. private $headers;
  24. public function __construct() {
  25. $this->url = 'https://api.deepseek.com/chat/completions';
  26. $this->api_key = env('DEEPSEEK_API_KEY');
  27. $this->headers = [
  28. 'Authorization' => 'Bearer '.$this->api_key,
  29. 'Content-Type' => 'application/json; charset=UTF-8'
  30. ];
  31. $this->sys_message = [
  32. 'role' => 'system',
  33. 'content' => '你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  34. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  35. 2.<分集剧本>要求包含“分集序号”、“分集标题”以及分镜信息,分镜信息需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。\n\n
  36. 示例如下:\n\n
  37. ###剧本名:西昆仑
  38. ###故事梗概
  39. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  40. ###剧本亮点
  41. 亮点1:绝境奇药,生死一线
  42. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  43. 亮点2:结拜兄妹,化解尴尬
  44. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  45. 亮点3:纤发夺命,情愫暗涌
  46. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  47. ###人物关系
  48. 阿雪与梁萧之间存在兄妹之情。
  49. ###核心矛盾
  50. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  51. ###主体列表
  52. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  53. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  54. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  55. 阴阳球:天地异宝,能化生精气,救人于危难。
  56. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  57. ###美术风格
  58. 基础画风风格词:厚涂古风
  59. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  60. ###场景列表
  61. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  62. ###分集剧本
  63. ##分集01
  64. 分集名: 第一集
  65. 分镜01-1
  66. 场景描述:地点、时间、场景
  67. 运镜:固定近距离
  68. 出场角色:男主、女主
  69. 台词内容:
  70. 女主: 女主对话
  71. 男主:男主对话
  72. 女主: 女主对话
  73. 男主: 男主对话
  74. 分镜01-2
  75. 场景描述:地点、时间、场景
  76. 运镜:从近到远
  77. 出场角色:男主、女主
  78. 台词内容:
  79. 女主: 女主对话
  80. 男主:男主对话
  81. 女主: 女主对话
  82. 男主: 男主对话
  83. 分镜01-3
  84. 场景描述:地点、时间、场景
  85. 运镜:快速拉近
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 分集名: 第二集
  94. 分镜02-1
  95. 场景描述:地点、时间、场景
  96. 运镜:从近到远
  97. 出场角色:男主、女主
  98. 台词内容:
  99. 女主: 女主对话
  100. 男主:男主对话
  101. 女主: 女主对话
  102. 男主: 男主对话
  103. 分镜02-2
  104. 场景描述:地点、时间、场景
  105. 运镜:从近到远
  106. 出场角色:男主、女主
  107. 台词内容:
  108. 女主: 女主对话
  109. 男主:男主对话
  110. 女主: 女主对话
  111. 男主: 男主对话'
  112. ];
  113. $this->test_content = <<<'EOD'
  114. ###剧本名:看不见的守护者
  115. ###故事梗概
  116. 少女许芸重生回到悲剧发生前一个月,她本是豪门假千金,上辈子被真千金徐清遥报复,被迫联姻后惨死。一个暗恋她至深的陌生男人程景,用与系统交易的代价换她重生,代价是她永远看不见他。许芸利用先知改变命运,躲避了表哥卞大伟的侵犯,并试图回归平凡生活。在危机四伏的重生路上,那个“看不见”的守护者程景一次次救她于危难。许芸从恐惧、好奇到依赖,并主动追寻这个神秘存在。两人在“一个看得见,一个看不见”的荒诞设定下,发展出一段跨越生死、充满拉扯与救赎的深情。最终,许芸的执着冲破了系统规则,两人得以相见相守,共度余生。
  117. ###剧本亮点
  118. 亮点1:重生设定与“隐形”守护者的双重奇幻
  119. 开篇即用快速剪辑展现许芸上辈子的惨死与陌生男人程景为她下葬、与系统交易的画面,建立强烈的戏剧冲突与悬念。重生后,许芸视角中程景的“不存在”与观众视角(或通过环境互动)能感知的“存在”形成奇妙反差,如被无形力量救下车、凭空出现的面条、地上的血脚印等,视觉呈现新颖,情感张力十足。
  120. 亮点2:“看见”与“看不见”的极致情感拉扯
  121. 许芸对着一团空气说话、试探、甚至调情的场景,充满了戏剧性的孤独与浪漫。她努力感知程景的存在,通过细微痕迹(如血迹、水渍、移动的物品)与他“交流”。这种单向可见的互动,将暗恋的卑微与守护的深情推到极致,观众能深切共情两人近在咫尺却无法触及的煎熬与甜蜜。
  122. 亮点3:悬疑推进与身份揭秘的层层递进
  123. 剧本并非单纯恋爱,穿插着许芸对抗原生家庭伤害、智斗恶毒表哥卞大伟的主线。程景的“隐形”能力成为她破局的关键外挂,但也带来了新的危险。随着许芸通过学校花名册、资助信等线索一步步接近程景的真实身份,悬疑感与情感共鸣同步加深,直到最终高潮的“相见”时刻,情感得到彻底释放。
  124. ###人物关系
  125. 许芸与程景:被守护者与隐形守护者,后成为恋人、夫妻。许芸从依赖、好奇到深爱并主动追寻程景;程景则因感恩与深爱,默默守护许芸两世。
  126. 许芸与徐家父母:亲生父母,关系疏离冷漠。母亲重男轻女,偏袒侄子卞大伟;父亲怯懦,后期在许芸影响下有所改变。
  127. 许芸与卞大伟:表哥,施暴者与主要反派,对许芸有侵犯意图,是前期主要威胁。
  128. 许芸与徐清遥:身份互换的真假千金,上辈子是仇敌,这辈子因许芸提前归位身份而关系未彻底恶化,但存在潜在矛盾。
  129. 许芸与夏颜:高中同桌兼闺蜜,后期因同时喜欢程景而产生嫉妒与隔阂,是推动程景“分手”谎言的工具人。
  130. ###核心矛盾
  131. 1. **生存矛盾**:重生后的许芸需躲避上辈子的悲剧命运(被卞大伟侵犯、被家庭出卖联姻),在恶劣原生环境中挣扎求生。
  132. 2. **感知矛盾**:系统规则导致许芸无法看见、听见程景,而程景深爱并守护着她。两人之间存在极致的“接触”渴望与“隔绝”现实的矛盾。
  133. 3. **情感矛盾**:许芸在依赖与追寻程景的过程中渐生情愫,但程景因自卑(身份差距)、身体创伤(以为不育)及系统限制,一度选择逃避和“分手”,造成两人的情感拉扯。
  134. 4. **身份矛盾**:真假千金的错位人生带来的家庭伦理与社会地位冲突,是许芸前世悲剧的根源,也是她今生需要面对和化解的阴影。
  135. ###主体列表
  136. 许芸-重生迷茫:刚重生时,心怀恐惧与决绝,试图改变命运。
  137. 许芸-坚韧求生:面对原生家庭压迫,冷静周旋,努力读书改变命运。
  138. 许芸-主动追寻:对“空气人”程景从好奇到依赖,再到大胆主动地试探与追求。
  139. 程景-隐形守护:始终在许芸身边,默默保护、照顾她,情感深沉而克制。
  140. 程景-隐忍挣扎:因系统限制和自身顾虑,承受着无法被感知的孤独与爱而不得的痛苦。
  141. 卞大伟-阴狠施暴:对许芸心怀不轨,是具象化的危险来源。
  142. 徐母-偏执刻薄:重男轻女,维护侄子,是家庭伤害的主要施加者。
  143. 徐父-怯懦转变:前期麻木,后期在女儿影响下逐渐觉醒。
  144. 夏颜-闺蜜变情敌:前期提供帮助,后期因嫉妒程景而说谎离间。
  145. “系统”:无形的规则设定,制造了主角间“看不见”的核心障碍。
  146. ###美术风格
  147. 基础画风风格词:写实细腻的现代都市情感风格,带有轻微悬疑色彩。
  148. 整体采用电影质感的写实风格,色彩随情绪和剧情变化。许芸重生前的回忆片段使用冷峻、压抑的蓝灰色调,对比强烈。重生后的现实生活,色调偏向自然光感,但徐家馄饨店等场景色调偏暗、拥挤,体现压抑感。当“隐形”的程景互动时,画面注重细节特写(如自动移动的物体、凹陷的床垫、凭空出现的水杯),并辅以微妙的光影变化或轻柔的焦点虚化来暗示他的“存在”。许芸与程景的独处时光,尤其是阁楼场景,色调转为温暖、柔和的橙黄色,营造私密与暧昧氛围。最终相见时刻,光线明亮饱满,色彩鲜活,象征隔阂的打破与希望降临。
  149. ###场景列表
  150. 徐家馄饨店:拥挤、老旧、充满烟火气的小店,是许芸重生后的主要生活场景,也是危机发生地。
  151. 学校教室/走廊:青春校园环境,是许芸努力学习、与夏颜交流的主要场景。
  152. 网吧包间:许芸躲避第一夜危机的地点,嘈杂、昏暗。
  153. 城市街道/路口:多次发生危机(车祸、被卞大伟堵截)和程景隐形救援的场景。
  154. 程景的阁楼:狭小但整洁,是两人的秘密基地和情感发酵的主要空间,充满生活气息与私密感。
  155. 医院:程景受伤后治疗的地点,也是许芸感到无助与寻找他的地方。
  156. 法院门口:卞大伟宣判后,徐母闹事、许芸再次感知到程景存在的场景。
  157. ###分集剧本
  158. ##分集01
  159. 分集名:重生与隐形救援
  160. 分镜01
  161. 场景描述:徐家馄饨店后院卧室,清晨,光线昏暗。许芸从噩梦中惊醒,额头上全是冷汗。
  162. 运镜:特写许芸惊恐睁大的双眼,快速闪回上辈子被家暴、惨死、以及一个模糊男人背影为她下葬的碎片画面。
  163. 出场角色:许芸
  164. 台词内容:
  165. 许芸(内心独白,带着颤音):我重生了…源于一个男人偏执的暗恋。
  166. 分镜02
  167. 场景描述:馄饨店前厅,清晨。徐母穿戴整齐,对正在收拾书包的许芸吩咐。卞大伟在锅炉后假装忙碌,眼神阴鸷地偷瞄许芸。
  168. 运镜:中景,先聚焦徐母严厉的脸,然后镜头平移,扫过乖巧点头的许芸,最后落在卞大伟身上,给他一个眼神特写。
  169. 出场角色:许芸,徐母,卞大伟
  170. 台词内容:
  171. 徐母:今天店就交给你表哥看着,晚上一放学就回来帮他干活。
  172. 许芸:(低头)嗯。
  173. 徐母:(转身离开)
  174. (许芸目光扫向卞大伟,内心独白):上辈子,就是他侮辱了徐清遥…也是我一切悲剧的开始。
  175. 分镜03
  176. 场景描述:网吧包间,夜。许芸坐在电脑前,屏幕光映着她苍白的脸。周围烟雾缭绕,嘈杂。
  177. 运镜:固定机位,侧面拍摄许芸蜷缩在椅子里的身影,环境音突出键盘声和隐约的游戏音效。
  178. 出场角色:许芸
  179. 台词内容:
  180. 许芸(内心独白):我在这里躲了一夜…可脑子里全是上辈子的事。徐清遥的恨,养父母的冷漠,那个老畜生的折磨…还有,那个给我收尸的陌生男人…
  181. 分镜04
  182. 场景描述:城市街道,清晨。许芸背着书包,困倦地过马路。一辆车急速驶来。
  183. 运镜:主观镜头,许芸视线模糊地看向冲来的车。紧接着第三视角,许芸的卫衣后领突然向后一紧,她整个人被“拽”离原地,车子擦身而过。
  184. 出场角色:许芸,路人老奶奶
  185. 台词内容:
  186. (急刹车声)
  187. 老奶奶:(拄着拐走近)这司机开车横冲直撞,要不是小姑娘你反应快…
  188. 许芸:(惊魂未定,四下张望)不是我自己躲的…
  189. (内心独白):是他!他就在我身边!
  190. 分镜05
  191. 场景描述:馄饨店后屋,白天。许芸刚进门,徐母拿着扫帚劈头盖脸打来。卞大伟在门口阴沉地看着。
  192. 运镜:手持晃动镜头,模拟挨打的混乱感。穿插卞大伟站在逆光门口的阴沉中景。
  193. 出场角色:许芸,徐母,卞大伟
  194. 台词内容:
  195. 徐母:死丫头!夜不归宿死哪儿去了?
  196. 许芸:(躲闪)去许家让清遥给我补课了!
  197. 徐母:(打累了,扔下扫帚)去包馄饨!
  198. (许芸沉默地洗手,开始包馄饨,余光警惕着卞大伟)
  199. ##分集02
  200. 分集名:危机再现与阁楼初夜
  201. 分镜01
  202. 场景描述:馄饨店后屋,傍晚。许芸放学推门进来,被埋伏的卞大伟一把抓住手腕。
  203. 运镜:快速推近,特写许芸惊愕的脸和卞大伟狞笑的手。镜头跟随挣扎的两人摇晃,撞倒桌椅。
  204. 出场角色:许芸,卞大伟
  205. 台词内容:
  206. 许芸:你干什么?放开我!
  207. 卞大伟:(喘着粗气)今天可没人救你了!
  208. (许芸挣扎中摸出兜里的小刀)
  209. 分镜02
  210. 场景描述:同上场景。卞大伟正要压倒许芸,突然怪叫着向后仰倒,仿佛被无形力量击中。
  211. 运镜:慢镜头,卞大伟身体不自然地扭曲、摔倒。许芸趁机爬起,震惊地看着“空气”。
  212. 出场角色:许芸,卞大伟
  213. 台词内容:
  214. 卞大伟:(对着空气怒吼)你他妈谁啊?!
  215. 许芸:(心口狂跳,看向卞大伟扭打的方向)是他…只能是他!
  216. 许芸:(朝“空气”大喊)我们走!
  217. 分镜03
  218. 场景描述:老旧居民楼楼梯,傍晚。许芸跟着一串突然出现在地上的“血脚印”奔跑。
  219. 运镜:俯拍镜头,跟随许芸上楼的脚步和地上断断续续的血脚印。
  220. 出场角色:许芸
  221. 台词内容:
  222. 许芸:(对着前方的空气)你受伤了!
  223. (血脚印停住)
  224. 许芸:(执拗地)我要跟你在一起。
  225. 分镜04
  226. 场景描述:狭小阁楼内,夜。许芸坐在床边,好奇地打量房间。小矮几上凭空出现两碗热气腾腾的面条。
  227. 运镜:全景展示阁楼布局,然后聚焦到矮几上“自动出现”的面碗。对面碗里的面条开始“自动”减少。
  228. 出场角色:许芸
  229. 台词内容:
  230. 许芸:(看着对面“自动”减少的面条,眼泪突然掉下来)啪嗒…好惨…这男的太惨了…
  231. 分镜05
  232. 场景描述:阁楼床上,夜。许芸穿着宽大T恤躺在床上。她突然睁开眼,感觉嘴唇上有温热柔软的触感。
  233. 运镜:特写许芸猛然睁大的眼睛,和微微湿润的嘴唇。背景是浴室隐约的水声。
  234. 出场角色:许芸
  235. 台词内容:
  236. 许芸:(内心惊愕)他在偷吻我?我…感觉到了?
  237. (她闭眼假装睡着,感觉脖颈又被亲了一下,忍不住轻颤)
  238. (浴室水声再次响起)
  239. 许芸:(嘴角微微勾起)好像…发现了系统的BUG?
  240. ##分集03
  241. 分集名:身份追寻与最终相见
  242. 分镜01
  243. 场景描述:学校教室,白天。许芸拿着重点班花名册,请同桌夏颜念名字。夏颜念到第一个名字时,许芸一脸茫然。
  244. 运镜:过肩镜头,从许芸视角看夏颜的嘴在动,但配以表示“无声”或“雪花噪音”的音效和画面扭曲效果。
  245. 出场角色:许芸,夏颜
  246. 台词内容:
  247. 夏颜:(念名单)…
  248. 许芸:(打断,急切地)夏夏,等高考后,你能帮我打听一下1号同学报哪所大学吗?我想跟他一起。
  249. 夏颜:(皱眉,嘴巴张合——许芸听不清)
  250. 许芸:(自顾自点头,眼冒星星)对,我喜欢1号同学!
  251. 分镜02
  252. 场景描述:法院外台阶,白天。卞大伟宣判后被带走,徐母发疯般冲过来要打许芸,被徐父拦住。许芸下台阶时,突然停下,嗅了嗅空气。
  253. 运镜:中景拍摄混乱场面,然后特写许芸突然愣住、微微抽动鼻翼的表情。
  254. 出场角色:许芸,徐母,徐父
  255. 台词内容:
  256. 徐母:(尖叫)许芸!你毁了我的一切!
  257. 许芸:(对徐父)爸,拉住她!(下台阶,脚步一顿)…皂角味?
  258. (内心独白):他来了?为什么…
  259. 分镜03
  260. 场景描述:程景家楼下小平台,傍晚。许芸站在平台边缘,下面是草坪。
  261. 运镜:全景,许芸孤身站在平台边,风吹动她的头发。然后切换为她主观视角,看向下方。
  262. 出场角色:许芸
  263. 台词内容:
  264. 许芸:(环顾四周,大声说)1号同学,没有你,我不想活了!
  265. (作势要跳)
  266. 分镜04
  267. 场景描述:同上场景。许芸身体前倾跌落的瞬间,被一股无形的力量拦腰抱住,然后轻轻“丢”在平台地面上。
  268. 运镜:高速摄影,捕捉许芸跌落瞬间被“空气”拦截并缓缓放下的超现实画面。
  269. 出场角色:许芸
  270. 台词内容:
  271. 许芸:(被抱住时惊喜)1号同学!我就知道…(被丢到地上,屁股疼)哎哟!
  272. 许芸:(爬起来,对着空气喊)你非要这么折磨我吗?还是你和夏颜在一起了?!
  273. 分镜05
  274. 场景描述:阁楼内,夜。许芸被浴室水声吵醒,迷迷糊糊走过去,赫然看见一个裸身男人(程景)在洗澡。
  275. 运镜:从许芸迷糊的主观镜头,到看清浴室景象时猛地拉近、定格在程景背影的震惊视角。
  276. 出场角色:许芸,程景
  277. 台词内容:
  278. 许芸:(惊吓后退)啊!你…你是谁?!
  279. (程景转身,两人对视)
  280. 程景:(震惊,试探)许芸?你能看见我?
  281. 许芸:(警惕)我当然能看见你!变-态!
  282. (程景扯掉浴巾,许芸惊呼转身又转回)
  283. 程景:(快速穿裤子)我就是你的1号同学。
  284. 分镜06
  285. 场景描述:阁楼内,片刻后。许芸接着夏颜的电话,程景站在一旁。接完电话,许芸走向程景。
  286. 运镜:双人镜头,许芸一边接电话,一边目光复杂地看着程景。挂电话后,她主动靠近,镜头柔和。
  287. 出场角色:许芸,程景
  288. 台词内容:
  289. 许芸:(对电话)…这挺好,可以毫无顾忌了。(挂电话,走向程景)
  290. 许芸:(圈住程景脖子)夏颜说,你受伤了,可能做不了爸爸?
  291. 程景:(眼神一暗)…嗯。
  292. 许芸:(微笑)没关系。我只想跟你好好地在一起。
  293. (两人相拥,窗外天色渐亮)
  294. EOD;
  295. }
  296. // 与推理模型对话
  297. public function chatWithReasoner($data) {
  298. $content = getProp($data, 'content');
  299. $model = getProp($data, 'model', 'r1');
  300. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  301. // 获取可选情感(根据音色可支持情感选)
  302. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  303. $emotion_list = [];
  304. foreach ($timbre_emotion as $emotion) {
  305. $tmp = explode(',', $emotion);
  306. $emotion_list = array_merge($emotion_list, $tmp);
  307. }
  308. $emotion_list = array_unique($emotion_list);
  309. $emotion_str = implode('、', $emotion_list);
  310. // // 获取可选情感
  311. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  312. // $emotion_str = implode('、', $emotion_list);
  313. // 是否启用情感
  314. $enable_emotion = getProp($data, 'enable_emotion', 0);
  315. if ($enable_emotion) {
  316. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  317. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  318. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  319. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  320. }else {
  321. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  322. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  323. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  324. }
  325. $messages = [
  326. [
  327. 'role' => 'system',
  328. 'content' => $sys_content
  329. ],
  330. [
  331. 'role' => 'user',
  332. 'content' => $content
  333. ]
  334. ];
  335. $post_data = [
  336. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  337. 'messages' => $messages,
  338. 'max_tokens' => 8192,
  339. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  340. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  341. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  342. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  343. 'response_format' => [
  344. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  345. ],
  346. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  347. ];
  348. $client = new Client(['timeout' => 1200, 'verify' => false]);
  349. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  350. $response = $result->getBody()->getContents();
  351. $response_arr = json_decode($response, true);
  352. $update_data = [];
  353. $content = '';
  354. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  355. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  356. $update_data = [
  357. 'role' => 'assistant',
  358. 'content' => $response_arr['choices'][0]['message']['content'],
  359. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  360. ];
  361. }
  362. // 处理获取到的剧本数据
  363. $script_content = handleScriptWords($content, $enable_emotion);
  364. $result = [
  365. 'origin_content' => $content,
  366. 'roles' => getProp($script_content, 'roles'),
  367. 'words' => getProp($script_content, 'words'),
  368. ];
  369. return $result;
  370. }
  371. public function resetParagraphAudio($data) {
  372. $bid = getProp($data, 'bid');
  373. $cid = getProp($data, 'cid');
  374. $version_id = getProp($data, 'version_id');
  375. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  376. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  377. 'generate_status' => '待制作',
  378. 'updated_at' => date('Y-m-d H:i:s')
  379. ]);
  380. }
  381. public function saveParagraphAudio($data) {
  382. $bid = getProp($data, 'bid');
  383. $cid = getProp($data, 'cid');
  384. $version_id = getProp($data, 'version_id');
  385. $sequence = getProp($data, 'sequence');
  386. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  387. // 获取所有情感
  388. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  389. $emotion_list = array_flip($emotion_list);
  390. // 获取音色支持情感
  391. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  392. $timbre_emotion = explode(',', $timbre_emotion);
  393. $emotion = getProp($data, 'emotion');
  394. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  395. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  396. $list = [
  397. 'bid' => $bid,
  398. 'cid' => $cid,
  399. 'version_id' => $version_id,
  400. 'sequence' => $sequence,
  401. 'role' => getProp($data, 'role'),
  402. 'gender' => getProp($data, 'gender'),
  403. 'text' => trim(getProp($data, 'text')),
  404. 'emotion' => $emotion,
  405. 'emotion_type' => $emotion_type,
  406. 'voice_type' => getProp($data, 'voice_type'),
  407. 'voice_name' => getProp($data, 'voice_name'),
  408. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  409. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  410. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  411. 'pitch' => getProp($data, 'pitch', 0),
  412. // 'paragraph_audio_url' => '',
  413. 'generate_status' => '制作中',
  414. 'error_msg' => '',
  415. 'updated_at' => date('Y-m-d H:i:s')
  416. ];
  417. $continue = false;
  418. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  419. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  420. $list['generate_status'] = '制作成功';
  421. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  422. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  423. $continue = true;
  424. }
  425. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  426. if ($id) {
  427. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  428. }else {
  429. $list['created_at'] = date('Y-m-d H:i:s');
  430. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  431. $boolen = $id ? true : false;
  432. }
  433. // 如果更新成功则加入查询队列
  434. if ($boolen) {
  435. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  436. Redis::sadd($redis_key, $id);
  437. }
  438. if ($boolen && !$continue) {
  439. $boolen = false;
  440. $client = new Client(['timeout' => 300, 'verify' => false]);
  441. // 根据ID通过API通知合成音频
  442. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  443. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  444. $response = $result->getBody()->getContents();
  445. $response_arr = json_decode($response, true);
  446. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  447. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  448. Log::info('通知火山生成段落音频失败: '.$error_msg);
  449. Utils::throwError('20003:通知火山生成段落音频失败');
  450. }
  451. $boolen = true;
  452. }
  453. return $boolen;
  454. }
  455. public function insertAudioEffect($data) {
  456. $audio_id = getProp($data, 'audio_id');
  457. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  458. $bid = getProp($chapter_audio, 'bid');
  459. $version_id = getProp($chapter_audio, 'version_id');
  460. $cid = getProp($chapter_audio, 'cid');
  461. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  462. $audio_effect_json = getProp($data, 'audio_effect_json');
  463. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  464. try {
  465. DB::beginTransaction();
  466. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  467. if (!$count) {
  468. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  469. }else {
  470. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  471. }
  472. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  473. 'audio_effect_status' => '添加中',
  474. 'audio_effect_json' => $audio_effect_json,
  475. 'updated_at' => date('Y-m-d H:i:s')
  476. ]);
  477. if (!$boolen1) {
  478. DB::rollBack();
  479. Utils::throwError('20003:更新生成数据失败');
  480. }
  481. $id = DB::table('mp_audio_tasks')->insertGetId([
  482. 'audio_id' => $audio_id,
  483. 'generate_status' => '执行中',
  484. 'generate_json' => json_encode([], 256),
  485. 'bid' => $bid,
  486. 'book_name' => getProp($chapter_audio, 'book_name'),
  487. 'version_id' => $version_id,
  488. 'version_name' => getProp($chapter_audio, 'version_name'),
  489. 'cid' => $cid,
  490. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  491. 'task_name' => $task_name,
  492. 'created_at' => date('Y-m-d H:i:s'),
  493. 'updated_at' => date('Y-m-d H:i:s')
  494. ]);
  495. if (!$id) {
  496. DB::rollBack();
  497. Utils::throwError('20003:创建任务失败');
  498. }
  499. }catch (\Exception $e) {
  500. DB::rollBack();
  501. Utils::throwError('20003:'.$e->getMessage());
  502. }
  503. DB::commit();
  504. $client = new Client(['timeout' => 300, 'verify' => false]);
  505. // 根据ID通过API通知合成音频
  506. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  507. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  508. $response = $result->getBody()->getContents();
  509. $response_arr = json_decode($response, true);
  510. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  511. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  512. Log::info('通知火山插入音效失败: '.$error_msg);
  513. Utils::throwError('20003:通知火山插入音效失败');
  514. }
  515. return true;
  516. }
  517. public function insertBgm($data) {
  518. $audio_id = getProp($data, 'audio_id');
  519. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  520. $bid = getProp($chapter_audio, 'bid');
  521. $version_id = getProp($chapter_audio, 'version_id');
  522. $cid = getProp($chapter_audio, 'cid');
  523. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  524. $bgm_json = getProp($data, 'bgm_json');
  525. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  526. if (!$bgm_json) {
  527. $bgm_json = getProp($data, 'audio_effect_json');
  528. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  529. }
  530. try {
  531. DB::beginTransaction();
  532. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  533. if (!$count) {
  534. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  535. }else {
  536. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  537. }
  538. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  539. 'bgm_status' => '添加中',
  540. 'bgm_json' => $bgm_json,
  541. 'updated_at' => date('Y-m-d H:i:s')
  542. ]);
  543. if (!$boolen1) {
  544. DB::rollBack();
  545. Utils::throwError('20003:更新生成数据失败');
  546. }
  547. $id = DB::table('mp_audio_tasks')->insertGetId([
  548. 'audio_id' => $audio_id,
  549. 'generate_status' => '执行中',
  550. 'generate_json' => json_encode([], 256),
  551. 'bid' => $bid,
  552. 'book_name' => getProp($chapter_audio, 'book_name'),
  553. 'version_id' => $version_id,
  554. 'version_name' => getProp($chapter_audio, 'version_name'),
  555. 'cid' => $cid,
  556. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  557. 'task_name' => $task_name,
  558. 'created_at' => date('Y-m-d H:i:s'),
  559. 'updated_at' => date('Y-m-d H:i:s')
  560. ]);
  561. if (!$id) {
  562. DB::rollBack();
  563. Utils::throwError('20003:创建任务失败');
  564. }
  565. }catch (\Exception $e) {
  566. DB::rollBack();
  567. Utils::throwError('20003:'.$e->getMessage());
  568. }
  569. DB::commit();
  570. $client = new Client(['timeout' => 300, 'verify' => false]);
  571. // 根据ID通过API通知合成音频
  572. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  573. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  574. $response = $result->getBody()->getContents();
  575. $response_arr = json_decode($response, true);
  576. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  577. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  578. Log::info('通知火山插入bgm失败: '.$error_msg);
  579. Utils::throwError('20003:通知火山插入bgm失败');
  580. }
  581. return true;
  582. }
  583. public function getParagraphAudios($data) {
  584. $bid = getProp($data, 'bid');
  585. $cid = getProp($data, 'cid');
  586. $version_id = getProp($data, 'version_id');
  587. $sequence = getProp($data, 'sequence');
  588. // 获取已生成的音频
  589. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  590. if ($sequence) $query->where('sequence', $sequence);
  591. $paragraph_audios = $query->orderBy('sequence')->get();
  592. $result = [];
  593. foreach($paragraph_audios as $item) {
  594. $result[] = [
  595. 'sequence' => getProp($item, 'sequence'),
  596. 'role' => getProp($item, 'role'),
  597. 'gender' => getProp($item, 'gender'),
  598. 'text' => trim(getProp($item, 'text')),
  599. 'emotion' => getProp($item, 'emotion'),
  600. 'emotion_type' => getProp($item, 'emotion_type'),
  601. 'voice_type' => getProp($item, 'voice_type'),
  602. 'voice_name' => getProp($item, 'voice_name'),
  603. 'speed_ratio' => getProp($item, 'speed_ratio'),
  604. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  605. 'emotion_scale' => getProp($item, 'emotion_scale'),
  606. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  607. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  608. ];
  609. }
  610. return $result;
  611. }
  612. // 新增合成任务
  613. public function addGenerateTask($data) {
  614. $bid = getProp($data, 'bid');
  615. $cid = getProp($data, 'cid');
  616. $version_id = getProp($data, 'version_id');
  617. $generate_json = getProp($data, 'generate_json');
  618. // 获取已生成的音频
  619. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  620. $paragraph_list = [];
  621. foreach($paragraph_audios as $item) {
  622. $paragraph_list[getProp($item, 'sequence')] = [
  623. 'role' => getProp($item, 'role'),
  624. 'gender' => getProp($item, 'gender'),
  625. 'text' => trim(getProp($item, 'text')),
  626. 'emotion' => getProp($item, 'emotion'),
  627. 'emotion_type' => getProp($item, 'emotion_type'),
  628. 'voice_type' => getProp($item, 'voice_type'),
  629. 'voice_name' => getProp($item, 'voice_name'),
  630. 'speed_ratio' => getProp($item, 'speed_ratio'),
  631. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  632. 'emotion_scale' => getProp($item, 'emotion_scale'),
  633. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  634. ];
  635. }
  636. // 更新角色-音色信息
  637. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  638. $existed_role_info = json_decode($existed_role_info, true);
  639. if (!$existed_role_info) $existed_role_info = [];
  640. // 获取情感信息
  641. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  642. $emotion_list = array_flip($emotion_list);
  643. // 获取音色对应情感组
  644. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  645. $timbre_emotion_list = [];
  646. foreach($timbre_emotions as $item) {
  647. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  648. }
  649. // 构造生成音频的json
  650. $words = json_decode($generate_json, true);
  651. // 最终合成前的参数组
  652. $mp_chapter_paragraph_audios = [];
  653. $sequence = 1;
  654. $complete_paragraph_sequences = [];
  655. foreach($words as &$word) {
  656. 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:参数格式有误');
  657. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  658. $role = getProp($word, 'role');
  659. $word['gender'] = (int)$word['gender'];
  660. // 判断音色对应情感是否支持,不支持则调整为中性
  661. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  662. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  663. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  664. if (isset($emotion_list[getProp($word, 'emotion')])) {
  665. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  666. }else {
  667. $word['emotion'] = '中性';
  668. $word['emotion_type'] = 'neutral';
  669. }
  670. $existed_role_info[$role] = [
  671. 'timbre_type' => $word['voice_type'],
  672. 'timbre_name' => $word['voice_name'],
  673. 'emotion' => $word['emotion'],
  674. 'emotion_type' => $word['emotion_type'],
  675. 'speed_ratio' => $word['speed_ratio'],
  676. 'loudness_ratio'=> $word['loudness_ratio'],
  677. 'emotion_scale' => $word['emotion_scale'],
  678. 'pitch' => $word['pitch']
  679. ];
  680. $word['paragraph_audio_url'] = '';
  681. // 判断生成参数是否相同,相同则直接使用已生成的音频
  682. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  683. // 如果音频存在并且参数都未改变则使用已生成的音频
  684. if (getProp($paragraph, 'paragraph_audio_url')) {
  685. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  686. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  687. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  688. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  689. // {
  690. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  691. // }
  692. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  693. }
  694. $tmp = $word;
  695. // 组装章节分句音频数据
  696. // $tmp['sequence'] = getProp($word, 'sequence');
  697. // $tmp['text'] = getProp($word, 'text');
  698. // $tmp['emotion'] = getProp($word, 'emotion');
  699. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  700. // $tmp['voice_name'] = getProp($word, 'voice_name');
  701. // $tmp['voice_type'] = getProp($word, 'voice_type');
  702. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  703. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  704. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  705. $tmp['bid'] = $bid;
  706. $tmp['version_id'] = $version_id;
  707. $tmp['cid'] = $cid;
  708. $tmp['sequence'] = $sequence;
  709. $tmp['created_at'] = date('Y-m-d H:i:s');
  710. $tmp['updated_at'] = date('Y-m-d H:i:s');
  711. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  712. $mp_chapter_paragraph_audios[] = $tmp;
  713. $complete_paragraph_sequences[] = $sequence;
  714. $sequence++;
  715. }
  716. $generate_json = json_encode($words, 256);
  717. // 判断是否有未生成字幕的段落
  718. $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();
  719. if ($no_subtitle_sequences) {
  720. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  721. }
  722. try {
  723. DB::beginTransaction();
  724. $role_info = json_encode($existed_role_info, 256);
  725. $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')]);
  726. if (!$boolen) {
  727. DB::rollBack();
  728. Utils::throwError('20003:更新角色信息失败');
  729. }
  730. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  731. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  732. if (!$count) {
  733. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  734. }else {
  735. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  736. }
  737. $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')]);
  738. if (!$boolen1) {
  739. DB::rollBack();
  740. Utils::throwError('20003:更新生成数据失败');
  741. }
  742. $id = DB::table('mp_audio_tasks')->insertGetId([
  743. 'audio_id' => getProp($chapter_audio, 'id'),
  744. 'generate_status' => '执行中',
  745. 'generate_json' => $generate_json,
  746. 'bid' => $bid,
  747. 'book_name' => getProp($chapter_audio, 'book_name'),
  748. 'version_id' => $version_id,
  749. 'version_name' => getProp($chapter_audio, 'version_name'),
  750. 'cid' => $cid,
  751. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  752. 'task_name' => $task_name,
  753. 'created_at' => date('Y-m-d H:i:s'),
  754. 'updated_at' => date('Y-m-d H:i:s')
  755. ]);
  756. if (!$id) {
  757. DB::rollBack();
  758. Utils::throwError('20003:创建任务失败');
  759. }
  760. // 删除不在段落序号范围内的其他数据
  761. if ($complete_paragraph_sequences) {
  762. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  763. }
  764. // // 删除章节分句音频数据并重新插入
  765. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  766. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  767. // if (!$boolen3) {
  768. // DB::rollBack();
  769. // Utils::throwError('20003:更新章节分句音频失败');
  770. // }
  771. } catch (\Exception $e) {
  772. DB::rollBack();
  773. Utils::throwError('20003:'.$e->getMessage());
  774. }
  775. DB::commit();
  776. // 通知火山生成音频
  777. $client = new Client(['timeout' => 300, 'verify' => false]);
  778. // 根据ID通过API通知合成音频
  779. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  780. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  781. $response = $result->getBody()->getContents();
  782. $response_arr = json_decode($response, true);
  783. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  784. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  785. Log::info('通知火山生成音频失败: '.$error_msg);
  786. Utils::throwError('20003:通知火山生成音频失败');
  787. }
  788. return true;
  789. }
  790. public function timbreList($data) {
  791. $gender = getProp($data, 'gender');
  792. $timbre_name = getProp($data, 'voice_name');
  793. $category_id = getProp($data, 'category_id');
  794. $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');
  795. if ($gender) {
  796. $query->where('gender', $gender);
  797. }
  798. if ($timbre_name) {
  799. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  800. }
  801. if ($category_id) {
  802. $query->where(function ($query) use ($category_id) {
  803. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  804. });
  805. }
  806. $list = $query->get()->map(function ($value) {
  807. $value = (array)$value;
  808. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  809. return $value;
  810. })->toArray();
  811. return $list;
  812. }
  813. // 生成火山临时token
  814. public function setStsToken() {
  815. // ************* 配置参数 *************
  816. $method = 'GET';
  817. $service = 'sts';
  818. $host = 'open.volcengineapi.com';
  819. $region = env('VOLC_REGION');
  820. $endpoint = 'https://open.volcengineapi.com';
  821. // $endpoint = 'https://tos-cn-beijing.volces.com';
  822. $access_key = env('VOLC_AK');
  823. $secret_key = env('VOLC_SK');
  824. // 获取缓存中的token,如果没有则请求接口
  825. $token = Redis::get('volc_sts_token');
  826. if (!$token) {
  827. // 查询参数
  828. $query_parameters = [
  829. 'Action' => 'AssumeRole',
  830. 'RoleSessionName' => 'user@zw',
  831. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  832. 'Version' => '2018-01-01'
  833. ];
  834. // 生成URL编码的查询字符串
  835. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  836. // 获取签名头信息
  837. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  838. // 构建完整URL
  839. $request_url = $endpoint . '?' . $request_parameters;
  840. $client = new Client(['verify' => false]);
  841. $response = $client->get($request_url, ['headers' => $headers]);
  842. $response_arr = json_decode($response->getBody()->getContents(), true);
  843. $result = [
  844. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  845. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  846. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  847. 'Region' => env('VOLC_REGION'),
  848. 'Endpoint' => env('VOLC_END_POINT'),
  849. 'Bucket' => env('VOLC_BUCKET'),
  850. ];
  851. // 缓存token
  852. Redis::setex('volc_sts_token', 3000, json_encode($result));
  853. return $result;
  854. } else {
  855. return json_decode($token, true);
  856. }
  857. // $response = $response['Response'];
  858. // $access_key = $response['Credentials']['AccessKeyId'];
  859. // $secret_key = $response['Credentials']['AccessKeySecret'];
  860. // $security_token = $response['Credentials']['SecurityToken'];
  861. // $expiration = $response['Credentials']['Expiration'];
  862. // dd($response_arr);
  863. }
  864. public function emotionGroups($data) {
  865. $id = getProp($data, 'group_id');
  866. $group_name = getProp($data, 'group_name');
  867. $voice_type = getProp($data, 'voice_type');
  868. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  869. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  870. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  871. if ($group_name) {
  872. $query->where('group_name', 'like', "%{$group_name}%");
  873. }
  874. if ($id) {
  875. $query->where('id', $id);
  876. }
  877. if ($voice_type) {
  878. $query->where('voice_type', $voice_type);
  879. }
  880. return $query->orderBy('id')->get()->map(function ($value) {
  881. return (array)$value;
  882. })->toArray();
  883. }
  884. private function sign($key, $msg) {
  885. return hash_hmac('sha256', $msg, $key, true);
  886. }
  887. // 生成签名密钥
  888. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  889. $kDate = $this->sign($key, $dateStamp);
  890. $kRegion = $this->sign($kDate, $regionName);
  891. $kService = $this->sign($kRegion, $serviceName);
  892. $kSigning = $this->sign($kService, 'request');
  893. return $kSigning;
  894. }
  895. // 获取签名头信息
  896. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  897. $contenttype = 'application/x-www-form-urlencoded';
  898. $accept = 'application/json';
  899. // 获取当前UTC时间
  900. $t = new DateTime('now', new DateTimeZone('UTC'));
  901. $xdate = $t->format('Ymd\THis\Z');
  902. $datestamp = $t->format('Ymd');
  903. // 1. 拼接规范请求串
  904. $canonical_uri = '/';
  905. $canonical_querystring = $request_parameters;
  906. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  907. $signed_headers = 'content-type;host;x-date';
  908. // 空请求体的SHA256哈希
  909. $payload_hash = hash('sha256', '');
  910. $canonical_request = implode("\n", [
  911. $method,
  912. $canonical_uri,
  913. $canonical_querystring,
  914. $canonical_headers,
  915. $signed_headers,
  916. $payload_hash
  917. ]);
  918. // 2. 拼接待签名字符串
  919. $algorithm = 'HMAC-SHA256';
  920. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  921. $hashed_canonical_request = hash('sha256', $canonical_request);
  922. $string_to_sign = implode("\n", [
  923. $algorithm,
  924. $xdate,
  925. $credential_scope,
  926. $hashed_canonical_request
  927. ]);
  928. // 3. 计算签名
  929. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  930. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  931. // 4. 添加签名到请求头
  932. $authorization_header = sprintf(
  933. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  934. $algorithm,
  935. $access_key,
  936. $credential_scope,
  937. $signed_headers,
  938. $signature
  939. );
  940. return [
  941. 'Accept' => $accept,
  942. 'Content-Type' => $contenttype,
  943. 'X-Date' => $xdate,
  944. 'Authorization' => $authorization_header
  945. ];
  946. }
  947. // 文字合成语音(火山引擎)
  948. public function tts($data) {
  949. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  950. $headers = [
  951. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  952. 'Content-Type' => 'application/json; charset=UTF-8'
  953. ];
  954. $post_data = [
  955. 'app' => [
  956. 'appid' => env('VOLC_APPID'),
  957. 'token' => env('VOLC_TOKEN'),
  958. 'cluster' => 'volcano_tts'
  959. ],
  960. 'user' => [
  961. 'uid' => 'mp_audio'
  962. ],
  963. // 'audio' => [
  964. // 'voice_type' =>
  965. // ],
  966. ];
  967. }
  968. public function scriptList($data) {
  969. $script_id = getProp($data, 'script_id');
  970. $script_name = getProp($data, 'script_name');
  971. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  972. if ($script_id) {
  973. $query->where('id', $script_id);
  974. }
  975. if ($script_name) {
  976. $query->where('script_name', 'like', "%{$script_name}%");
  977. }
  978. return $query->orderBy('created_at', 'desc')->paginate(12);
  979. }
  980. public function scriptInfo($data) {
  981. $script_id = getProp($data, 'script_id');
  982. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  983. ->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();
  984. if (!$script) Utils::throwError('20003:该剧本不存在!');
  985. $script = (array)$script;
  986. $script['roles'] = json_decode($script['roles']);
  987. $script['scenes'] = json_decode($script['scenes']);
  988. // 获取分集信息
  989. $episodes = DB::table('mp_script_episodes')->where('script_id', $script_id)->orderBy('episode_number')
  990. ->select('id', 'episode_number', 'title', 'content', 'segment_number', 'segment_content')
  991. ->orderBy('episode_number')->orderBy('segment_number')->get()->map(function ($value) {
  992. return (array)$value;
  993. })->toArray();
  994. $return_episodes = [];
  995. foreach($episodes as $episode) {
  996. $episode_number = getProp($episode, 'episode_number');
  997. if (isset($return_episodes[$episode_number])) {
  998. $return_episodes[$episode_number]['segments'][] = [
  999. 'segment_number' => getProp($episode, 'segment_number'),
  1000. 'segment_content' => getProp($episode, 'segment_content')
  1001. ];
  1002. }else {
  1003. $return_episodes[$episode_number] = [
  1004. 'episode_number' => $episode_number,
  1005. 'title' => getProp($episode, 'title'),
  1006. 'segments' => [
  1007. [
  1008. 'segment_number' => getProp($episode, 'segment_number'),
  1009. 'segment_content' => getProp($episode, 'segment_content')
  1010. ]
  1011. ]
  1012. ];
  1013. }
  1014. }
  1015. $script['episodes'] = array_values($return_episodes);
  1016. return $script;
  1017. }
  1018. public function createScript($data) {
  1019. $script_name = getProp($data, 'script_name');
  1020. $uid = Site::getUid(); // 获取当前用户ID
  1021. if (!$script_name) Utils::throwError('20001:剧本名称不能为空');
  1022. return DB::table('mp_scripts')->insertGetId([
  1023. 'script_name' => $script_name,
  1024. 'user_id' => $uid,
  1025. 'created_at' => date('Y-m-d H:i:s'),
  1026. 'updated_at' => date('Y-m-d H:i:s')
  1027. ]);
  1028. }
  1029. /**
  1030. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1031. *
  1032. * @param array $data 包含以下参数:
  1033. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1034. * - question: 用户问题(可选)
  1035. * - model: 使用的模型(r1 或 v3,默认 v3)
  1036. * @return \Generator 返回生成器,用于流式输出
  1037. */
  1038. public function chatWithFileStream($data) {
  1039. $script_id = getProp($data, 'script_id');
  1040. $file = getProp($data, 'file');
  1041. $content = getProp($data, 'content', '');
  1042. $bid = getProp($data, 'bid', 0);
  1043. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1044. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1045. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1046. $model = getProp($data, 'model', 'v3');
  1047. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1048. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1049. if (!$script) {
  1050. Utils::throwError('20003:剧本不存在');
  1051. }
  1052. if (!$file && !$content && !$bid) {
  1053. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1054. }
  1055. // 提取文件内容
  1056. if ($content) {
  1057. $content = filterContent($content);
  1058. } elseif ($file) {
  1059. $content = $this->extractFileContent($file);
  1060. if (!$content) {
  1061. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1062. }
  1063. } elseif ($bid) {
  1064. $content = $this->getContentByBid($bid);
  1065. if (!$content) {
  1066. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1067. }
  1068. } else {
  1069. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1070. }
  1071. // 构建消息
  1072. $messages = [
  1073. $this->sys_message,
  1074. [
  1075. 'role' => 'user',
  1076. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1077. ]
  1078. ];
  1079. $post_data = [
  1080. 'model' => $model,
  1081. 'messages' => $messages,
  1082. 'max_tokens' => 8192,
  1083. 'temperature' => 0.7,
  1084. 'frequency_penalty' => 0,
  1085. 'presence_penalty' => 0,
  1086. 'response_format' => ['type' => 'text'],
  1087. 'stream' => true // 启用流式输出
  1088. ];
  1089. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1090. $response = $client->post($this->url, [
  1091. 'json' => $post_data,
  1092. 'headers' => $this->headers,
  1093. 'stream' => true // 启用流式响应
  1094. ]);
  1095. $body = $response->getBody();
  1096. $fullContent = '';
  1097. $fullReasoningContent = '';
  1098. $usage = [];
  1099. $buffer = '';
  1100. Log::info('开始读取 DeepSeek 流式响应');
  1101. // 逐行读取流式响应
  1102. while (!$body->eof()) {
  1103. $chunk = $body->read(1024); // 每次读取 1KB
  1104. $buffer .= $chunk;
  1105. // 按行分割
  1106. $lines = explode("\n", $buffer);
  1107. // 保留最后一个不完整的行
  1108. $buffer = array_pop($lines);
  1109. foreach ($lines as $line) {
  1110. $line = trim($line);
  1111. // 跳过空行
  1112. if (empty($line)) {
  1113. continue;
  1114. }
  1115. // Log::info('收到原始行数据', ['line' => $line]);
  1116. // 检查是否是 SSE 数据行
  1117. if (strpos($line, 'data: ') !== 0) {
  1118. Log::warning('非 SSE 数据行', ['line' => $line]);
  1119. continue;
  1120. }
  1121. $data = substr($line, 6); // 移除 "data: " 前缀
  1122. if ($data === '[DONE]') {
  1123. Log::info('收到结束标记');
  1124. break 2; // 跳出两层循环
  1125. }
  1126. try {
  1127. $json = json_decode($data, true);
  1128. if (json_last_error() !== JSON_ERROR_NONE) {
  1129. Log::warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1130. continue;
  1131. }
  1132. // Log::info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1133. if (isset($json['choices'][0]['delta'])) {
  1134. $delta = $json['choices'][0]['delta'];
  1135. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1136. // 注释掉以下内容则不返回d思维链内容
  1137. if (isset($delta['reasoning_content'])) {
  1138. $fullReasoningContent .= $delta['reasoning_content'];
  1139. // Log::info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1140. yield [
  1141. 'type' => 'reasoning',
  1142. 'content' => $delta['reasoning_content'],
  1143. 'full_reasoning' => $fullReasoningContent
  1144. ];
  1145. }
  1146. // 处理最终回答内容
  1147. if (isset($delta['content'])) {
  1148. $fullContent .= $delta['content'];
  1149. // Log::info('输出回答内容', ['length' => strlen($delta['content'])]);
  1150. yield [
  1151. 'type' => 'content',
  1152. 'content' => $delta['content'],
  1153. 'full_content' => $fullContent
  1154. ];
  1155. }
  1156. }
  1157. // 获取使用统计信息
  1158. if (isset($json['usage'])) {
  1159. $usage = $json['usage'];
  1160. Log::info('收到使用统计', ['usage' => $usage]);
  1161. }
  1162. } catch (\Exception $e) {
  1163. Log::error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1164. continue;
  1165. }
  1166. }
  1167. }
  1168. Log::info('流式读取完成', [
  1169. 'content_length' => strlen($fullContent),
  1170. 'reasoning_length' => strlen($fullReasoningContent)
  1171. ]);
  1172. // 处理完整内容并返回最终结果
  1173. $script_arr = [];
  1174. if ($fullContent) {
  1175. $script_arr = handleScriptContent($fullContent);
  1176. }
  1177. yield [
  1178. 'type' => 'done',
  1179. 'script' => $script_arr,
  1180. 'answer' => $fullContent,
  1181. 'reasoning' => $fullReasoningContent,
  1182. 'usage' => $usage
  1183. ];
  1184. }
  1185. /**
  1186. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1187. *
  1188. * @param array $data 包含以下参数:
  1189. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1190. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1191. * - model: 使用的模型(r1 或 v3,默认 v3)
  1192. * @return array
  1193. */
  1194. public function chatWithFile($data) {
  1195. // dd(handleScriptContent(''));
  1196. $script_id = getProp($data, 'script_id');
  1197. $file = getProp($data, 'file');
  1198. $content = getProp($data, 'content', '');
  1199. $bid = getProp($data, 'bid', 0);
  1200. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1201. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1202. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1203. $model = getProp($data, 'model', 'v3');
  1204. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1205. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1206. if (!$script) {
  1207. Utils::throwError('20003:剧本不存在');
  1208. }
  1209. if (!$file && !$content && !$bid) {
  1210. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1211. }
  1212. // 提取文件内容
  1213. if ($content) {
  1214. $content = filterContent($content);
  1215. } elseif ($file) {
  1216. $content = $this->extractFileContent($file);
  1217. if (!$content) {
  1218. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1219. }
  1220. } elseif ($bid) {
  1221. $content = $this->getContentByBid($bid);
  1222. if (!$content) {
  1223. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1224. }
  1225. } else {
  1226. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1227. }
  1228. // 构建消息
  1229. $messages = [
  1230. $this->sys_message,
  1231. [
  1232. 'role' => 'user',
  1233. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1234. ]
  1235. ];
  1236. $post_data = [
  1237. 'model' => $model,
  1238. 'messages' => $messages,
  1239. 'max_tokens' => 8192,
  1240. 'temperature' => 0.7,
  1241. 'frequency_penalty' => 0,
  1242. 'presence_penalty' => 0,
  1243. 'response_format' => ['type' => 'text'],
  1244. 'stream' => false
  1245. ];
  1246. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1247. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  1248. $response = $result->getBody()->getContents();
  1249. $response_arr = json_decode($response, true);
  1250. $content = '';
  1251. $usage = [];
  1252. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  1253. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  1254. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  1255. }
  1256. // \Log::info('返回值内容: '.$content);
  1257. $script_arr = [];
  1258. // 处理结果
  1259. if ($content) {
  1260. $script_arr = handleScriptContent($content);
  1261. }
  1262. return [
  1263. 'script' => $script_arr,
  1264. 'answer' => $content,
  1265. 'usage' => $usage
  1266. ];
  1267. }
  1268. public function saveScript($data) {
  1269. $script_arr =getProp($data, 'script', []);
  1270. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1271. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1272. $script_id = getProp($data, 'script_id');
  1273. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1274. try {
  1275. DB::beginTransaction();
  1276. $update_data = [
  1277. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1278. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1279. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1280. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1281. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1282. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1283. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1284. 'status' => 3,
  1285. 'start_episode_sequence' => $start_episode_sequence,
  1286. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1287. 'episode_num' => count($script_arr['episodes']),
  1288. 'updated_at' => date('Y-m-d H:i:s')
  1289. ];
  1290. // 保存剧本内容
  1291. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1292. if (!$boolen) {
  1293. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1294. Utils::throwError('20003:剧本内容保存失败');
  1295. }
  1296. // 保存分集内容
  1297. // 删除历史分集内容
  1298. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1299. $episodes = [];
  1300. $sequence = 1;
  1301. foreach ($script_arr['episodes'] as $episode) {
  1302. $segment_number = 1;
  1303. foreach($episode['segments'] as $segment) {
  1304. $episodes[] = [
  1305. 'script_id' => $script_id,
  1306. 'episode_number' => $episode['episode_number'],
  1307. 'title' => $episode['title'],
  1308. // 'content' => $episode['content'],
  1309. 'content' => '',
  1310. 'segment_number' => $segment_number,
  1311. 'segment_content' => $segment['segment_content'],
  1312. 'sequence' => $sequence,
  1313. 'created_at' => date('Y-m-d H:i:s'),
  1314. 'updated_at' => date('Y-m-d H:i:s')
  1315. ];
  1316. $sequence++;
  1317. $segment_number++;
  1318. }
  1319. }
  1320. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1321. if (!$boolen2) {
  1322. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1323. Utils::throwError('20003:分集内容保存失败');
  1324. }
  1325. } catch (\Exception $e) {
  1326. DB::rollBack();
  1327. Utils::throwError('20003:'.$e->getMessage());
  1328. }
  1329. DB::commit();
  1330. return true;
  1331. }
  1332. public function exportScript($data) {
  1333. $script = $this->scriptInfo($data);
  1334. $export_type = getProp($data, 'export_type', 'txt');
  1335. // 生成文件名
  1336. $filename = $script['script_name'] . '_' . date('YmdHis');
  1337. // 根据导出类型生成不同格式的文件
  1338. switch ($export_type) {
  1339. case 'txt':
  1340. return $this->exportScriptAsTxt($script, $filename);
  1341. case 'pdf':
  1342. return $this->exportScriptAsPdf($script, $filename);
  1343. default:
  1344. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  1345. }
  1346. }
  1347. /**
  1348. * 导出剧本为TXT格式
  1349. */
  1350. private function exportScriptAsTxt($script, $filename) {
  1351. // 构建TXT内容
  1352. $content = $this->buildScriptContent($script);
  1353. // 设置响应头,直接下载
  1354. header('Content-Type: text/plain; charset=utf-8');
  1355. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  1356. header('Content-Length: ' . strlen($content));
  1357. // 输出内容并结束
  1358. echo $content;
  1359. exit();
  1360. }
  1361. /**
  1362. * 导出剧本为PDF格式
  1363. */
  1364. private function exportScriptAsPdf($script, $filename) {
  1365. // 使用HTML转PDF的方式来更好地支持中文
  1366. $htmlContent = $this->buildScriptHtmlForPdf($script);
  1367. // 创建PDF实例
  1368. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1369. // 设置文档信息
  1370. $pdf->SetCreator('剧本导出系统');
  1371. $pdf->SetAuthor('系统');
  1372. $pdf->SetTitle($script['script_name']);
  1373. $pdf->SetSubject('剧本导出');
  1374. // 设置边距
  1375. $pdf->SetMargins(15, 15, 15);
  1376. $pdf->SetAutoPageBreak(TRUE, 15);
  1377. // 添加页面
  1378. $pdf->AddPage();
  1379. // 注册并使用 simsun.ttf 字体
  1380. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  1381. // 使用HTML内容生成PDF
  1382. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  1383. // 直接输出PDF文件供下载
  1384. header('Content-Type: application/pdf');
  1385. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  1386. // 直接输出PDF内容
  1387. $pdf->Output($filename . '.pdf', 'D');
  1388. exit();
  1389. }
  1390. /**
  1391. * 构建用于PDF的HTML内容
  1392. */
  1393. private function buildScriptHtmlForPdf($script) {
  1394. $html = '<style>
  1395. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  1396. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  1397. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  1398. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  1399. .info { margin-bottom: 8px; }
  1400. .episode { margin-bottom: 20px; page-break-inside: avoid; }
  1401. .segment { margin-bottom: 10px; margin-left: 20px; }
  1402. </style>';
  1403. // 标题
  1404. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  1405. // 剧本简介
  1406. if (!empty($script['intro'])) {
  1407. $html .= '<h2>剧本简介</h2>';
  1408. $html .= '<p>' . nl2br(htmlspecialchars($script['intro'])) . '</p>';
  1409. }
  1410. // 亮点
  1411. if (!empty($script['highlights'])) {
  1412. $html .= '<h2>亮点</h2>';
  1413. $html .= '<p>' . nl2br(htmlspecialchars($script['highlights'])) . '</p>';
  1414. }
  1415. // 核心矛盾
  1416. if (!empty($script['core_contradiction'])) {
  1417. $html .= '<h2>核心矛盾</h2>';
  1418. $html .= '<p>' . nl2br(htmlspecialchars($script['core_contradiction'])) . '</p>';
  1419. }
  1420. // 艺术风格
  1421. if (!empty($script['art_style'])) {
  1422. $html .= '<h2>艺术风格</h2>';
  1423. $html .= '<p>' . nl2br(htmlspecialchars($script['art_style'])) . '</p>';
  1424. }
  1425. // 角色列表
  1426. if (!empty($script['roles']) && is_array($script['roles'])) {
  1427. $html .= '<h2>角色列表</h2>';
  1428. $html .= '<ul>';
  1429. foreach ($script['roles'] as $role) {
  1430. if (is_array($role) || is_object($role)) {
  1431. $html .= '<li>' . htmlspecialchars(getProp($role, 'role', '')) . ':' . htmlspecialchars(getProp($role, 'description', '')) . '</li>';
  1432. } else {
  1433. $html .= '<li>' . htmlspecialchars($role) . '</li>';
  1434. }
  1435. }
  1436. $html .= '</ul>';
  1437. }
  1438. // 角色关系
  1439. if (!empty($script['role_relationship'])) {
  1440. $html .= '<h2>角色关系</h2>';
  1441. $html .= '<p>' . nl2br(htmlspecialchars($script['role_relationship'])) . '</p>';
  1442. }
  1443. // 场景列表
  1444. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1445. $html .= '<h2>场景列表</h2>';
  1446. $html .= '<ul>';
  1447. foreach ($script['scenes'] as $scene) {
  1448. if (is_array($scene) || is_object($scene)) {
  1449. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene', '')) . ':' . htmlspecialchars(getProp($scene, 'description', '')) . '</li>';
  1450. } else {
  1451. $html .= '<li>' . htmlspecialchars($scene) . '</li>';
  1452. }
  1453. }
  1454. $html .= '</ul>';
  1455. }
  1456. // 分集内容
  1457. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1458. $html .= '<h2>分集内容</h2>';
  1459. foreach ($script['episodes'] as $episode) {
  1460. $html .= '<div class="episode">';
  1461. $html .= '<h3>第' . htmlspecialchars($episode['episode_number']) . '集';
  1462. if (!empty($episode['title'])) {
  1463. $html .= ':' . htmlspecialchars($episode['title']);
  1464. }
  1465. $html .= '</h3>';
  1466. // 处理分段内容
  1467. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1468. foreach ($episode['segments'] as $segment) {
  1469. if (!empty($segment['segment_content'])) {
  1470. $html .= '<div class="segment">';
  1471. if (!empty($segment['segment_number'])) {
  1472. $html .= '<strong>第' . htmlspecialchars($segment['segment_number']) . '段</strong><br>';
  1473. }
  1474. $html .= nl2br(htmlspecialchars($segment['segment_content']));
  1475. $html .= '</div>';
  1476. }
  1477. }
  1478. }
  1479. $html .= '</div>';
  1480. }
  1481. }
  1482. return $html;
  1483. }
  1484. /**
  1485. * 构建PDF内容
  1486. */
  1487. private function buildPdfContent($pdf, $script) {
  1488. // 标题
  1489. $pdf->SetFont('dejavusans', 'B', 18);
  1490. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  1491. $pdf->Ln(5);
  1492. // 基本信息
  1493. $pdf->SetFont('dejavusans', '', 12);
  1494. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  1495. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  1496. $pdf->Ln(5);
  1497. // 剧本简介
  1498. if (!empty($script['intro'])) {
  1499. $pdf->SetFont('dejavusans', 'B', 14);
  1500. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  1501. $pdf->SetFont('dejavusans', '', 12);
  1502. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  1503. $pdf->Ln(3);
  1504. }
  1505. // 亮点
  1506. if (!empty($script['highlights'])) {
  1507. $pdf->SetFont('dejavusans', 'B', 14);
  1508. $pdf->Cell(0, 10, '亮点', 0, 1);
  1509. $pdf->SetFont('dejavusans', '', 12);
  1510. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  1511. $pdf->Ln(3);
  1512. }
  1513. // 核心矛盾
  1514. if (!empty($script['core_contradiction'])) {
  1515. $pdf->SetFont('dejavusans', 'B', 14);
  1516. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  1517. $pdf->SetFont('dejavusans', '', 12);
  1518. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  1519. $pdf->Ln(3);
  1520. }
  1521. // 艺术风格
  1522. if (!empty($script['art_style'])) {
  1523. $pdf->SetFont('dejavusans', 'B', 14);
  1524. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  1525. $pdf->SetFont('dejavusans', '', 12);
  1526. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  1527. $pdf->Ln(3);
  1528. }
  1529. // 备注
  1530. if (!empty($script['remark'])) {
  1531. $pdf->SetFont('dejavusans', 'B', 14);
  1532. $pdf->Cell(0, 10, '备注', 0, 1);
  1533. $pdf->SetFont('dejavusans', '', 12);
  1534. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  1535. $pdf->Ln(3);
  1536. }
  1537. // 角色列表
  1538. if (!empty($script['roles']) && is_array($script['roles'])) {
  1539. $pdf->SetFont('dejavusans', 'B', 14);
  1540. $pdf->Cell(0, 10, '角色列表', 0, 1);
  1541. $pdf->SetFont('dejavusans', '', 12);
  1542. foreach ($script['roles'] as $index => $role) {
  1543. if (is_array($role) || is_object($role)) {
  1544. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  1545. } else {
  1546. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  1547. }
  1548. }
  1549. $pdf->Ln(3);
  1550. }
  1551. // 角色关系
  1552. if (!empty($script['role_relationship'])) {
  1553. $pdf->SetFont('dejavusans', 'B', 14);
  1554. $pdf->Cell(0, 10, '角色关系', 0, 1);
  1555. $pdf->SetFont('dejavusans', '', 12);
  1556. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  1557. $pdf->Ln(3);
  1558. }
  1559. // 场景列表
  1560. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1561. $pdf->SetFont('dejavusans', 'B', 14);
  1562. $pdf->Cell(0, 10, '场景列表', 0, 1);
  1563. $pdf->SetFont('dejavusans', '', 12);
  1564. foreach ($script['scenes'] as $index => $scene) {
  1565. if (is_array($scene) || is_object($scene)) {
  1566. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  1567. } else {
  1568. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  1569. }
  1570. }
  1571. $pdf->Ln(5);
  1572. }
  1573. // 分集内容
  1574. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1575. $pdf->SetFont('dejavusans', 'B', 16);
  1576. $pdf->Cell(0, 12, '分集内容', 0, 1);
  1577. $pdf->Ln(3);
  1578. foreach ($script['episodes'] as $episode) {
  1579. // 检查是否需要新页面
  1580. if ($pdf->GetY() > 250) {
  1581. $pdf->AddPage();
  1582. }
  1583. $pdf->SetFont('dejavusans', 'B', 14);
  1584. $episodeTitle = '第' . $episode['episode_number'] . '集';
  1585. if (!empty($episode['title'])) {
  1586. $episodeTitle .= ':' . $episode['title'];
  1587. }
  1588. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  1589. // 处理分段内容
  1590. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1591. $pdf->SetFont('dejavusans', '', 12);
  1592. foreach ($episode['segments'] as $segment) {
  1593. if (!empty($segment['segment_content'])) {
  1594. // 如果有分段编号,显示分段标题
  1595. if (!empty($segment['segment_number'])) {
  1596. $pdf->SetFont('dejavusans', 'B', 12);
  1597. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  1598. $pdf->SetFont('dejavusans', '', 12);
  1599. }
  1600. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  1601. $pdf->Ln(2);
  1602. }
  1603. }
  1604. }
  1605. $pdf->Ln(5);
  1606. }
  1607. }
  1608. }
  1609. /**
  1610. * 构建剧本文本内容
  1611. */
  1612. private function buildScriptContent($script) {
  1613. $content = '';
  1614. // 剧本基本信息
  1615. if (!empty($script['intro'])) {
  1616. $content .= "###故事梗概\n" . $script['intro'] . "\n\n";
  1617. }
  1618. if (!empty($script['highlights'])) {
  1619. $content .= "###剧本亮点\n" . $script['highlights'] . "\n\n";
  1620. }
  1621. if (!empty($script['role_relationship'])) {
  1622. $content .= "###人物关系\n" . $script['role_relationship'] . "\n\n";
  1623. }
  1624. if (!empty($script['core_contradiction'])) {
  1625. $content .= "###核心矛盾\n" . $script['core_contradiction'] . "\n\n";
  1626. }
  1627. if (!empty($script['roles']) && is_array($script['roles'])) {
  1628. $content .= "###主体列表\n";
  1629. foreach ($script['roles'] as $role) {
  1630. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  1631. }
  1632. $content .= "\n\n";
  1633. }
  1634. if (!empty($script['art_style'])) {
  1635. $content .= "###美术风格\n" . $script['art_style'] . "\n\n";
  1636. }
  1637. // 场景信息
  1638. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1639. $content .= "###场景列表\n";
  1640. foreach ($script['scenes'] as $scene) {
  1641. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  1642. }
  1643. $content .= "\n\n";
  1644. }
  1645. // 分集内容
  1646. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1647. $content .= "###分集剧本\n";
  1648. foreach ($script['episodes'] as $episode) {
  1649. $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  1650. if (!empty($episode['title'])) {
  1651. $content .= ":" . $episode['title'];
  1652. }
  1653. $content .= "\n";
  1654. // 处理分镜
  1655. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1656. foreach ($episode['segments'] as $segment) {
  1657. $content .= "分镜" . $episode['episode_number'] . '-' . $segment['segment_number'] . "\n";
  1658. $content .= $segment['segment_content'] . "\n\n";
  1659. }
  1660. }
  1661. }
  1662. }
  1663. return $content;
  1664. }
  1665. /**
  1666. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1667. *
  1668. * @param array $data 包含以下参数:
  1669. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1670. * - question: 用户问题(可选)
  1671. * - model: 使用的模型(r1 或 v3,默认 v3)
  1672. * @return \Generator 返回生成器,用于流式输出
  1673. */
  1674. public function addChat($data) {
  1675. $uid = Site::getUid();
  1676. $file = getProp($data, 'file');
  1677. $content = getProp($data, 'content', '');
  1678. $bid = getProp($data, 'bid', 0);
  1679. $question =getProp($data, 'question', "请根据实例格式完成剧本大纲");
  1680. $prompt = getProp($data, 'prompt', '帮我根据给出的内容生成短剧大纲');
  1681. $model = getProp($data, 'model', 'v3');
  1682. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1683. if (!$file && !$content && !$bid) {
  1684. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1685. }
  1686. // 提取文件内容
  1687. if ($content) {
  1688. $content = filterContent($content);
  1689. } elseif ($file) {
  1690. $content = $this->extractFileContent($file);
  1691. if (!$content) {
  1692. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1693. }
  1694. } elseif ($bid) {
  1695. $content = $this->getContentByBid($bid);
  1696. if (!$content) {
  1697. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1698. }
  1699. } else {
  1700. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1701. }
  1702. // 构建消息
  1703. $messages = [
  1704. [
  1705. 'role' => 'system',
  1706. 'content' => '你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  1707. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  1708. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  1709. 示例如下:\n\n
  1710. ###剧本名:西昆仑
  1711. ###故事梗概
  1712. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1713. ###剧本亮点
  1714. 亮点1:绝境奇药,生死一线
  1715. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1716. 亮点2:结拜兄妹,化解尴尬
  1717. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1718. 亮点3:纤发夺命,情愫暗涌
  1719. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1720. ###人物关系
  1721. 阿雪与梁萧之间存在兄妹之情。
  1722. ###核心矛盾
  1723. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1724. ###主体列表
  1725. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1726. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1727. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1728. 阴阳球:天地异宝,能化生精气,救人于危难。
  1729. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1730. ###美术风格
  1731. 基础画风风格词:厚涂古风
  1732. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1733. ###场景列表
  1734. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。'
  1735. ],
  1736. [
  1737. 'role' => 'user',
  1738. 'content' => "以下是文档内容:
  1739. {$content}
  1740. 用户问题:
  1741. {$question}"
  1742. ]
  1743. ];
  1744. $post_data = [
  1745. 'model' => $model,
  1746. 'messages' => $messages,
  1747. 'max_tokens' => 8192,
  1748. 'temperature' => 0.7,
  1749. 'frequency_penalty' => 0,
  1750. 'presence_penalty' => 0,
  1751. 'response_format' => ['type' => 'text'],
  1752. 'stream' => true // 启用流式输出
  1753. ];
  1754. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1755. $response = $client->post($this->url, [
  1756. 'json' => $post_data,
  1757. 'headers' => $this->headers,
  1758. 'stream' => true // 启用流式响应
  1759. ]);
  1760. $body = $response->getBody();
  1761. $fullContent = '';
  1762. $fullReasoningContent = '';
  1763. $usage = [];
  1764. $buffer = '';
  1765. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1766. // 逐行读取流式响应
  1767. while (!$body->eof()) {
  1768. $chunk = $body->read(1024); // 每次读取 1KB
  1769. $buffer .= $chunk;
  1770. // 按行分割
  1771. $lines = explode("\n", $buffer);
  1772. // 保留最后一个不完整的行
  1773. $buffer = array_pop($lines);
  1774. foreach ($lines as $line) {
  1775. $line = trim($line);
  1776. // 跳过空行
  1777. if (empty($line)) {
  1778. continue;
  1779. }
  1780. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  1781. // 检查是否是 SSE 数据行
  1782. if (strpos($line, 'data: ') !== 0) {
  1783. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1784. continue;
  1785. }
  1786. $data = substr($line, 6); // 移除 "data: " 前缀
  1787. if ($data === '[DONE]') {
  1788. dLog('deepseek')->info('收到结束标记');
  1789. break 2; // 跳出两层循环
  1790. }
  1791. try {
  1792. $json = json_decode($data, true);
  1793. if (json_last_error() !== JSON_ERROR_NONE) {
  1794. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1795. continue;
  1796. }
  1797. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1798. if (isset($json['choices'][0]['delta'])) {
  1799. $delta = $json['choices'][0]['delta'];
  1800. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1801. // 注释掉以下内容则不返回d思维链内容
  1802. if (isset($delta['reasoning_content'])) {
  1803. $fullReasoningContent .= $delta['reasoning_content'];
  1804. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1805. yield [
  1806. 'type' => 'reasoning',
  1807. 'content' => $delta['reasoning_content'],
  1808. 'full_reasoning' => $fullReasoningContent
  1809. ];
  1810. }
  1811. // 处理最终回答内容
  1812. if (isset($delta['content'])) {
  1813. $fullContent .= $delta['content'];
  1814. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  1815. yield [
  1816. 'type' => 'content',
  1817. 'content' => $delta['content'],
  1818. 'full_content' => $fullContent
  1819. ];
  1820. }
  1821. }
  1822. // 获取使用统计信息
  1823. if (isset($json['usage'])) {
  1824. $usage = $json['usage'];
  1825. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1826. }
  1827. } catch (\Exception $e) {
  1828. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1829. continue;
  1830. }
  1831. }
  1832. }
  1833. dLog('deepseek')->info('流式读取完成', [
  1834. 'content_length' => strlen($fullContent),
  1835. 'reasoning_length' => strlen($fullReasoningContent)
  1836. ]);
  1837. dLog('deepseek')->info('完整内容: '.$fullContent);
  1838. // $fullContent = $this->test_content;
  1839. // $fullReasoningContent = [];
  1840. // $usage = [];
  1841. // $uid = 0;
  1842. // $content = '';
  1843. // $question = '';
  1844. // $anime_id = 10;
  1845. // $fullContent = '###剧本名:看不见的守护者
  1846. // ###故事梗概
  1847. // 假千金许芸重生回到悲剧发生前一个月,为改变被养父母逼迫联姻、最终家暴致死的命运,她提前与真千金徐清遥身份归位,回到亲生父母家。然而,亲生母亲重男轻女,表哥卞大伟对她虎视眈眈。在危机时刻,一个因系统规则而无法被她看见、听见的“空气人”屡次救她于危难。许芸逐渐发现,“空气人”竟是高中时她曾资助过的学霸程景,他因感恩与暗恋,用自己的一切换她重生。两人在“看不见”的困境中相互试探、彼此救赎。许芸勇敢反击原生家庭的伤害,并执着地追寻程景的存在。最终,她的坚持冲破了系统限制,两人得以相见相守,共度余生。
  1848. // ###剧本亮点
  1849. // 亮点1:无形守护,生死相随
  1850. // 开场即用蒙太奇手法快速闪回许芸上辈子惨死、陌生男人(程景)为她收尸下葬的悲凉画面,与重生后她在车流中被“无形力量”猛然拉回的惊险瞬间形成强烈对比。通过许芸茫然四顾、观众却能看到空气中隐约波动的特效,营造出“守护者无处不在却不可见”的悬疑与浪漫感,奠定故事独特基调。
  1851. // 亮点2:阁楼共生,暧昧无声
  1852. // 狭小阁楼内,许芸与“看不见”的程景共处。画面聚焦于两碗面条自动减少、带血纸巾莫名出现、深夜有人喂水等细节,通过许芸的独角戏表演和空镜头的巧妙运用,将无形的陪伴与克制的欲望可视化。尤其是许芸主动“挑衅”、程景流鼻血的幽默桥段,在压抑中迸发甜涩的青春悸动,情感张力十足。
  1853. // 亮点3:真相撕裂,破障重逢
  1854. // 当许芸从徐清遥处得知程景是她曾资助的男孩时,记忆碎片如潮水般涌入脑海的视觉呈现。高潮在于许芸为逼程景现身而“跳楼”,程景下意识抱住她却被“看见”的瞬间。镜头从许芸视角切换为全知视角,程景英俊却惊慌的脸首次清晰展现,两人对视间,长达十年的暗恋、守护与挣扎在此刻爆发,极具情感冲击力。
  1855. // ###人物关系
  1856. // 许芸与程景:从被资助者与资助者,发展为被守护者与隐形守护者,最终成为恋人、夫妻。
  1857. // 许芸与徐母(生母):对抗关系,徐母重男轻女,偏袒侄子卞大伟,是许芸前期的主要压力源。
  1858. // 许芸与卞大伟:受害者与加害者,卞大伟是许芸人身安全的直接威胁。
  1859. // 许芸与徐清遥(真千金):身份互换的复杂关系,前期存在潜在对立,后期因共同遭遇(被卞大伟侵害威胁)而产生微妙共鸣。
  1860. // 程景与夏颜:同学关系,夏颜单恋程景,并因嫉妒成为许芸与程景关系中的短暂阻碍。
  1861. // ###核心矛盾
  1862. // 许芸渴望看见并拥抱用生命守护她的程景,却受系统规则所限,无法感知他的存在;程景深爱许芸,愿为她付出一切,却因自卑、身体受损(以为不育)及系统限制,一度选择逃避和“分手”。两人在“看不见的爱”与“触不到的恋人”困境中,进行一场关于勇气、坚持与相互救赎的博弈。
  1863. // ###主体列表
  1864. // 许芸-高中生(重生初期):17岁,面容清丽但带着重生后的疲惫与警觉。身形纤细,常穿着洗得发白的校服或简单卫衣,眼神时而脆弱时而坚定。
  1865. // 许芸-大学生/成年:20-30岁,气质逐渐成熟温婉,衣着简约大方,笑容增多,眼中有了被爱滋养的光彩。
  1866. // 程景-隐形状态(高中至大学):观众可见其模糊轮廓或行动痕迹(如血脚印、空气波动),实际为18-22岁,身高约185cm,肩宽腿长,习惯穿干净的白衬衫或棉质T恤,身上有淡淡的皂角清香。
  1867. // 程景-显形状态(大学后):面容英俊,眉眼深邃,鼻梁高挺,下颌线清晰。身材挺拔,有清晰的肌肉线条。初期显形时略带羞涩与不安,后期沉稳深情。
  1868. // 卞大伟:20岁出头,身材粗壮,皮肤油腻,小眼睛透着阴沉与邪气,常穿脏旧的背心或夹克。
  1869. // 徐母:40多岁,面容刻薄,身材微胖,烫着过时的卷发,穿着艳俗的碎花衬衫,眼神势利。
  1870. // 徐父:40多岁,身材佝偻,面容愁苦,穿着沾满污渍的工装,眼神怯懦。
  1871. // 夏颜:17-20岁,齐肩短发,长相清秀,穿着得体,前期是开朗学霸,后期面对程景时眼神充满倾慕与嫉妒。
  1872. // 徐清遥:17岁,与许芸有几分相似,但气质更冷冽倔强,穿着普通但整洁。
  1873. // ###美术风格
  1874. // 基础画风风格词:现实主义的细腻光影与超现实元素结合
  1875. // 整体采用现实主义基调,色彩饱和度较低,前期以灰蓝、暗绿色调为主,渲染重生后的压抑感与危机感。许芸在徐家的场景光线昏暗、拥挤;程景的阁楼则色调偏暖黄,营造狭小但安全的港湾感。“隐形”程景存在的场景,通过细微的空气扭曲、光影异常、物品无故移动等超现实特效来表现。后期两人相见后,画面色彩逐渐明亮、温暖,尤其婚后生活场景,充满柔和的日光与温馨的家居细节。人物造型追求真实感,服装、环境道具都需体现年代与阶层特征。
  1876. // ###场景列表
  1877. // 徐家馄饨店:老旧居民楼底层店铺,门面窄小,招牌褪色。店内狭窄拥挤,墙壁被油烟熏得发黄,摆放着简陋的桌椅和包馄饨的案板。光线主要来自门口和一台昏黄的吊灯,整体氛围压抑脏乱。
  1878. // 程景的阁楼:位于老式居民楼顶层,空间低矮狭小,斜屋顶开着一扇小窗。室内仅有一张单人床、一张旧书桌和一个矮几。书桌上堆满高中课本与试卷,床单整洁但洗得发白。阳光透过小窗形成光柱,灰尘在光中飞舞,环境简陋但充满生活气息与书卷气。
  1879. // 学校走廊与教室:典型的县级高中环境,走廊墙壁斑驳,贴满励志标语。教室拥挤,课桌堆满书本。重点班教室略显整洁,氛围紧张有序。
  1880. // 街边与巷口:许芸被卞大伟堵截的地点,位于老旧街区,墙壁布满涂鸦和小广告,路边有臭水沟,环境杂乱,危机四伏。
  1881. // 医院病房:多人间病房,设施陈旧,光线苍白冰冷。2号病床空无一物(观众可见程景,许芸看不见),与周围形成诡异对比,突出许芸的孤独与无助。
  1882. // 婚后家居:十年后,许芸与程景的家。宽敞明亮的客厅,装修简约温馨,有绿植和照片墙,阳光充足,与之前的压抑环境形成鲜明对比,象征苦尽甘来。 ';
  1883. // 处理完整内容并返回最终结果
  1884. $script_arr = [];
  1885. if ($fullContent) {
  1886. $script_arr = handleScriptContent($fullContent);
  1887. }
  1888. // 新建动漫
  1889. $anime_name = getProp($script_arr, 'script_name');
  1890. if (!$anime_name) {
  1891. yield [
  1892. 'type' => 'done',
  1893. 'answer' => $fullContent,
  1894. 'reasoning' => $fullReasoningContent,
  1895. 'usage' => $usage,
  1896. 'error' => '未能识别到剧本名称,请确认内容是否符合要求'
  1897. ];
  1898. }
  1899. // 确认对话名称唯一性
  1900. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  1901. $anime_name = $anime_name . '_' . date('YmdHis');
  1902. }
  1903. $table_data = [
  1904. 'user_id' => $uid,
  1905. 'anime_name' => $anime_name,
  1906. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1907. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1908. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1909. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1910. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1911. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1912. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1913. 'status' => '解析完成',
  1914. 'content' => $content,
  1915. // 'start_episode_sequence' => 1,
  1916. // 'end_episode_sequence' => count($script_arr['episodes']),
  1917. // 'episode_num' => count($script_arr['episodes']),
  1918. 'generate_status' => '待执行',
  1919. 'created_at' => date('Y-m-d H:i:s'),
  1920. 'updated_at' => date('Y-m-d H:i:s')
  1921. ];
  1922. try {
  1923. DB::beginTransaction();
  1924. // 新建动漫大纲
  1925. $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  1926. if (!$anime_id) {
  1927. dLog('deepseek')->info('对话保存失败', $table_data);
  1928. Utils::throwError('20003:对话保存失败');
  1929. }
  1930. // 保存对话记录
  1931. $recrods = [
  1932. [
  1933. 'uid' => $uid,
  1934. 'anime_id' => $anime_id,
  1935. 'sequence' => 0,
  1936. 'role' => 'user',
  1937. 'content' => "用户问题:\n
  1938. {$prompt}\n\n
  1939. 以下是文档内容:\n
  1940. {$content}",
  1941. 'created_at' => date('Y-m-d H:i:s'),
  1942. 'updated_at' => date('Y-m-d H:i:s')
  1943. ],
  1944. [
  1945. 'uid' => $uid,
  1946. 'anime_id' => $anime_id,
  1947. 'sequence' => 0,
  1948. 'role' => 'assistant',
  1949. 'content' => $fullContent,
  1950. 'created_at' => date('Y-m-d H:i:s'),
  1951. 'updated_at' => date('Y-m-d H:i:s')
  1952. ]
  1953. ];
  1954. // 保存对话记录
  1955. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  1956. if (!$boolen3) {
  1957. Utils::throwError('20003:对话记录保存失败');
  1958. }
  1959. }catch (\Exception $e) {
  1960. DB::rollBack();
  1961. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  1962. yield [
  1963. 'type' => 'done',
  1964. 'answer' => $fullContent,
  1965. 'reasoning' => $fullReasoningContent,
  1966. 'usage' => $usage,
  1967. 'error' => $e->getMessage(),
  1968. ];
  1969. }
  1970. DB::commit();
  1971. $table_data['anime_id'] = $anime_id;
  1972. $table_data['roles'] = json_decode($table_data['roles'], true);
  1973. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  1974. // $table_data['episodes'] = $script_arr['episodes'];
  1975. unset($table_data['created_at']);
  1976. unset($table_data['updated_at']);
  1977. unset($table_data['status']);
  1978. yield [
  1979. 'type' => 'done',
  1980. 'script' => $table_data,
  1981. 'answer' => $fullContent,
  1982. 'reasoning' => $fullReasoningContent,
  1983. 'usage' => $usage
  1984. ];
  1985. }
  1986. public function chat($data) {
  1987. $uid = Site::getUid();
  1988. $anime_id = getProp($data, 'anime_id');
  1989. $episode_number = getProp($data, 'episode_number', 1);
  1990. $anime = DB::table('mp_animes')->where('id', $anime_id)->select('content', 'roles', 'scenes')->first();
  1991. if (!$anime) Utils::throwError('20003:该对话不存在!');
  1992. $roles = json_decode(getProp($anime, 'roles'), true);
  1993. $scenes = json_decode(getProp($anime, 'scenes'), true);
  1994. // 转换主体列表和场景列表的格式
  1995. $roles_content = '';
  1996. foreach ($roles as $role) {
  1997. $roles_content .= getProp($role, 'role').': '.getProp($role, 'description')."\n";
  1998. }
  1999. $scenes_content = '';
  2000. foreach($scenes as $scene) {
  2001. $scenes_content .= getProp($scene, 'scene').': '.getProp($scene, 'description')."\n";
  2002. }
  2003. $prompt = getProp($data, 'prompt', '确认分镜大纲');
  2004. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  2005. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}
  2006. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$roles_content}\n\n
  2007. 3.<场景列表>必须在以下场景中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$scenes_content}\n\n
  2008. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”: \n\n
  2009. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2010. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音音色”、“台词内容”和“画面类型”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2011. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2012. 4.4“分镜信息”中的“台词内容”需与原文中的台词完全一致,不得修改或添加任何内容。
  2013. 示例格式:\n\n
  2014. 第1集:隐形的守护者
  2015. ###故事梗概
  2016. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  2017. ###美术风格
  2018. 基础画风风格词:韩漫二次元
  2019. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  2020. ###主体列表
  2021. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。
  2022. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。
  2023. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。
  2024. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。
  2025. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。
  2026. ###场景列表
  2027. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  2028. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  2029. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  2030. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  2031. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  2032. ###分镜剧本
  2033. ##第1幕:徐家老旧厨房 白天 室内
  2034. 分镜1
  2035. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2036. 构图设计:全景,低角度仰视
  2037. 运镜调度:手持拍摄
  2038. 配音角色:旁白
  2039. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2040. 画面类型:普通画面
  2041. 分镜2
  2042. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2043. 构图设计:近景,徐母面部特写
  2044. 运镜调度:固定镜头
  2045. 配音角色:徐母
  2046. 台词内容:问我夜不归宿死哪儿去了。
  2047. 画面类型:对口型
  2048. ##第2幕:徐家简陋客厅 黄昏 室内
  2049. 分镜3
  2050. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2051. 构图设计:全景,景深虚化
  2052. 运镜调度:固定镜头
  2053. 配音角色:旁白
  2054. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2055. 画面类型:普通画面
  2056. 分镜4
  2057. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2058. 构图设计:特写,火车票
  2059. 运镜调度:固定镜头
  2060. 配音角色:旁白
  2061. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2062. 画面类型:普通画面
  2063. \n\n";
  2064. // 获取章节内容
  2065. $full_content = getProp($anime, 'content');
  2066. // 根据章节内容拆分章节
  2067. $chapters = $this->splitContent($full_content);
  2068. if ($prompt == '确认分镜大纲') {
  2069. $content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2070. if (!$content) {
  2071. Utils::throwError('20003:章节内容无法获取,请确认');
  2072. }
  2073. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  2074. // 构建消息
  2075. $messages[] =
  2076. [
  2077. 'role' => 'user',
  2078. 'content' => $question
  2079. ];
  2080. }else if ($prompt == '继续策划下一集') {
  2081. $content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2082. if (!$content) {
  2083. Utils::throwError('20003:章节内容无法获取,请确认');
  2084. }
  2085. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  2086. // 获取上一集最后记录
  2087. $prev_sequence = $episode_number - 1;
  2088. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', $prev_sequence)
  2089. ->select('role', 'content')->orderBy('created_at', 'desc')->orderBy('id')->get()->map(function($value) {
  2090. return (array)$value;
  2091. })->toArray();
  2092. // 构建消息
  2093. $messages[] =
  2094. [
  2095. 'role' => 'user',
  2096. 'content' => $question
  2097. ];
  2098. }else {
  2099. $content = '';
  2100. $question = $prompt;
  2101. $messages[] =
  2102. [
  2103. 'role' => 'user',
  2104. 'content' => $question
  2105. ];
  2106. }
  2107. $model = getProp($data, 'model', 'v3');
  2108. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2109. $post_data = [
  2110. 'model' => $model,
  2111. 'messages' => $messages,
  2112. 'max_tokens' => 8192,
  2113. 'temperature' => 0.7,
  2114. 'frequency_penalty' => 0,
  2115. 'presence_penalty' => 0,
  2116. 'response_format' => ['type' => 'text'],
  2117. 'stream' => true // 启用流式输出
  2118. ];
  2119. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2120. $response = $client->post($this->url, [
  2121. 'json' => $post_data,
  2122. 'headers' => $this->headers,
  2123. 'stream' => true // 启用流式响应
  2124. ]);
  2125. $body = $response->getBody();
  2126. $fullContent = '';
  2127. $fullReasoningContent = '';
  2128. $usage = [];
  2129. $buffer = '';
  2130. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2131. // 逐行读取流式响应
  2132. while (!$body->eof()) {
  2133. $chunk = $body->read(1024); // 每次读取 1KB
  2134. $buffer .= $chunk;
  2135. // 按行分割
  2136. $lines = explode("\n", $buffer);
  2137. // 保留最后一个不完整的行
  2138. $buffer = array_pop($lines);
  2139. foreach ($lines as $line) {
  2140. $line = trim($line);
  2141. // 跳过空行
  2142. if (empty($line)) {
  2143. continue;
  2144. }
  2145. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  2146. // 检查是否是 SSE 数据行
  2147. if (strpos($line, 'data: ') !== 0) {
  2148. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2149. continue;
  2150. }
  2151. $data = substr($line, 6); // 移除 "data: " 前缀
  2152. if ($data === '[DONE]') {
  2153. dLog('deepseek')->info('收到结束标记');
  2154. break 2; // 跳出两层循环
  2155. }
  2156. try {
  2157. $json = json_decode($data, true);
  2158. if (json_last_error() !== JSON_ERROR_NONE) {
  2159. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2160. continue;
  2161. }
  2162. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  2163. if (isset($json['choices'][0]['delta'])) {
  2164. $delta = $json['choices'][0]['delta'];
  2165. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2166. // 注释掉以下内容则不返回d思维链内容
  2167. if (isset($delta['reasoning_content'])) {
  2168. $fullReasoningContent .= $delta['reasoning_content'];
  2169. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  2170. yield [
  2171. 'type' => 'reasoning',
  2172. 'content' => $delta['reasoning_content'],
  2173. 'full_reasoning' => $fullReasoningContent
  2174. ];
  2175. }
  2176. // 处理最终回答内容
  2177. if (isset($delta['content'])) {
  2178. $fullContent .= $delta['content'];
  2179. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  2180. yield [
  2181. 'type' => 'content',
  2182. 'content' => $delta['content'],
  2183. 'full_content' => $fullContent
  2184. ];
  2185. }
  2186. }
  2187. // 获取使用统计信息
  2188. if (isset($json['usage'])) {
  2189. $usage = $json['usage'];
  2190. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2191. }
  2192. } catch (\Exception $e) {
  2193. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2194. continue;
  2195. }
  2196. }
  2197. }
  2198. dLog('deepseek')->info('流式读取完成', [
  2199. 'content_length' => strlen($fullContent),
  2200. 'reasoning_length' => strlen($fullReasoningContent)
  2201. ]);
  2202. // // $fullContent = '111';
  2203. // // $fullReasoningContent = [];
  2204. // // $usage = [];
  2205. // // $uid = 0;
  2206. // // $content = '';
  2207. // // $question = '';
  2208. // // $episode_number = 1;
  2209. // // $anime_id = 13;
  2210. // $fullContent = DB::table('mp_anime_records')->orderBy('id', 'desc')->value('content');
  2211. dLog('deepseek')->info('完整内容: '.$fullContent);
  2212. // 处理完整内容并返回最终结果
  2213. $episode_arr = handleEpisodeContent($fullContent);
  2214. try {
  2215. DB::beginTransaction();
  2216. // 新建动漫剧集
  2217. // // 删除历史分集内容
  2218. // DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->delete();
  2219. // $episodes = [];
  2220. // $sequence = 1;
  2221. // foreach($episode_arr['acts'] as $act) {
  2222. // foreach($act['segments'] as $segment) {
  2223. // $episodes[] = [
  2224. // 'anime_id' => $anime_id,
  2225. // 'episode_number' => $episode_number,
  2226. // 'title' => $episode_arr['episode_title'],
  2227. // // 'content' => $episode['content'],
  2228. // 'content' => '',
  2229. // 'intro' => $episode_arr['intro'],
  2230. // 'art_style' => $episode_arr['art_style'],
  2231. // 'act_number' => $act['act_number'],
  2232. // 'act_title' => $act['act_title'],
  2233. // 'roles' => json_encode($episode_arr['roles'], 256),
  2234. // 'scenes' => json_encode($episode_arr['scenes'], 256),
  2235. // 'segment_number' => $segment['segment_number'],
  2236. // 'segment_content' => $segment['segment_content'],
  2237. // 'sequence' => $sequence,
  2238. // 'created_at' => date('Y-m-d H:i:s'),
  2239. // 'updated_at' => date('Y-m-d H:i:s')
  2240. // ];
  2241. // $sequence++;
  2242. // }
  2243. // }
  2244. $episode = [
  2245. 'anime_id' => $anime_id,
  2246. 'episode_number' => $episode_number,
  2247. 'title' => $episode_arr['episode_title'],
  2248. 'content' => $content,
  2249. // 'content' => '',
  2250. 'intro' => $episode_arr['intro'],
  2251. 'art_style' => $episode_arr['art_style'],
  2252. 'roles' => json_encode($episode_arr['roles'], 256),
  2253. 'scenes' => json_encode($episode_arr['scenes'], 256),
  2254. 'acts' => json_encode($episode_arr['acts'], 256),
  2255. 'sequence' => 1,
  2256. 'generate_status' => '待执行',
  2257. 'generate_at' => date('Y-m-d H:i:s'),
  2258. 'is_default' => 1,
  2259. 'created_at' => date('Y-m-d H:i:s'),
  2260. ];
  2261. $episode_id = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->value('id');
  2262. if ($episode_id) {
  2263. $episode['updated_at'] = date('Y-m-d H:i:s');
  2264. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  2265. }else {
  2266. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  2267. $boolen2 = $episode_id ? true : false;
  2268. }
  2269. if (!$boolen2) {
  2270. dLog('deepseek')->info('分集内容保存失败', $episode);
  2271. Utils::throwError('20003:分集内容保存失败');
  2272. }
  2273. // 保存对话记录
  2274. $recrods = [
  2275. [
  2276. 'uid' => $uid,
  2277. 'anime_id' => $anime_id,
  2278. 'role' => 'user',
  2279. 'content' => $prompt,
  2280. 'sequence' => $episode_number,
  2281. 'created_at' => date('Y-m-d H:i:s'),
  2282. 'updated_at' => date('Y-m-d H:i:s')
  2283. ],
  2284. [
  2285. 'uid' => $uid,
  2286. 'anime_id' => $anime_id,
  2287. 'role' => 'assistant',
  2288. 'content' => $fullContent,
  2289. 'sequence' => $episode_number,
  2290. 'created_at' => date('Y-m-d H:i:s'),
  2291. 'updated_at' => date('Y-m-d H:i:s')
  2292. ]
  2293. ];
  2294. // 保存对话记录
  2295. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  2296. if (!$boolen3) {
  2297. Utils::throwError('20003:对话记录保存失败');
  2298. }
  2299. }catch (\Exception $e) {
  2300. DB::rollBack();
  2301. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2302. yield [
  2303. 'type' => 'done',
  2304. 'answer' => $fullContent,
  2305. 'reasoning' => $fullReasoningContent,
  2306. 'usage' => $usage,
  2307. 'error' => $e->getMessage(),
  2308. ];
  2309. }
  2310. DB::commit();
  2311. $episode['episode_id'] = $episode_id;
  2312. $episode['roles'] = json_decode($episode['roles'], true);
  2313. $episode['scenes'] = json_decode($episode['scenes'], true);
  2314. $episode['acts'] = json_decode($episode['acts'], true);
  2315. yield [
  2316. 'type' => 'done',
  2317. 'episode' => $episode,
  2318. 'answer' => $fullContent,
  2319. 'reasoning' => $fullReasoningContent,
  2320. 'usage' => $usage
  2321. ];
  2322. }
  2323. private function splitContent($content) {
  2324. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  2325. $chapters = [];
  2326. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  2327. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  2328. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  2329. foreach ($matches as $match) {
  2330. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  2331. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  2332. if (!empty($title) && !empty($chapterContent)) {
  2333. $chapters[] = [
  2334. 'title' => $title,
  2335. 'content' => $chapterContent
  2336. ];
  2337. }
  2338. }
  2339. }
  2340. return $chapters;
  2341. }
  2342. public function getContentByBid($bid) {
  2343. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  2344. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  2345. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  2346. $content = '';
  2347. foreach ($chapters as $chapter) {
  2348. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  2349. }
  2350. return $content;
  2351. }
  2352. /**
  2353. * 根据文件类型提取文本内容
  2354. *
  2355. * @param mixed $file 文件对象或文件路径
  2356. * @return string
  2357. */
  2358. public function extractFileContent($file) {
  2359. // 获取文件路径和扩展名
  2360. if (is_string($file)) {
  2361. $filePath = $file;
  2362. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  2363. } else {
  2364. // Laravel UploadedFile 对象
  2365. $filePath = $file->getRealPath();
  2366. $extension = strtolower($file->getClientOriginalExtension());
  2367. }
  2368. $content = '';
  2369. switch ($extension) {
  2370. case 'txt':
  2371. $content = $this->extractTxtContent($filePath);
  2372. break;
  2373. case 'pdf':
  2374. $content = $this->extractPdfContent($filePath);
  2375. break;
  2376. case 'doc':
  2377. case 'docx':
  2378. $content = $this->extractWordContent($filePath);
  2379. break;
  2380. // case 'jpg':
  2381. // case 'jpeg':
  2382. // case 'png':
  2383. // case 'gif':
  2384. // case 'bmp':
  2385. // case 'webp':
  2386. // $content = $this->extractImageContent($filePath);
  2387. // break;
  2388. default:
  2389. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  2390. }
  2391. return $content;
  2392. }
  2393. /**
  2394. * 提取 TXT 文件内容
  2395. */
  2396. private function extractTxtContent($filePath) {
  2397. if (!file_exists($filePath)) {
  2398. Utils::throwError('20003:文件不存在');
  2399. }
  2400. $content = file_get_contents($filePath);
  2401. // 尝试检测并转换编码
  2402. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  2403. if ($encoding && $encoding !== 'UTF-8') {
  2404. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  2405. }
  2406. return trim($content);
  2407. }
  2408. /**
  2409. * 提取 PDF 文件内容
  2410. */
  2411. private function extractPdfContent($filePath) {
  2412. if (!file_exists($filePath)) {
  2413. Utils::throwError('20003:文件不存在');
  2414. }
  2415. try {
  2416. $parser = new PdfParser();
  2417. $pdf = $parser->parseFile($filePath);
  2418. $content = $pdf->getText();
  2419. return trim($content);
  2420. } catch (\Exception $e) {
  2421. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  2422. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  2423. }
  2424. }
  2425. /**
  2426. * 提取 Word 文件内容(支持 doc 和 docx)
  2427. */
  2428. private function extractWordContent($filePath) {
  2429. if (!file_exists($filePath)) {
  2430. Utils::throwError('20003:文件不存在');
  2431. }
  2432. try {
  2433. $phpWord = WordIOFactory::load($filePath);
  2434. $content = '';
  2435. foreach ($phpWord->getSections() as $section) {
  2436. foreach ($section->getElements() as $element) {
  2437. $content .= $this->extractWordElementText($element);
  2438. }
  2439. }
  2440. return trim($content);
  2441. } catch (\Exception $e) {
  2442. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  2443. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  2444. }
  2445. }
  2446. /**
  2447. * 递归提取 Word 元素中的文本
  2448. */
  2449. private function extractWordElementText($element) {
  2450. $text = '';
  2451. if (method_exists($element, 'getText')) {
  2452. $text .= $element->getText() . "\n";
  2453. } elseif (method_exists($element, 'getElements')) {
  2454. foreach ($element->getElements() as $childElement) {
  2455. $text .= $this->extractWordElementText($childElement);
  2456. }
  2457. }
  2458. return $text;
  2459. }
  2460. /**
  2461. * 提取图片内容(使用火山引擎 OCR)
  2462. */
  2463. private function extractImageContent($filePath) {
  2464. if (!file_exists($filePath)) {
  2465. Utils::throwError('20003:文件不存在');
  2466. }
  2467. try {
  2468. // 读取图片并转换为 base64
  2469. $imageData = file_get_contents($filePath);
  2470. $base64Image = base64_encode($imageData);
  2471. // 调用火山引擎 OCR 服务
  2472. $content = $this->callVolcEngineOCR($base64Image);
  2473. return trim($content);
  2474. } catch (\Exception $e) {
  2475. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  2476. Utils::throwError('20003:图片识别失败');
  2477. }
  2478. }
  2479. /**
  2480. * 调用火山引擎 OCR 服务识别图片文字
  2481. *
  2482. * @param string $base64Image base64 编码的图片数据
  2483. * @return string 识别的文字内容
  2484. */
  2485. private function callVolcEngineOCR($base64Image) {
  2486. $method = 'POST';
  2487. $service = 'cv';
  2488. $host = 'visual.volcengineapi.com';
  2489. $region = env('VOLC_REGION', 'cn-north-1');
  2490. $access_key = env('VOLC_AK');
  2491. $secret_key = env('VOLC_SK');
  2492. $action = 'OCRNormal';
  2493. $version = '2020-08-26';
  2494. if (!$access_key || !$secret_key) {
  2495. Utils::throwError('20003:请配置火山引擎 AK/SK');
  2496. }
  2497. // 请求体
  2498. $body = json_encode([
  2499. 'image_base64' => $base64Image
  2500. ]);
  2501. // 生成签名
  2502. $headers = $this->getVolcEngineSignHeaders(
  2503. $method, $service, $host, $region,
  2504. "Action={$action}&Version={$version}",
  2505. $access_key, $secret_key, $body
  2506. );
  2507. $client = new Client(['timeout' => 60, 'verify' => false]);
  2508. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  2509. 'headers' => $headers,
  2510. 'body' => $body
  2511. ]);
  2512. $response_arr = json_decode($response->getBody()->getContents(), true);
  2513. // 提取识别的文字
  2514. $textLines = [];
  2515. if (isset($response_arr['data']['line_texts'])) {
  2516. $textLines = $response_arr['data']['line_texts'];
  2517. } elseif (isset($response_arr['data']['ocr_infos'])) {
  2518. foreach ($response_arr['data']['ocr_infos'] as $info) {
  2519. if (isset($info['text'])) {
  2520. $textLines[] = $info['text'];
  2521. }
  2522. }
  2523. }
  2524. if (empty($textLines)) {
  2525. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  2526. return '';
  2527. }
  2528. return implode("\n", $textLines);
  2529. }
  2530. /**
  2531. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  2532. */
  2533. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  2534. $contentType = 'application/json';
  2535. $accept = 'application/json';
  2536. // 获取当前UTC时间
  2537. $t = new DateTime('now', new DateTimeZone('UTC'));
  2538. $xDate = $t->format('Ymd\THis\Z');
  2539. $dateStamp = $t->format('Ymd');
  2540. // 计算 body 的 sha256 哈希
  2541. $payloadHash = hash('sha256', $body);
  2542. // 1. 拼接规范请求串
  2543. $canonicalUri = '/';
  2544. $canonicalQueryString = $queryString;
  2545. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  2546. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  2547. $canonicalRequest = implode("\n", [
  2548. $method,
  2549. $canonicalUri,
  2550. $canonicalQueryString,
  2551. $canonicalHeaders,
  2552. $signedHeaders,
  2553. $payloadHash
  2554. ]);
  2555. // 2. 拼接待签名字符串
  2556. $algorithm = 'HMAC-SHA256';
  2557. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  2558. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  2559. $stringToSign = implode("\n", [
  2560. $algorithm,
  2561. $xDate,
  2562. $credentialScope,
  2563. $hashedCanonicalRequest
  2564. ]);
  2565. // 3. 计算签名
  2566. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  2567. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  2568. // 4. 添加签名到请求头
  2569. $authorizationHeader = sprintf(
  2570. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2571. $algorithm,
  2572. $access_key,
  2573. $credentialScope,
  2574. $signedHeaders,
  2575. $signature
  2576. );
  2577. return [
  2578. 'Accept' => $accept,
  2579. 'Content-Type' => $contentType,
  2580. 'Host' => $host,
  2581. 'X-Date' => $xDate,
  2582. 'X-Content-Sha256'=> $payloadHash,
  2583. 'Authorization' => $authorizationHeader
  2584. ];
  2585. }
  2586. public function generateScriptWords($cid, $model = 'r1') {
  2587. ini_set('max_execution_time', 0);
  2588. if (!$cid) Utils::throwError('20003: 请选择章节!');
  2589. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  2590. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2591. $messages = [
  2592. [
  2593. 'role' => 'system',
  2594. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  2595. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  2596. 2.非对话部分请全部用旁白角色代替
  2597. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  2598. ],
  2599. [
  2600. 'role' => 'user',
  2601. 'content' => $content
  2602. ]
  2603. ];
  2604. $post_data = [
  2605. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  2606. 'messages' => $messages,
  2607. 'max_tokens' => 8192,
  2608. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  2609. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  2610. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  2611. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  2612. 'response_format' => [
  2613. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  2614. ],
  2615. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  2616. ];
  2617. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2618. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2619. $response = $result->getBody()->getContents();
  2620. $response_arr = json_decode($response, true);
  2621. $update_data = [];
  2622. $content = '';
  2623. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2624. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2625. $update_data = [
  2626. 'role' => 'assistant',
  2627. 'content' => $response_arr['choices'][0]['message']['content'],
  2628. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  2629. ];
  2630. }
  2631. return $content;
  2632. }
  2633. }