DeepSeekService.php 305 KB

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