DeepSeekService.php 284 KB

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