DeepSeekService.php 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007
  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,并且分镜序号需连续(跨分幕中的分镜序号需连续)。
  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' => 0,
  2256. 'created_at' => date('Y-m-d H:i:s'),
  2257. ];
  2258. $episode_id = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->value('id');
  2259. if ($episode_id) {
  2260. $episode['updated_at'] = date('Y-m-d H:i:s');
  2261. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  2262. }else {
  2263. $boolen2 = DB::table('mp_anime_episodes')->insert($episode);
  2264. }
  2265. if (!$boolen2) {
  2266. dLog('deepseek')->info('分集内容保存失败', $episode);
  2267. Utils::throwError('20003:分集内容保存失败');
  2268. }
  2269. // 保存对话记录
  2270. $recrods = [
  2271. [
  2272. 'uid' => $uid,
  2273. 'anime_id' => $anime_id,
  2274. 'role' => 'user',
  2275. 'content' => $prompt,
  2276. 'sequence' => $episode_number,
  2277. 'created_at' => date('Y-m-d H:i:s'),
  2278. 'updated_at' => date('Y-m-d H:i:s')
  2279. ],
  2280. [
  2281. 'uid' => $uid,
  2282. 'anime_id' => $anime_id,
  2283. 'role' => 'assistant',
  2284. 'content' => $fullContent,
  2285. 'sequence' => $episode_number,
  2286. 'created_at' => date('Y-m-d H:i:s'),
  2287. 'updated_at' => date('Y-m-d H:i:s')
  2288. ]
  2289. ];
  2290. // 保存对话记录
  2291. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  2292. if (!$boolen3) {
  2293. Utils::throwError('20003:对话记录保存失败');
  2294. }
  2295. }catch (\Exception $e) {
  2296. DB::rollBack();
  2297. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2298. yield [
  2299. 'type' => 'done',
  2300. 'answer' => $fullContent,
  2301. 'reasoning' => $fullReasoningContent,
  2302. 'usage' => $usage,
  2303. 'error' => $e->getMessage(),
  2304. ];
  2305. }
  2306. DB::commit();
  2307. $episode['roles'] = json_decode($episode['roles'], true);
  2308. $episode['scenes'] = json_decode($episode['scenes'], true);
  2309. $episode['acts'] = json_decode($episode['acts'], true);
  2310. yield [
  2311. 'type' => 'done',
  2312. 'episode' => $episode,
  2313. 'answer' => $fullContent,
  2314. 'reasoning' => $fullReasoningContent,
  2315. 'usage' => $usage
  2316. ];
  2317. }
  2318. private function splitContent($content) {
  2319. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  2320. $chapters = [];
  2321. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  2322. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  2323. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  2324. foreach ($matches as $match) {
  2325. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  2326. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  2327. if (!empty($title) && !empty($chapterContent)) {
  2328. $chapters[] = [
  2329. 'title' => $title,
  2330. 'content' => $chapterContent
  2331. ];
  2332. }
  2333. }
  2334. }
  2335. return $chapters;
  2336. }
  2337. public function getContentByBid($bid) {
  2338. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  2339. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  2340. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  2341. $content = '';
  2342. foreach ($chapters as $chapter) {
  2343. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  2344. }
  2345. return $content;
  2346. }
  2347. /**
  2348. * 根据文件类型提取文本内容
  2349. *
  2350. * @param mixed $file 文件对象或文件路径
  2351. * @return string
  2352. */
  2353. public function extractFileContent($file) {
  2354. // 获取文件路径和扩展名
  2355. if (is_string($file)) {
  2356. $filePath = $file;
  2357. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  2358. } else {
  2359. // Laravel UploadedFile 对象
  2360. $filePath = $file->getRealPath();
  2361. $extension = strtolower($file->getClientOriginalExtension());
  2362. }
  2363. $content = '';
  2364. switch ($extension) {
  2365. case 'txt':
  2366. $content = $this->extractTxtContent($filePath);
  2367. break;
  2368. case 'pdf':
  2369. $content = $this->extractPdfContent($filePath);
  2370. break;
  2371. case 'doc':
  2372. case 'docx':
  2373. $content = $this->extractWordContent($filePath);
  2374. break;
  2375. // case 'jpg':
  2376. // case 'jpeg':
  2377. // case 'png':
  2378. // case 'gif':
  2379. // case 'bmp':
  2380. // case 'webp':
  2381. // $content = $this->extractImageContent($filePath);
  2382. // break;
  2383. default:
  2384. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  2385. }
  2386. return $content;
  2387. }
  2388. /**
  2389. * 提取 TXT 文件内容
  2390. */
  2391. private function extractTxtContent($filePath) {
  2392. if (!file_exists($filePath)) {
  2393. Utils::throwError('20003:文件不存在');
  2394. }
  2395. $content = file_get_contents($filePath);
  2396. // 尝试检测并转换编码
  2397. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  2398. if ($encoding && $encoding !== 'UTF-8') {
  2399. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  2400. }
  2401. return trim($content);
  2402. }
  2403. /**
  2404. * 提取 PDF 文件内容
  2405. */
  2406. private function extractPdfContent($filePath) {
  2407. if (!file_exists($filePath)) {
  2408. Utils::throwError('20003:文件不存在');
  2409. }
  2410. try {
  2411. $parser = new PdfParser();
  2412. $pdf = $parser->parseFile($filePath);
  2413. $content = $pdf->getText();
  2414. return trim($content);
  2415. } catch (\Exception $e) {
  2416. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  2417. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  2418. }
  2419. }
  2420. /**
  2421. * 提取 Word 文件内容(支持 doc 和 docx)
  2422. */
  2423. private function extractWordContent($filePath) {
  2424. if (!file_exists($filePath)) {
  2425. Utils::throwError('20003:文件不存在');
  2426. }
  2427. try {
  2428. $phpWord = WordIOFactory::load($filePath);
  2429. $content = '';
  2430. foreach ($phpWord->getSections() as $section) {
  2431. foreach ($section->getElements() as $element) {
  2432. $content .= $this->extractWordElementText($element);
  2433. }
  2434. }
  2435. return trim($content);
  2436. } catch (\Exception $e) {
  2437. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  2438. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  2439. }
  2440. }
  2441. /**
  2442. * 递归提取 Word 元素中的文本
  2443. */
  2444. private function extractWordElementText($element) {
  2445. $text = '';
  2446. if (method_exists($element, 'getText')) {
  2447. $text .= $element->getText() . "\n";
  2448. } elseif (method_exists($element, 'getElements')) {
  2449. foreach ($element->getElements() as $childElement) {
  2450. $text .= $this->extractWordElementText($childElement);
  2451. }
  2452. }
  2453. return $text;
  2454. }
  2455. /**
  2456. * 提取图片内容(使用火山引擎 OCR)
  2457. */
  2458. private function extractImageContent($filePath) {
  2459. if (!file_exists($filePath)) {
  2460. Utils::throwError('20003:文件不存在');
  2461. }
  2462. try {
  2463. // 读取图片并转换为 base64
  2464. $imageData = file_get_contents($filePath);
  2465. $base64Image = base64_encode($imageData);
  2466. // 调用火山引擎 OCR 服务
  2467. $content = $this->callVolcEngineOCR($base64Image);
  2468. return trim($content);
  2469. } catch (\Exception $e) {
  2470. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  2471. Utils::throwError('20003:图片识别失败');
  2472. }
  2473. }
  2474. /**
  2475. * 调用火山引擎 OCR 服务识别图片文字
  2476. *
  2477. * @param string $base64Image base64 编码的图片数据
  2478. * @return string 识别的文字内容
  2479. */
  2480. private function callVolcEngineOCR($base64Image) {
  2481. $method = 'POST';
  2482. $service = 'cv';
  2483. $host = 'visual.volcengineapi.com';
  2484. $region = env('VOLC_REGION', 'cn-north-1');
  2485. $access_key = env('VOLC_AK');
  2486. $secret_key = env('VOLC_SK');
  2487. $action = 'OCRNormal';
  2488. $version = '2020-08-26';
  2489. if (!$access_key || !$secret_key) {
  2490. Utils::throwError('20003:请配置火山引擎 AK/SK');
  2491. }
  2492. // 请求体
  2493. $body = json_encode([
  2494. 'image_base64' => $base64Image
  2495. ]);
  2496. // 生成签名
  2497. $headers = $this->getVolcEngineSignHeaders(
  2498. $method, $service, $host, $region,
  2499. "Action={$action}&Version={$version}",
  2500. $access_key, $secret_key, $body
  2501. );
  2502. $client = new Client(['timeout' => 60, 'verify' => false]);
  2503. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  2504. 'headers' => $headers,
  2505. 'body' => $body
  2506. ]);
  2507. $response_arr = json_decode($response->getBody()->getContents(), true);
  2508. // 提取识别的文字
  2509. $textLines = [];
  2510. if (isset($response_arr['data']['line_texts'])) {
  2511. $textLines = $response_arr['data']['line_texts'];
  2512. } elseif (isset($response_arr['data']['ocr_infos'])) {
  2513. foreach ($response_arr['data']['ocr_infos'] as $info) {
  2514. if (isset($info['text'])) {
  2515. $textLines[] = $info['text'];
  2516. }
  2517. }
  2518. }
  2519. if (empty($textLines)) {
  2520. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  2521. return '';
  2522. }
  2523. return implode("\n", $textLines);
  2524. }
  2525. /**
  2526. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  2527. */
  2528. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  2529. $contentType = 'application/json';
  2530. $accept = 'application/json';
  2531. // 获取当前UTC时间
  2532. $t = new DateTime('now', new DateTimeZone('UTC'));
  2533. $xDate = $t->format('Ymd\THis\Z');
  2534. $dateStamp = $t->format('Ymd');
  2535. // 计算 body 的 sha256 哈希
  2536. $payloadHash = hash('sha256', $body);
  2537. // 1. 拼接规范请求串
  2538. $canonicalUri = '/';
  2539. $canonicalQueryString = $queryString;
  2540. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  2541. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  2542. $canonicalRequest = implode("\n", [
  2543. $method,
  2544. $canonicalUri,
  2545. $canonicalQueryString,
  2546. $canonicalHeaders,
  2547. $signedHeaders,
  2548. $payloadHash
  2549. ]);
  2550. // 2. 拼接待签名字符串
  2551. $algorithm = 'HMAC-SHA256';
  2552. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  2553. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  2554. $stringToSign = implode("\n", [
  2555. $algorithm,
  2556. $xDate,
  2557. $credentialScope,
  2558. $hashedCanonicalRequest
  2559. ]);
  2560. // 3. 计算签名
  2561. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  2562. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  2563. // 4. 添加签名到请求头
  2564. $authorizationHeader = sprintf(
  2565. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2566. $algorithm,
  2567. $access_key,
  2568. $credentialScope,
  2569. $signedHeaders,
  2570. $signature
  2571. );
  2572. return [
  2573. 'Accept' => $accept,
  2574. 'Content-Type' => $contentType,
  2575. 'Host' => $host,
  2576. 'X-Date' => $xDate,
  2577. 'X-Content-Sha256'=> $payloadHash,
  2578. 'Authorization' => $authorizationHeader
  2579. ];
  2580. }
  2581. public function generateScriptWords($cid, $model = 'r1') {
  2582. ini_set('max_execution_time', 0);
  2583. if (!$cid) Utils::throwError('20003: 请选择章节!');
  2584. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  2585. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2586. $messages = [
  2587. [
  2588. 'role' => 'system',
  2589. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  2590. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  2591. 2.非对话部分请全部用旁白角色代替
  2592. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  2593. ],
  2594. [
  2595. 'role' => 'user',
  2596. 'content' => $content
  2597. ]
  2598. ];
  2599. $post_data = [
  2600. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  2601. 'messages' => $messages,
  2602. 'max_tokens' => 8192,
  2603. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  2604. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  2605. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  2606. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  2607. 'response_format' => [
  2608. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  2609. ],
  2610. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  2611. ];
  2612. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2613. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2614. $response = $result->getBody()->getContents();
  2615. $response_arr = json_decode($response, true);
  2616. $update_data = [];
  2617. $content = '';
  2618. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2619. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2620. $update_data = [
  2621. 'role' => 'assistant',
  2622. 'content' => $response_arr['choices'][0]['message']['content'],
  2623. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  2624. ];
  2625. }
  2626. return $content;
  2627. }
  2628. }