DeepSeekService.php 212 KB

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