DeepSeekService.php 182 KB

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