DeepSeekService.php 230 KB

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