DeepSeekService.php 783 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. private $gemini_text_models;
  29. protected $aiImageGenerationService;
  30. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  33. $this->api_key = env('DEEPSEEK_API_KEY');
  34. $this->headers = [
  35. 'Authorization' => 'Bearer '.$this->api_key,
  36. 'Content-Type' => 'application/json; charset=UTF-8'
  37. ];
  38. // 火山引擎模型列表
  39. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  40. // GPT文本模型列表
  41. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  42. // Gemini文本模型列表
  43. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  44. $this->sys_message = [
  45. 'role' => 'system',
  46. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  47. 强制要求:\n
  48. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  49. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  50. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  51. 普通要求:\n
  52. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  53. 2.<分集剧本>的要求如下:
  54.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  55.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  56.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  57.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  58. \n\n
  59. 示例如下:\n
  60. ###剧本名:西昆仑
  61. ###故事梗概
  62. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  63. ###剧本亮点
  64. 亮点1:绝境奇药,生死一线
  65. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  66. 亮点2:结拜兄妹,化解尴尬
  67. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  68. 亮点3:纤发夺命,情愫暗涌
  69. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  70. ###人物关系
  71. 阿雪与梁萧之间存在兄妹之情。
  72. ###核心矛盾
  73. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  74. ###主体列表
  75. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  76. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  77. 阴阳球:天地异宝,能化生精气,救人于危难。
  78. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  79. ###美术风格
  80. 基础画风风格词:厚涂古风
  81. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  82. ###场景列表
  83. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  84. ###分集剧本
  85. ##分集01
  86. 第1集: 第一集的标题
  87. 场景描述:地点、时间、场景
  88. 运镜:固定近距离
  89. 出场角色:男主、女主
  90. 台词内容:
  91. 女主: 女主对话
  92. 男主:男主对话
  93. 女主: 女主对话
  94. 男主: 男主对话
  95. ##分集02
  96. 第2集: 第二集的标题
  97. 场景描述:地点、时间、场景
  98. 运镜:固定近距离
  99. 出场角色:男主、女主
  100. 台词内容:
  101. 女主: 女主对话
  102. 男主:男主对话
  103. 女主: 女主对话
  104. 男主: 男主对话"
  105. ];
  106. }
  107. /**
  108. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  109. *
  110. * @param array $data 请求参数
  111. * @return \Generator 返回生成器,用于流式输出
  112. */
  113. public function generateText($data) {
  114. // 获取请求参数
  115. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  116. $messages = getProp($data, 'messages', []);
  117. $systemPrompt = getProp($data, 'system_prompt', '');
  118. $prompt = getProp($data, 'prompt', '');
  119. $images = getProp($data, 'images', []); // 支持多张图片
  120. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  121. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  122. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  123. $isGeminiModel = in_array($model, $this->gemini_text_models);
  124. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  125. Utils::throwError('20003:仅Gemini模型支持视频输入');
  126. }
  127. // 如果没有提供messages,则根据system_prompt、content和images构建
  128. if (empty($messages)) {
  129. $messages = [];
  130. // 添加系统提示词
  131. if (!empty($systemPrompt)) {
  132. $messages[] = [
  133. 'role' => 'system',
  134. 'content' => $systemPrompt
  135. ];
  136. }
  137. // 构建用户消息内容(支持文本+图片)
  138. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  139. $userMessage = [
  140. 'role' => 'user',
  141. 'content' => []
  142. ];
  143. // 添加文本内容
  144. if (!empty($prompt)) {
  145. $userMessage['content'][] = [
  146. 'type' => 'text',
  147. 'text' => $prompt
  148. ];
  149. }
  150. // 处理上传的图片文件
  151. if (!empty($images)) {
  152. if (!is_array($images)) {
  153. $images = [$images];
  154. }
  155. foreach ($images as $image) {
  156. $imageBase64 = $this->processImageToBase64($image);
  157. if ($imageBase64) {
  158. $userMessage['content'][] = [
  159. 'type' => 'image_url',
  160. 'image_url' => [
  161. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  162. ]
  163. ];
  164. }
  165. }
  166. }
  167. // 处理图片URL
  168. if (!empty($imageUrls)) {
  169. if (!is_array($imageUrls)) {
  170. $imageUrls = [$imageUrls];
  171. }
  172. foreach ($imageUrls as $url) {
  173. if (!empty($url)) {
  174. $userMessage['content'][] = [
  175. 'type' => 'image_url',
  176. 'image_url' => [
  177. 'url' => $url
  178. ]
  179. ];
  180. }
  181. }
  182. }
  183. // 处理上传的视频文件(仅 Gemini)
  184. if (!empty($videos) && $isGeminiModel) {
  185. if (!is_array($videos)) {
  186. $videos = [$videos];
  187. }
  188. foreach ($videos as $video) {
  189. $inlineData = $this->processMediaToInlineData($video);
  190. if ($inlineData) {
  191. $userMessage['content'][] = [
  192. 'type' => 'video',
  193. 'inline_data' => $inlineData
  194. ];
  195. }
  196. }
  197. }
  198. // 处理视频URL(仅 Gemini)
  199. if (!empty($videoUrls) && $isGeminiModel) {
  200. if (!is_array($videoUrls)) {
  201. $videoUrls = [$videoUrls];
  202. }
  203. foreach ($videoUrls as $url) {
  204. if (!empty($url)) {
  205. $userMessage['content'][] = [
  206. 'type' => 'video_url',
  207. 'video_url' => ['url' => $url]
  208. ];
  209. }
  210. }
  211. }
  212. // 如果只有文本内容,简化为字符串格式
  213. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  214. $userMessage['content'] = $userMessage['content'][0]['text'];
  215. }
  216. $messages[] = $userMessage;
  217. }
  218. }
  219. // 验证messages不为空
  220. if (empty($messages)) {
  221. Utils::throwError('20003:请提供有效的对话内容');
  222. }
  223. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  224. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  225. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  226. if ($model === 'deepseek-chat') {
  227. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  228. $model = 'deepseek-v4-flash';
  229. $thinkingMode = 'disabled';
  230. } elseif ($model === 'deepseek-reasoner') {
  231. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  232. $model = 'deepseek-v4-flash';
  233. $thinkingMode = 'enabled';
  234. }
  235. // 构建请求参数
  236. $post_data = [
  237. 'model' => $model,
  238. 'messages' => $messages,
  239. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  240. 'temperature' => getProp($data, 'temperature', 1),
  241. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  242. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  243. 'thinking' => ['type' => $thinkingMode],
  244. 'stream' => true // 启用流式输出
  245. ];
  246. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  247. // 添加可选参数
  248. if (isset($data['top_p'])) {
  249. $post_data['top_p'] = $data['top_p'];
  250. }
  251. if (isset($data['response_format'])) {
  252. $post_data['response_format'] = $data['response_format'];
  253. }
  254. // 根据模型类型选择调用方法
  255. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  256. // DeepSeek 官方模型使用 DeepSeek API
  257. return $this->deepSeekStreamResponse($post_data);
  258. } else if (in_array($model, $this->gpt_text_models)) {
  259. // GPT 模型使用 TokenRouter API
  260. return $this->gpt54StreamResponse($post_data);
  261. } else if (in_array($model, $this->gemini_text_models)) {
  262. // Gemini 模型使用 Gemini API
  263. return $this->geminiStreamResponse($post_data, $model);
  264. } else if (in_array($model, $this->valid_text_models)) {
  265. // 火山引擎支持的模型使用火山引擎 API
  266. return $this->volcEngineChatCompletion($post_data);
  267. } else {
  268. Utils::throwError('20003:不支持的模型: ' . $model);
  269. }
  270. }
  271. public function createGenerateText($data) {
  272. $file = getProp($data, 'file');
  273. $episode_num = getProp($data, 'episode_num');
  274. $uid = Site::getUid();
  275. $cpid = Site::getCpid();
  276. if (!$file) {
  277. Utils::throwError('20003:请上传文件');
  278. }
  279. // 提取文件内容
  280. $content = $this->extractFileContent($file);
  281. if (!$content) {
  282. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  283. }
  284. // 拆分章节并校验章节总数、标题连续性
  285. if ($episode_num) {
  286. $this->validateGenerateTextChapters($content, (int)$episode_num);
  287. }
  288. // 获取原始文件名(不含扩展名)作为script_name
  289. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  290. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  291. // 字节安全剥离,不依赖服务器locale设置
  292. $originalName = $file->getClientOriginalName();
  293. $extension = $file->getClientOriginalExtension();
  294. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  295. ? substr($originalName, 0, -strlen($extension) - 1)
  296. : $originalName;
  297. if ($script_name === '') {
  298. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  299. }
  300. // 如果同一用户的剧本名存在则提示
  301. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  302. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  303. }
  304. // 插入数据到mp_scripts表
  305. $script_id = DB::table('mp_scripts')->insertGetId([
  306. 'script_name' => $script_name,
  307. 'user_id' => $uid,
  308. 'cpid' => $cpid,
  309. 'content' => $content,
  310. 'created_at' => date('Y-m-d H:i:s'),
  311. 'updated_at' => date('Y-m-d H:i:s')
  312. ]);
  313. return [
  314. 'script_id' => $script_id,
  315. 'script_name' => $script_name
  316. ];
  317. }
  318. /**
  319. * 拆分剧本内容并校验章节总数与标题连续性
  320. *
  321. * @param string $content
  322. * @param int $episodeNum
  323. * @return void
  324. */
  325. private function validateGenerateTextChapters($content, $episodeNum)
  326. {
  327. $chapters = splitContent($content);
  328. if (count($chapters) !== $episodeNum) {
  329. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  330. }
  331. if (empty($chapters)) {
  332. return;
  333. }
  334. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  335. $numbers = [];
  336. $unparsedIndex = null;
  337. foreach ($chapters as $index => $chapter) {
  338. $num = $this->parseChapterNumber($chapter['title']);
  339. if ($num === null) {
  340. $unparsedIndex = $index;
  341. break;
  342. }
  343. $numbers[] = $num;
  344. }
  345. if ($unparsedIndex === null) {
  346. $expected = 1;
  347. foreach ($numbers as $index => $num) {
  348. if ($num !== $expected) {
  349. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  350. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  351. }
  352. $expected++;
  353. }
  354. return;
  355. }
  356. // 标题格式无法用正则确认时,交给模型分析
  357. $titles = array_column($chapters, 'title');
  358. $aiResult = $this->validateChapterSequenceByAI($titles);
  359. if ($aiResult['valid'] === false) {
  360. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  361. if (isset($chapters[$badIndex - 1])) {
  362. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  363. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  364. }
  365. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  366. }
  367. if ($aiResult['valid'] === null) {
  368. if (isset($chapters[$unparsedIndex])) {
  369. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  370. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  371. }
  372. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  373. }
  374. }
  375. /**
  376. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  377. *
  378. * @param string $title
  379. * @return int|null
  380. */
  381. private function parseChapterNumber($title)
  382. {
  383. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  384. return null;
  385. }
  386. return $this->convertChineseNumber($match[1]);
  387. }
  388. /**
  389. * 中文数字转阿拉伯数字(支持到千)
  390. *
  391. * @param string $numStr
  392. * @return int
  393. */
  394. private function convertChineseNumber($numStr)
  395. {
  396. if (preg_match('/^\d+$/', $numStr)) {
  397. return (int)$numStr;
  398. }
  399. $map = [
  400. '零' => 0,
  401. '一' => 1,
  402. '二' => 2,
  403. '两' => 2,
  404. '三' => 3,
  405. '四' => 4,
  406. '五' => 5,
  407. '六' => 6,
  408. '七' => 7,
  409. '八' => 8,
  410. '九' => 9
  411. ];
  412. $total = 0;
  413. $section = 0;
  414. $length = mb_strlen($numStr);
  415. for ($i = 0; $i < $length; $i++) {
  416. $char = mb_substr($numStr, $i, 1);
  417. if (isset($map[$char])) {
  418. $section = $map[$char];
  419. } elseif ($char === '十') {
  420. $total += $section === 0 ? 10 : $section * 10;
  421. $section = 0;
  422. } elseif ($char === '百') {
  423. $total += $section === 0 ? 100 : $section * 100;
  424. $section = 0;
  425. } elseif ($char === '千') {
  426. $total += $section === 0 ? 1000 : $section * 1000;
  427. $section = 0;
  428. }
  429. }
  430. return $total + $section;
  431. }
  432. /**
  433. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  434. *
  435. * @param array $titles
  436. * @return array{valid: bool|null, invalid_index: int|null}
  437. */
  438. private function validateChapterSequenceByAI($titles)
  439. {
  440. $titleLines = [];
  441. foreach (array_slice($titles, 0, 200) as $index => $title) {
  442. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  443. }
  444. $result = [
  445. 'valid' => null,
  446. 'invalid_index' => null
  447. ];
  448. $post_data = [
  449. 'model' => 'deepseek-v4-flash',
  450. 'messages' => [
  451. [
  452. 'role' => 'system',
  453. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  454. ],
  455. [
  456. 'role' => 'user',
  457. 'content' => implode("\n", $titleLines),
  458. ],
  459. ],
  460. 'temperature' => 0,
  461. 'frequency_penalty' => 0,
  462. 'presence_penalty' => 0,
  463. 'stream' => false,
  464. ];
  465. try {
  466. $result = $this->chatOnly($post_data, 8);
  467. $content = trim((string)($result['fullContent'] ?? ''));
  468. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  469. $result['valid'] = strtolower($match[1]) === 'true';
  470. }
  471. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  472. $result['invalid_index'] = (int)$match[1];
  473. }
  474. } catch (\Exception $e) {
  475. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  476. }
  477. return $result;
  478. }
  479. /**
  480. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  481. *
  482. * @param array $data 请求参数
  483. * @return array 返回结果数组
  484. */
  485. public function newGenerateText($data) {
  486. // 获取请求参数
  487. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  488. $messages = getProp($data, 'messages', []);
  489. $systemPrompt = getProp($data, 'system_prompt', '');
  490. $prompt = getProp($data, 'prompt', '');
  491. $images = getProp($data, 'images', []); // 支持多张图片
  492. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  493. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  494. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  495. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  496. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  497. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  498. $generateTaskId = 0;
  499. if ($script_id > 0) {
  500. $uid = Site::getUid();
  501. $existingTask = DB::table('mp_script_generate_tasks')
  502. ->where('uid', $uid)
  503. ->where('script_id', $script_id)
  504. ->orderByDesc('id')
  505. ->first();
  506. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  507. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  508. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  509. }
  510. }
  511. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  512. $originalContent = '';
  513. if ($script_id > 0) {
  514. $script = DB::table('mp_scripts')
  515. ->where('id', $script_id)
  516. ->where('is_deleted', 0)
  517. ->first();
  518. if (!$script) {
  519. Utils::throwError('20003:剧本不存在或已删除');
  520. }
  521. $originalContent = $script->content ?? '';
  522. if (empty($originalContent)) {
  523. Utils::throwError('20003:剧本内容为空');
  524. }
  525. // 将剧本内容添加到提示词前面
  526. if (!empty($originalContent)) {
  527. if (!empty($prompt)) {
  528. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  529. } else {
  530. $prompt = "原文内容:\n" . $originalContent;
  531. }
  532. }
  533. }
  534. // 新增: 如果提供了template_id,从数据库获取template_prompt
  535. if ($templateId > 0) {
  536. $template = DB::table('mp_prompt_templates')
  537. ->where('id', $templateId)
  538. ->where('is_deleted', 0)
  539. ->first();
  540. if (!$template) {
  541. Utils::throwError('20003:模板不存在或已删除');
  542. }
  543. $templatePrompt = $template->template_prompt ?? '';
  544. // 将模板提示词和用户输入的prompt组合
  545. // 模板为准,用户输入作为补充要求
  546. if (!empty($templatePrompt)) {
  547. if (!empty($prompt)) {
  548. $prompt = $templatePrompt . "\n\n" . $prompt;
  549. } else {
  550. $prompt = $templatePrompt;
  551. }
  552. }
  553. }
  554. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  555. if (empty($messages)) {
  556. $messages = [];
  557. // 添加系统提示词
  558. if (!empty($systemPrompt)) {
  559. $messages[] = [
  560. 'role' => 'system',
  561. 'content' => $systemPrompt
  562. ];
  563. }
  564. // 构建用户消息内容(支持文本+图片)
  565. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  566. $userMessage = [
  567. 'role' => 'user',
  568. 'content' => []
  569. ];
  570. // 添加文本内容
  571. if (!empty($prompt)) {
  572. $userMessage['content'][] = [
  573. 'type' => 'text',
  574. 'text' => $prompt
  575. ];
  576. }
  577. // 处理上传的图片文件
  578. if (!empty($images)) {
  579. if (!is_array($images)) {
  580. $images = [$images];
  581. }
  582. foreach ($images as $image) {
  583. $imageBase64 = $this->processImageToBase64($image);
  584. if ($imageBase64) {
  585. $userMessage['content'][] = [
  586. 'type' => 'image_url',
  587. 'image_url' => [
  588. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  589. ]
  590. ];
  591. }
  592. }
  593. }
  594. // 处理图片URL
  595. if (!empty($imageUrls)) {
  596. if (!is_array($imageUrls)) {
  597. $imageUrls = [$imageUrls];
  598. }
  599. foreach ($imageUrls as $url) {
  600. if (!empty($url)) {
  601. $userMessage['content'][] = [
  602. 'type' => 'image_url',
  603. 'image_url' => [
  604. 'url' => $url
  605. ]
  606. ];
  607. }
  608. }
  609. }
  610. // 如果只有文本内容,简化为字符串格式
  611. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  612. $userMessage['content'] = $userMessage['content'][0]['text'];
  613. }
  614. $messages[] = $userMessage;
  615. }
  616. }
  617. // 验证messages不为空
  618. if (empty($messages)) {
  619. Utils::throwError('20003:请提供有效的对话内容');
  620. }
  621. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  622. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  623. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  624. if ($model === 'deepseek-chat') {
  625. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  626. $model = 'deepseek-v4-flash';
  627. $thinkingMode = 'disabled';
  628. } elseif ($model === 'deepseek-reasoner') {
  629. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  630. $model = 'deepseek-v4-flash';
  631. $thinkingMode = 'enabled';
  632. }
  633. // 构建请求参数(非流式)
  634. $post_data = [
  635. 'model' => $model,
  636. 'messages' => $messages,
  637. 'temperature' => getProp($data, 'temperature', 1),
  638. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  639. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  640. 'thinking' => ['type' => $thinkingMode],
  641. 'stream' => false // 非流式输出
  642. ];
  643. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  644. // 添加可选参数
  645. if (isset($data['top_p'])) {
  646. $post_data['top_p'] = $data['top_p'];
  647. }
  648. // 新增: 根据response_format设置响应格式
  649. if ($responseFormat === 'json') {
  650. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  651. $hasJsonKeyword = false;
  652. foreach ($post_data['messages'] as $message) {
  653. if (isset($message['content'])) {
  654. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  655. if (stripos($content, 'json') !== false) {
  656. $hasJsonKeyword = true;
  657. break;
  658. }
  659. }
  660. }
  661. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  662. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  663. if (!$hasJsonKeyword) {
  664. $lastMessageIndex = count($post_data['messages']) - 1;
  665. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  666. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  667. // 如果content是字符串,直接追加
  668. if (is_string($lastContent)) {
  669. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  670. }
  671. // 如果content是数组(包含文本和图片),在文本部分追加
  672. else if (is_array($lastContent)) {
  673. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  674. if ($contentPart['type'] === 'text') {
  675. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  676. break;
  677. }
  678. }
  679. }
  680. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  681. }
  682. }
  683. // 设置response_format参数(所有支持的模型)
  684. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  685. // DeepSeek模型
  686. $post_data['response_format'] = ['type' => 'json_object'];
  687. } else if (in_array($model, $this->gpt_text_models)) {
  688. // GPT模型
  689. $post_data['response_format'] = ['type' => 'json_object'];
  690. } else if (in_array($model, $this->valid_text_models)) {
  691. // 火山引擎模型
  692. $post_data['response_format'] = ['type' => 'json_object'];
  693. }
  694. }
  695. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  696. if ($script_id > 0) {
  697. $uid = Site::getUid();
  698. // 创建新的生成任务
  699. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  700. 'uid' => $uid,
  701. 'script_id' => $script_id,
  702. 'sequence' => $sequence,
  703. 'status' => 'processing',
  704. 'prompt' => getProp($data, 'prompt', ''),
  705. 'started_at' => date('Y-m-d H:i:s'),
  706. 'created_at' => date('Y-m-d H:i:s'),
  707. 'updated_at' => date('Y-m-d H:i:s')
  708. ]);
  709. }
  710. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  711. try {
  712. $aiResult = null;
  713. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  714. // DeepSeek 官方模型使用现有的 chatOnly 方法
  715. $result = $this->chatOnly($post_data);
  716. // 记录实际使用的模型
  717. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  718. $aiResult = [
  719. 'content' => $result['fullContent'],
  720. 'reasoning_content' => $result['fullReasoningContent'],
  721. 'usage' => $result['usage'],
  722. 'model' => $model,
  723. 'finish_reason' => 'stop'
  724. ];
  725. } else if (in_array($model, $this->gpt_text_models)) {
  726. // GPT 模型使用现有的 gpt54ChatOnly 方法
  727. $result = $this->gpt54ChatOnly($post_data);
  728. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  729. $aiResult = [
  730. 'content' => $result['fullContent'],
  731. 'reasoning_content' => '',
  732. 'usage' => $result['usage'],
  733. 'model' => $model,
  734. 'finish_reason' => 'stop'
  735. ];
  736. } else if (in_array($model, $this->gemini_text_models)) {
  737. // Gemini 模型使用 Gemini API(非流式)
  738. $result = $this->geminiChatOnly($post_data, $model);
  739. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  740. $aiResult = [
  741. 'content' => $result['fullContent'],
  742. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  743. 'usage' => $result['usage'],
  744. 'model' => $model,
  745. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  746. ];
  747. } else if (in_array($model, $this->valid_text_models)) {
  748. // 火山引擎支持的模型使用火山引擎 API(非流式)
  749. $post_data['stream'] = false;
  750. $result = $this->volcEngineChatCompletion($post_data);
  751. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  752. 'requested_model' => $model,
  753. 'result_keys' => array_keys($result),
  754. 'has_fullContent' => isset($result['fullContent']),
  755. 'has_content' => isset($result['content'])
  756. ]);
  757. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  758. $aiResult = [
  759. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  760. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  761. 'usage' => $result['usage'] ?? [],
  762. 'model' => $model,
  763. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  764. ];
  765. } else {
  766. Utils::throwError('20003:不支持的模型: ' . $model);
  767. }
  768. } catch (\Exception $e) {
  769. // 生成失败,更新任务状态
  770. if ($generateTaskId) {
  771. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  772. 'status' => 'failed',
  773. 'error_message' => $e->getMessage(),
  774. 'completed_at' => date('Y-m-d H:i:s'),
  775. 'updated_at' => date('Y-m-d H:i:s')
  776. ]);
  777. }
  778. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  779. }
  780. // 生成成功,更新任务状态
  781. if ($generateTaskId && $aiResult) {
  782. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  783. 'status' => 'success',
  784. 'result' => getProp($aiResult, 'content', ''),
  785. 'completed_at' => date('Y-m-d H:i:s'),
  786. 'updated_at' => date('Y-m-d H:i:s')
  787. ]);
  788. $aiResult['generate_task_id'] = $generateTaskId;
  789. }
  790. // 新增: 如果提供了script_id,保存对话记录
  791. if ($script_id > 0 && $aiResult) {
  792. try {
  793. $uid = Site::getUid();
  794. $now = now();
  795. // 获取用户原始的prompt(不包含剧本内容)
  796. $originalPrompt = getProp($data, 'prompt', '');
  797. $recordsToInsert = [
  798. [
  799. 'uid' => $uid,
  800. 'script_id' => $script_id,
  801. 'sequence' => $sequence,
  802. 'role' => 'user',
  803. 'content' => $originalPrompt,
  804. 'created_at' => $now,
  805. 'updated_at' => $now,
  806. ],
  807. [
  808. 'uid' => $uid,
  809. 'script_id' => $script_id,
  810. 'sequence' => $sequence,
  811. 'role' => 'assistant',
  812. 'content' => $aiResult['content'],
  813. 'created_at' => $now,
  814. 'updated_at' => $now,
  815. ]
  816. ];
  817. DB::table('mp_script_records')->insert($recordsToInsert);
  818. // 获取刚插入的记录ID(假设按插入顺序返回)
  819. $insertedRecords = DB::table('mp_script_records')
  820. ->where('uid', $uid)
  821. ->where('script_id', $script_id)
  822. ->where('sequence', $sequence)
  823. ->orderBy('id', 'desc')
  824. ->limit(2)
  825. ->get()
  826. ->map(function ($record) {
  827. return [
  828. 'rid' => $record->id,
  829. 'script_id' => $record->script_id,
  830. 'sequence' => $record->sequence,
  831. 'role' => $record->role,
  832. 'content' => $record->content,
  833. 'created_at' => $record->created_at,
  834. ];
  835. })
  836. ->reverse()
  837. ->values()
  838. ->toArray();
  839. // 将记录信息添加到返回结果中
  840. $aiResult['records'] = $insertedRecords;
  841. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  842. } catch (\Exception $e) {
  843. // 记录错误但不影响主流程
  844. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  845. }
  846. }
  847. return $aiResult;
  848. }
  849. /**
  850. * 通用 Gemini 文生文方法(支持流式和非流式)
  851. *
  852. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  853. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  854. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  855. * system_prompt 系统提示词(可选)
  856. * prompt 用户提示词(可选)
  857. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  858. * image_urls 图片/视频URL列表(可选,同上)
  859. * temperature 温度(可选,默认 1)
  860. * top_p 核采样(可选)
  861. * max_tokens 最大输出 token(可选,默认 8192)
  862. * response_format text/json(可选)
  863. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  864. * thinking_budget 思考预算(可选,默认 20)
  865. * stream 是否流式(可选,默认 false)
  866. *
  867. * @param array $data 请求参数
  868. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  869. */
  870. public function geminiGenerateText($data) {
  871. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  872. $isStream = (bool)getProp($data, 'stream', false);
  873. if (!in_array($model, $this->gemini_text_models)) {
  874. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  875. }
  876. $requestData = $this->buildGeminiRequestBody($data, $model);
  877. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  878. if ($isStream) {
  879. // 流式返回生成器
  880. return $this->geminiStreamResponse($requestData, $model);
  881. }
  882. // 非流式
  883. return $this->geminiChatOnly($requestData, $model);
  884. }
  885. /**
  886. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  887. */
  888. private function geminiMediaMaxBytes() {
  889. return 14 * 1024 * 1024;
  890. }
  891. /**
  892. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  893. */
  894. private function buildGeminiRequestBody($data, $model) {
  895. $messages = getProp($data, 'messages', []);
  896. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  897. if (empty($messages)) {
  898. $systemPrompt = getProp($data, 'system_prompt', '');
  899. $prompt = getProp($data, 'prompt', '');
  900. $images = getProp($data, 'images', []);
  901. $imageUrls = getProp($data, 'image_urls', []);
  902. $messages = [];
  903. if (!empty($systemPrompt)) {
  904. $messages[] = [
  905. 'role' => 'system',
  906. 'content' => $systemPrompt
  907. ];
  908. }
  909. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  910. $userMessage = ['role' => 'user', 'content' => []];
  911. if (!empty($prompt)) {
  912. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  913. }
  914. if (!empty($images)) {
  915. if (!is_array($images)) {
  916. $images = [$images];
  917. }
  918. foreach ($images as $image) {
  919. $inlineData = $this->processMediaToInlineData($image);
  920. if ($inlineData) {
  921. $userMessage['content'][] = [
  922. 'type' => 'image',
  923. 'inline_data' => $inlineData
  924. ];
  925. }
  926. }
  927. }
  928. if (!empty($imageUrls)) {
  929. if (!is_array($imageUrls)) {
  930. $imageUrls = [$imageUrls];
  931. }
  932. foreach ($imageUrls as $url) {
  933. if (!empty($url)) {
  934. $inlineData = $this->processMediaToInlineData($url);
  935. if ($inlineData) {
  936. $userMessage['content'][] = [
  937. 'type' => 'image',
  938. 'inline_data' => $inlineData
  939. ];
  940. }
  941. }
  942. }
  943. }
  944. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  945. $userMessage['content'] = $userMessage['content'][0]['text'];
  946. }
  947. $messages[] = $userMessage;
  948. }
  949. }
  950. if (empty($messages)) {
  951. Utils::throwError('20003:请提供有效的对话内容');
  952. }
  953. // 转换为 Gemini contents 格式
  954. $systemInstruction = '';
  955. $contents = [];
  956. foreach ($messages as $message) {
  957. $role = getProp($message, 'role', 'user');
  958. $content = getProp($message, 'content', '');
  959. if ($role === 'system') {
  960. if (is_array($content)) {
  961. $systemInstruction = $this->extractGeminiTextFromParts($content);
  962. } else {
  963. $systemInstruction = (string)$content;
  964. }
  965. continue;
  966. }
  967. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  968. $parts = [];
  969. if (is_array($content)) {
  970. foreach ($content as $part) {
  971. $partType = getProp($part, 'type', 'text');
  972. if ($partType === 'text') {
  973. $text = (string)getProp($part, 'text', '');
  974. if ($text !== '') {
  975. $parts[] = ['text' => $text];
  976. }
  977. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  978. if (in_array($partType, ['image_url', 'video_url'])) {
  979. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  980. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  981. } elseif (isset($part['inline_data'])) {
  982. // 已处理过的 inline_data 直接使用
  983. $parts[] = ['inline_data' => $part['inline_data']];
  984. continue;
  985. } else {
  986. $url = '';
  987. }
  988. $inlineData = $this->processMediaToInlineData($url);
  989. if ($inlineData) {
  990. $parts[] = ['inline_data' => $inlineData];
  991. }
  992. }
  993. }
  994. } else {
  995. $text = (string)$content;
  996. if ($text !== '') {
  997. $parts[] = ['text' => $text];
  998. }
  999. }
  1000. if (!empty($parts)) {
  1001. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1002. }
  1003. }
  1004. if (empty($contents)) {
  1005. Utils::throwError('20003:请提供有效的对话内容');
  1006. }
  1007. // 构建生成配置
  1008. $generationConfig = [];
  1009. if (getProp($data, 'temperature', null) !== null) {
  1010. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1011. }
  1012. if (getProp($data, 'top_p', null) !== null) {
  1013. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1014. }
  1015. if (getProp($data, 'frequency_penalty', null) !== null) {
  1016. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1017. }
  1018. if (getProp($data, 'presence_penalty', null) !== null) {
  1019. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1020. }
  1021. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1022. if ($maxOutputTokens <= 0) {
  1023. $maxOutputTokens = 8192;
  1024. }
  1025. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1026. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1027. $maxOutputTokens = 32768;
  1028. }
  1029. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1030. // response_format 映射:text -> text/plain,json -> application/json
  1031. $responseFormat = getProp($data, 'response_format', 'text');
  1032. if (is_array($responseFormat)) {
  1033. $responseFormat = getProp($responseFormat, 'type', 'text');
  1034. }
  1035. if (in_array($responseFormat, ['json', 'json_object'])) {
  1036. $generationConfig['responseMimeType'] = 'application/json';
  1037. } else {
  1038. $generationConfig['responseMimeType'] = 'text/plain';
  1039. }
  1040. $requestData = [
  1041. 'contents' => $contents,
  1042. 'generationConfig' => $generationConfig,
  1043. ];
  1044. if ($systemInstruction !== '') {
  1045. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1046. }
  1047. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1048. $thinkingMode = getProp($data, 'thinking', null);
  1049. if (is_array($thinkingMode)) {
  1050. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1051. }
  1052. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1053. if ($thinkingMode === null) {
  1054. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1055. }
  1056. if ($thinkingMode === 'enabled') {
  1057. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1058. if ($thinkingBudget <= 0) {
  1059. $thinkingBudget = 20;
  1060. }
  1061. $requestData['generationConfig']['thinkingConfig'] = [
  1062. 'thinkingBudget' => $thinkingBudget
  1063. ];
  1064. } elseif ($defaultThinking) {
  1065. // 该模型仅支持思考模式,传 0 会返回 400
  1066. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1067. } else {
  1068. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1069. }
  1070. return $requestData;
  1071. }
  1072. /**
  1073. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1074. *
  1075. * 模型名 -> env 变量名映射:
  1076. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1077. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1078. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1079. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1080. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1081. */
  1082. private function getGeminiApiKey($model) {
  1083. $map = [
  1084. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1085. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1086. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1087. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1088. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1089. ];
  1090. if (isset($map[$model])) {
  1091. $key = env($map[$model]);
  1092. if (!empty($key)) {
  1093. return $key;
  1094. }
  1095. }
  1096. return env('GEMINI_API_KEY', '');
  1097. }
  1098. /**
  1099. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1100. */
  1101. private function geminiChatOnly($requestData, $model) {
  1102. $apiKey = $this->getGeminiApiKey($model);
  1103. if (empty($apiKey)) {
  1104. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1105. }
  1106. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1107. if (isset($requestData['messages'])) {
  1108. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1109. }
  1110. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1111. . '/models/' . $model . ':generateContent';
  1112. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1113. $headers = [
  1114. 'Authorization' => 'Bearer ' . $apiKey,
  1115. 'Content-Type' => 'application/json'
  1116. ];
  1117. $maxRetries = $this->gptRetryTimes();
  1118. $interval = $this->gptRetryInterval();
  1119. $attempt = 0;
  1120. while (true) {
  1121. try {
  1122. $response = $client->post($url, [
  1123. 'json' => $requestData,
  1124. 'headers' => $headers
  1125. ]);
  1126. $responseArr = json_decode($response->getBody()->getContents(), true);
  1127. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1128. $fullContent = $this->extractGeminiContent($responseArr);
  1129. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1130. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1131. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1132. ? $responseArr['candidates'][0]['finishReason']
  1133. : '';
  1134. return [
  1135. 'fullContent' => $fullContent,
  1136. 'fullReasoningContent' => $fullReasoningContent,
  1137. 'usage' => $usage,
  1138. 'finish_reason' => $finishReason
  1139. ];
  1140. } catch (\Exception $e) {
  1141. $retryable = true;
  1142. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1143. $status = $e->getResponse()->getStatusCode();
  1144. $retryable = $status >= 500 || $status == 429;
  1145. }
  1146. if (!$retryable || $attempt >= $maxRetries) {
  1147. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1148. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1149. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1150. }
  1151. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1152. 'retry' => $attempt + 1,
  1153. 'max_retries' => $maxRetries,
  1154. 'error' => $e->getMessage()
  1155. ]);
  1156. sleep($interval);
  1157. $attempt++;
  1158. }
  1159. }
  1160. }
  1161. /**
  1162. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1163. */
  1164. private function geminiStreamResponse($requestData, $model) {
  1165. $apiKey = $this->getGeminiApiKey($model);
  1166. if (empty($apiKey)) {
  1167. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1168. }
  1169. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1170. if (isset($requestData['messages'])) {
  1171. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1172. }
  1173. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1174. . '/models/' . $model . ':generateContent?alt=sse';
  1175. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1176. $headers = [
  1177. 'Authorization' => 'Bearer ' . $apiKey,
  1178. 'Content-Type' => 'application/json'
  1179. ];
  1180. try {
  1181. $response = $client->post($url, [
  1182. 'json' => $requestData,
  1183. 'headers' => $headers,
  1184. 'stream' => true
  1185. ]);
  1186. $body = $response->getBody();
  1187. $fullContent = '';
  1188. $fullReasoningContent = '';
  1189. $usage = [];
  1190. $buffer = '';
  1191. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1192. while (!$body->eof()) {
  1193. $chunk = $body->read(1024);
  1194. $buffer .= $chunk;
  1195. $lines = explode("\n", $buffer);
  1196. $buffer = array_pop($lines);
  1197. foreach ($lines as $line) {
  1198. $line = trim($line);
  1199. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1200. continue;
  1201. }
  1202. $data = substr($line, 6);
  1203. if ($data === '[DONE]') {
  1204. break 2;
  1205. }
  1206. try {
  1207. $json = json_decode($data, true);
  1208. if (json_last_error() !== JSON_ERROR_NONE) {
  1209. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1210. continue;
  1211. }
  1212. // 思考内容(thoughts)
  1213. $thoughts = $this->extractGeminiThoughts($json);
  1214. if ($thoughts !== '') {
  1215. $fullReasoningContent .= $thoughts;
  1216. yield [
  1217. 'type' => 'reasoning',
  1218. 'content' => $thoughts,
  1219. 'full_reasoning' => $fullReasoningContent
  1220. ];
  1221. }
  1222. // 回答内容
  1223. $partText = $this->extractGeminiContent($json);
  1224. if ($partText !== '') {
  1225. $fullContent .= $partText;
  1226. yield [
  1227. 'type' => 'content',
  1228. 'content' => $partText,
  1229. ];
  1230. }
  1231. // 使用统计
  1232. if (isset($json['usageMetadata'])) {
  1233. $usage = $json['usageMetadata'];
  1234. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1235. }
  1236. } catch (\Exception $e) {
  1237. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1238. continue;
  1239. }
  1240. }
  1241. }
  1242. dLog('deepseek')->info('Gemini流式读取完成', [
  1243. 'content_length' => strlen($fullContent),
  1244. 'reasoning_length' => strlen($fullReasoningContent)
  1245. ]);
  1246. yield [
  1247. 'type' => 'done',
  1248. 'full_content' => $fullContent,
  1249. 'full_reasoning' => $fullReasoningContent,
  1250. 'usage' => $usage
  1251. ];
  1252. } catch (\Exception $e) {
  1253. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1254. yield [
  1255. 'type' => 'error',
  1256. 'msg' => $e->getMessage(),
  1257. 'code' => $e->getCode()
  1258. ];
  1259. }
  1260. }
  1261. /**
  1262. * 从 Gemini 响应中提取回答文本
  1263. */
  1264. private function extractGeminiContent($responseArr) {
  1265. $text = '';
  1266. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1267. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1268. if (isset($part['text'])) {
  1269. $text .= $part['text'];
  1270. }
  1271. }
  1272. }
  1273. return $text;
  1274. }
  1275. /**
  1276. * 从 Gemini 响应中提取思考内容
  1277. */
  1278. private function extractGeminiReasoningContent($responseArr) {
  1279. $reasoning = '';
  1280. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1281. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1282. if (isset($thought['text'])) {
  1283. $reasoning .= $thought['text'];
  1284. }
  1285. }
  1286. }
  1287. return $reasoning;
  1288. }
  1289. /**
  1290. * 从 Gemini 流式响应中提取本次增量思考内容
  1291. */
  1292. private function extractGeminiThoughts($responseArr) {
  1293. $thoughts = '';
  1294. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1295. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1296. if (isset($thought['text'])) {
  1297. $thoughts .= $thought['text'];
  1298. }
  1299. }
  1300. }
  1301. return $thoughts;
  1302. }
  1303. /**
  1304. * 提取消息数组中的纯文本
  1305. */
  1306. private function extractGeminiTextFromParts($parts) {
  1307. $text = '';
  1308. if (is_array($parts)) {
  1309. foreach ($parts as $part) {
  1310. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1311. $text .= (string)getProp($part, 'text', '');
  1312. }
  1313. }
  1314. }
  1315. return $text;
  1316. }
  1317. /**
  1318. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1319. *
  1320. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1321. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1322. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1323. *
  1324. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1325. * @return array|null ['mime_type' => string, 'data' => string]
  1326. */
  1327. private function processMediaToInlineData($media) {
  1328. if (empty($media)) {
  1329. return null;
  1330. }
  1331. $localPath = null;
  1332. $isTempFile = false;
  1333. try {
  1334. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1335. if (is_string($media) && strpos($media, 'data:') === 0) {
  1336. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1337. return [
  1338. 'mime_type' => $matches[1],
  1339. 'data' => $matches[2]
  1340. ];
  1341. }
  1342. return null;
  1343. }
  1344. // 2. 获取本地文件路径
  1345. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1346. $localPath = $this->downloadMediaToTemp($media);
  1347. $isTempFile = true;
  1348. } elseif (is_string($media)) {
  1349. $localPath = $media;
  1350. } else {
  1351. // Laravel UploadedFile 对象
  1352. $localPath = $media->getRealPath();
  1353. }
  1354. if (!$localPath || !file_exists($localPath)) {
  1355. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1356. return null;
  1357. }
  1358. $fileSize = filesize($localPath);
  1359. $maxBytes = $this->geminiMediaMaxBytes();
  1360. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1361. $mimeType = $this->detectMediaMime($localPath);
  1362. $isVideo = strpos($mimeType, 'video/') === 0;
  1363. $needCompress = $fileSize > $maxBytes;
  1364. $duration = 0;
  1365. if ($isVideo) {
  1366. $duration = $this->getMediaDuration($localPath);
  1367. if ($duration > 300) {
  1368. $needCompress = true;
  1369. }
  1370. }
  1371. $finalPath = $localPath;
  1372. $compressedPath = null;
  1373. if ($needCompress && $this->ffmpegAvailable()) {
  1374. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1375. if ($compressed && file_exists($compressed)) {
  1376. $compressedPath = $compressed;
  1377. if (filesize($compressed) < $fileSize || $isVideo) {
  1378. $finalPath = $compressed;
  1379. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1380. } else {
  1381. @unlink($compressed);
  1382. $compressedPath = null;
  1383. }
  1384. }
  1385. }
  1386. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1387. $finalSize = filesize($finalPath);
  1388. if ($finalSize > $maxBytes) {
  1389. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1390. 'path' => $localPath,
  1391. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1392. 'limit_mb' => 14
  1393. ]);
  1394. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1395. }
  1396. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1397. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1398. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1399. }
  1400. $data = base64_encode(file_get_contents($finalPath));
  1401. return [
  1402. 'mime_type' => $mimeType,
  1403. 'data' => $data
  1404. ];
  1405. } catch (\App\Exceptions\ApiException $e) {
  1406. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1407. throw $e;
  1408. } catch (\Exception $e) {
  1409. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1410. return null;
  1411. } finally {
  1412. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1413. @unlink($compressedPath);
  1414. }
  1415. if ($isTempFile && $localPath && file_exists($localPath)) {
  1416. @unlink($localPath);
  1417. }
  1418. }
  1419. }
  1420. /**
  1421. * 下载远程多媒体到临时目录
  1422. *
  1423. * @return string|null 本地临时文件路径
  1424. */
  1425. private function downloadMediaToTemp($url) {
  1426. try {
  1427. $tempDir = storage_path('app/temp/gemini');
  1428. if (!is_dir($tempDir)) {
  1429. mkdir($tempDir, 0775, true);
  1430. }
  1431. $extension = 'tmp';
  1432. $pathInfo = parse_url($url, PHP_URL_PATH);
  1433. if ($pathInfo) {
  1434. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1435. if ($ext && strlen($ext) <= 10) {
  1436. $extension = strtolower($ext);
  1437. }
  1438. }
  1439. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1440. $client = new Client(['timeout' => 300, 'verify' => false]);
  1441. $response = $client->get($url, ['sink' => $tmpFile]);
  1442. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1443. @unlink($tmpFile);
  1444. return null;
  1445. }
  1446. return $tmpFile;
  1447. } catch (\Exception $e) {
  1448. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1449. return null;
  1450. }
  1451. }
  1452. /**
  1453. * 检测多媒体文件 MIME 类型
  1454. */
  1455. private function detectMediaMime($filePath) {
  1456. $imageInfo = @getimagesize($filePath);
  1457. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1458. return $imageInfo['mime'];
  1459. }
  1460. // 视频按扩展名粗略判断
  1461. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1462. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1463. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1464. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1465. if (isset($videoExts[$ext])) {
  1466. return $videoExts[$ext];
  1467. }
  1468. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1469. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1470. if (isset($imageExts[$ext])) {
  1471. return $imageExts[$ext];
  1472. }
  1473. return 'application/octet-stream';
  1474. }
  1475. /**
  1476. * 获取多媒体时长(秒),非视频或失败返回 0
  1477. */
  1478. private function getMediaDuration($filePath) {
  1479. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1480. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1481. $output = trim((string)shell_exec($cmd));
  1482. $duration = (float)$output;
  1483. return $duration > 0 ? $duration : 0;
  1484. }
  1485. /**
  1486. * 检查 ffmpeg 是否可用
  1487. */
  1488. private function ffmpegAvailable() {
  1489. static $available = null;
  1490. if ($available !== null) {
  1491. return $available;
  1492. }
  1493. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1494. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1495. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1496. $available = false;
  1497. return $available;
  1498. }
  1499. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1500. $output = shell_exec($cmd);
  1501. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1502. return $available;
  1503. }
  1504. /**
  1505. * 使用 ffmpeg 压缩多媒体文件
  1506. *
  1507. * @param string $inputFile 输入文件路径
  1508. * @param bool $isVideo 是否为视频
  1509. * @param float $duration 视频时长(秒),非视频传 0
  1510. * @return string|null 压缩后的文件路径,失败返回 null
  1511. */
  1512. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1513. try {
  1514. $tempDir = storage_path('app/temp/gemini');
  1515. if (!is_dir($tempDir)) {
  1516. mkdir($tempDir, 0775, true);
  1517. }
  1518. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1519. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1520. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1521. if ($isVideo) {
  1522. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1523. $speedFactor = 1.0;
  1524. if ($duration > 300) {
  1525. $speedFactor = $duration / 300;
  1526. }
  1527. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1528. $finalDuration = $duration / max(1.0, $speedFactor);
  1529. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1530. $targetBitrate = max(300, min(6000, $targetBitrate));
  1531. $filters = [];
  1532. $filters[] = 'scale=min(1280,iw):-2';
  1533. $filters[] = 'fps=24';
  1534. if ($speedFactor > 1.0) {
  1535. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1536. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1537. $fullCount = (int)ceil($speedFactor / 2.0);
  1538. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1539. if ($lastTempo < 0.5) {
  1540. $fullCount++;
  1541. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1542. }
  1543. for ($i = 0; $i < $fullCount; $i++) {
  1544. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1545. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1546. }
  1547. }
  1548. $filterStr = implode(',', $filters);
  1549. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1550. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1551. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1552. } else {
  1553. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1554. $imageInfo = @getimagesize($inputFile);
  1555. $scaleW = 2048;
  1556. $scaleH = 2048;
  1557. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1558. if ($imageInfo[0] >= $imageInfo[1]) {
  1559. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1560. $scaleW = 2048;
  1561. } else {
  1562. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1563. $scaleH = 2048;
  1564. }
  1565. }
  1566. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1567. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1568. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1569. }
  1570. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1571. $output = shell_exec($cmd);
  1572. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1573. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1574. 'input' => $inputFile,
  1575. 'output' => $output
  1576. ]);
  1577. @unlink($outputFile);
  1578. return null;
  1579. }
  1580. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1581. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1582. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1583. ]);
  1584. return $outputFile;
  1585. } catch (\Exception $e) {
  1586. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1587. return null;
  1588. }
  1589. }
  1590. /**
  1591. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1592. *
  1593. * @param array $data
  1594. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1595. */
  1596. public function getScriptGenerateTasks($data) {
  1597. $uid = Site::getUid();
  1598. return DB::table('mp_script_generate_tasks as t')
  1599. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1600. ->where('t.uid', $uid)
  1601. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1602. ->orderByDesc('t.id')
  1603. ->paginate(15);
  1604. }
  1605. public function saveScriptChatHistory($data) {
  1606. $uid = Site::getUid();
  1607. $rid = getProp($data, 'rid');
  1608. $script_id = getProp($data, 'script_id');
  1609. $sequence = getProp($data, 'sequence', 0);
  1610. $content = getProp($data, 'content');
  1611. if (!$rid) {
  1612. Utils::throwError('20003:请选择对话记录ID');
  1613. }
  1614. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1615. if (!$record) {
  1616. Utils::throwError('20003:对话记录不存在');
  1617. }
  1618. if (!$script_id) {
  1619. Utils::throwError('20003:请选择剧本');
  1620. }
  1621. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1622. if (!$script) {
  1623. Utils::throwError('20003:剧本不存在');
  1624. }
  1625. // 批量插入数据
  1626. return DB::table('mp_script_records')->where('id', $rid)->update([
  1627. 'content' => $content,
  1628. 'updated_at' => date('Y-m-d H:i:s')
  1629. ]);
  1630. }
  1631. /**
  1632. * 获取剧本的历史对话记录
  1633. *
  1634. * @param array $data 请求参数
  1635. * @return array 返回历史记录数组
  1636. */
  1637. public function getScriptChatHistory($data) {
  1638. $uid = Site::getUid();
  1639. $script_id = getProp($data, 'script_id');
  1640. $rid = getProp($data, 'rid');
  1641. $sequence = getProp($data, 'sequence', null);
  1642. if (!$script_id) {
  1643. Utils::throwError('20003:请提供剧本ID');
  1644. }
  1645. // 验证剧本是否存在
  1646. $script = DB::table('mp_scripts')
  1647. ->where('id', $script_id)
  1648. ->where('is_deleted', 0)
  1649. ->first();
  1650. if (!$script) {
  1651. Utils::throwError('20003:剧本不存在');
  1652. }
  1653. // 构建查询
  1654. $query = DB::table('mp_script_records')
  1655. ->where('script_id', $script_id);
  1656. // ->where('uid', $uid);
  1657. // 如果提供了 sequence,则过滤指定剧集
  1658. if ($sequence !== null) {
  1659. $query->where('sequence', $sequence);
  1660. }
  1661. // 记录ID筛选
  1662. if ($rid) {
  1663. $query->where('id', $rid);
  1664. }
  1665. // 查询记录并按 id 正序排序
  1666. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1667. ->orderBy('created_at', 'asc')
  1668. ->orderBy('id', 'asc')
  1669. ->get()
  1670. ->map(function ($record) {
  1671. return [
  1672. 'rid' => $record->id,
  1673. 'script_id' => $record->script_id,
  1674. 'sequence' => $record->sequence,
  1675. 'role' => $record->role,
  1676. 'content' => $record->content,
  1677. 'products' => $record->products ? json_decode($record->products) : [],
  1678. 'created_at' => $record->created_at,
  1679. ];
  1680. })
  1681. ->toArray();
  1682. return $records;
  1683. }
  1684. /**
  1685. * 处理图片转换为base64
  1686. *
  1687. * @param mixed $image 图片文件对象或文件路径
  1688. * @return string|null base64编码的图片数据
  1689. */
  1690. private function processImageToBase64($image) {
  1691. try {
  1692. // 获取文件路径
  1693. if (is_string($image)) {
  1694. $filePath = $image;
  1695. } else {
  1696. // Laravel UploadedFile 对象
  1697. $filePath = $image->getRealPath();
  1698. }
  1699. if (!file_exists($filePath)) {
  1700. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1701. return null;
  1702. }
  1703. // 验证是否为图片文件
  1704. $imageInfo = @getimagesize($filePath);
  1705. if ($imageInfo === false) {
  1706. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1707. return null;
  1708. }
  1709. // 读取图片并转换为base64
  1710. $imageData = file_get_contents($filePath);
  1711. $base64Image = base64_encode($imageData);
  1712. dLog('deepseek')->info('图片转换成功', [
  1713. 'size' => strlen($imageData),
  1714. 'type' => $imageInfo['mime']
  1715. ]);
  1716. return $base64Image;
  1717. } catch (\Exception $e) {
  1718. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1719. return null;
  1720. }
  1721. }
  1722. private function getArtStylePromptMappings($art_style='')
  1723. {
  1724. $arr = [
  1725. '唯美真人风格' => [
  1726. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1727. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1728. ],
  1729. '真人古风风格' => [
  1730. 'aliases' => ['真人古风风格', '真人古风'],
  1731. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1732. ],
  1733. '日系动漫风格' => [
  1734. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1735. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1736. ],
  1737. '国漫风格' => [
  1738. 'aliases' => ['国漫风格', '国漫'],
  1739. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1740. ],
  1741. 'Q版卡通风格' => [
  1742. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1743. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1744. ],
  1745. '简约扁平风格' => [
  1746. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1747. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1748. ],
  1749. '武侠风格' => [
  1750. 'aliases' => ['武侠风格', '武侠'],
  1751. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1752. ],
  1753. '古风仙侠风格' => [
  1754. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1755. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1756. ],
  1757. '新中式水墨风格' => [
  1758. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1759. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1760. ],
  1761. '写实插画风格' => [
  1762. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1763. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1764. ],
  1765. '3D卡通风格' => [
  1766. 'aliases' => ['3D卡通风格', '3D卡通'],
  1767. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1768. ],
  1769. '条漫风格' => [
  1770. 'aliases' => ['条漫风格', '条漫'],
  1771. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1772. ],
  1773. '赛博朋克风格' => [
  1774. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1775. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  1776. ],
  1777. '暗黑悬疑风格' => [
  1778. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1779. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  1780. ],
  1781. '治愈清新风格' => [
  1782. 'aliases' => ['治愈清新风格', '治愈清新'],
  1783. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  1784. ],
  1785. '3D真人风格' => [
  1786. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  1787. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  1788. ],
  1789. ];
  1790. if($art_style) {
  1791. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  1792. }
  1793. return $arr;
  1794. $arr = [
  1795. '唯美真人风格' => [
  1796. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1797. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  1798. 2. 色彩色调
  1799. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  1800. 3. 画质精度
  1801. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  1802. 4. 画面观感
  1803. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  1804. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  1805. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  1806. ],
  1807. '真人古风风格' => [
  1808. 'aliases' => ['真人古风风格', '真人古风'],
  1809. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  1810. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  1811. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  1812. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  1813. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  1814. ],
  1815. '日系动漫风格' => [
  1816. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1817. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  1818. 正向提示词(中文)
  1819. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  1820. 必须遵守规则
  1821. • 全程保持日系动漫风格,不混入其他画风
  1822. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  1823. • 画面适配所选画面比例,构图居中,主体突出
  1824. • 线条干净、色彩统一,不杂乱、不突兀
  1825. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  1826. ],
  1827. '国漫风格' => [
  1828. 'aliases' => ['国漫风格', '国漫'],
  1829. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  1830. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  1831. 必须遵守规则
  1832. • 严格保持国漫画风,不串风格、不混画风
  1833. • 角色形象统一,不随意改变五官、身材、服饰
  1834. • 画面构图稳定,适合漫剧叙事展示
  1835. • 色调统一,不出现脏色、杂色
  1836. 禁止/避免词汇
  1837. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  1838. ],
  1839. 'Q版卡通风格' => [
  1840. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1841. 'prompt' => "风格说明
  1842. 头大身小,造型可爱圆润,简约干净
  1843. 正向提示词(中文)
  1844. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  1845. 必须遵守规则
  1846. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  1847. • 角色造型统一,表情可爱,不诡异
  1848. • 画面简洁清爽,无多余复杂元素
  1849. • 色彩明亮柔和,不刺眼
  1850. 禁止/避免词汇
  1851. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  1852. ],
  1853. '简约扁平风格' => [
  1854. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1855. 'prompt' => "风格说明
  1856. 色块简洁、无复杂渐变,现代极简风
  1857. 正向提示词(中文)
  1858. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  1859. 必须遵守规则
  1860. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  1861. • 构图简洁,主体突出,无多余装饰
  1862. • 色彩统一、干净,不杂乱
  1863. 禁止/避免词汇
  1864. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  1865. ],
  1866. '武侠风格' => [
  1867. 'aliases' => ['武侠风格', '武侠'],
  1868. 'prompt' => "风格说明
  1869. 江湖气息,线条硬朗,动作感强
  1870. 正向提示词(中文)
  1871. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  1872. 必须遵守规则
  1873. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  1874. • 角色形象、服饰、身材比例统一
  1875. • 画面动作自然,不扭曲、不畸形
  1876. 禁止/避免词汇
  1877. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  1878. ],
  1879. '古风仙侠风格' => [
  1880. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1881. 'prompt' => "风格说明
  1882. 飘逸汉服、云雾仙气、唯美空灵
  1883. 正向提示词(中文)
  1884. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  1885. 必须遵守规则
  1886. • 保持古风仙侠统一画风,不混入现代、科幻元素
  1887. • 角色服饰、发型、形象前后一致
  1888. • 场景仙气飘逸,色调清雅统一
  1889. • 画面唯美柔和,不阴暗、不诡异
  1890. 禁止/避免词汇
  1891. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  1892. ],
  1893. '新中式水墨风格' => [
  1894. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1895. 'prompt' => "风格说明
  1896. 淡墨渲染,毛笔笔触,留白意境
  1897. 正向提示词(中文)
  1898. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  1899. 必须遵守规则
  1900. • 严格保持水墨质感,不混入厚涂、写实、卡通
  1901. • 色调淡雅统一,不浓艳杂乱
  1902. • 画面干净有意境,不堆砌元素
  1903. 禁止/避免词汇
  1904. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  1905. ],
  1906. '写实插画风格' => [
  1907. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1908. 'prompt' => "风格说明
  1909. 接近真人比例,光影真实,质感细腻
  1910. 正向提示词(中文)
  1911. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  1912. 必须遵守规则
  1913. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  1914. • 角色五官、身材、服饰高度统一
  1915. • 画面清晰、光影自然、不扭曲
  1916. 禁止/避免词汇
  1917. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  1918. ],
  1919. '3D卡通风格' => [
  1920. 'aliases' => ['3D卡通风格', '3D卡通'],
  1921. 'prompt' => "风格说明
  1922. 3D建模质感,柔和渲染,圆润可爱
  1923. 正向提示词(中文)
  1924. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1925. 必须遵守规则
  1926. • 保持3D卡通统一质感,不出现2D杂乱线条
  1927. • 角色模型、比例、形象前后一致
  1928. • 画面干净,不模糊、不穿模
  1929. 禁止/避免词汇
  1930. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1931. ],
  1932. '条漫风格' => [
  1933. 'aliases' => ['条漫风格', '条漫'],
  1934. 'prompt' => "风格说明
  1935. 纵向分镜,上下滑动阅读,轻量化
  1936. 正向提示词(中文)
  1937. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1938. 必须遵守规则
  1939. • 保持条漫纵向阅读逻辑,构图简洁
  1940. • 画风统一,不混写实、3D、水墨
  1941. • 画面干净,不杂乱
  1942. 禁止/避免词汇
  1943. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1944. ],
  1945. '赛博朋克风格' => [
  1946. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1947. 'prompt' => "风格说明
  1948. 霓虹灯光、未来都市、暗色调、科技机械
  1949. 正向提示词(中文)
  1950. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1951. 必须遵守规则
  1952. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1953. • 色调以暗调+霓虹为主,色彩统一
  1954. • 画面科技感强,不杂乱
  1955. 禁止/避免词汇
  1956. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1957. ],
  1958. '暗黑悬疑风格' => [
  1959. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1960. 'prompt' => "风格说明
  1961. 低饱和、冷色调、阴影重、神秘压抑
  1962. 正向提示词(中文)
  1963. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1964. 必须遵守规则
  1965. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1966. • 画面氛围压抑神秘,但不低俗、不血腥
  1967. • 角色形象统一,不崩坏
  1968. 禁止/避免词汇
  1969. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1970. ],
  1971. '治愈清新风格' => [
  1972. 'aliases' => ['治愈清新风格', '治愈清新'],
  1973. 'prompt' => "风格说明
  1974. 马卡龙色系、柔光、温暖干净
  1975. 正向提示词(中文)
  1976. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1977. 必须遵守规则
  1978. • 保持治愈清新统一色调,不阴暗、不诡异
  1979. • 画面柔和干净,无杂乱元素
  1980. • 角色形象柔和可爱,不狰狞
  1981. 禁止/避免词汇
  1982. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1983. ],
  1984. ];
  1985. return $arr;
  1986. }
  1987. public function getArtStylePromptByInput($inputArtStyle): string
  1988. {
  1989. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1990. if ($normalizedInput === '') {
  1991. return '';
  1992. }
  1993. return $this->getArtStylePromptMappings($normalizedInput);
  1994. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1995. // foreach ($mapping['aliases'] as $alias) {
  1996. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1997. // if ($normalizedAlias === '') {
  1998. // continue;
  1999. // }
  2000. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2001. // return $mapping['prompt'];
  2002. // }
  2003. // }
  2004. // }
  2005. return '';
  2006. }
  2007. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2008. $stylePrefixes = [
  2009. '唯美真人风格' => [
  2010. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2011. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2012. ],
  2013. '真人古风风格' => [
  2014. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2015. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2016. ],
  2017. '日系动漫风格' => [
  2018. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2019. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2020. ],
  2021. '国漫风格' => [
  2022. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2023. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2024. ],
  2025. 'Q版卡通风格' => [
  2026. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2027. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2028. ],
  2029. '简约扁平风格' => [
  2030. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2031. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2032. ],
  2033. '武侠风格' => [
  2034. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2035. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2036. ],
  2037. '古风仙侠风格' => [
  2038. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2039. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2040. ],
  2041. '新中式水墨风格' => [
  2042. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2043. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2044. ],
  2045. '写实插画风格' => [
  2046. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2047. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2048. ],
  2049. '3D卡通风格' => [
  2050. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2051. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2052. ],
  2053. '条漫风格' => [
  2054. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2055. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2056. ],
  2057. '赛博朋克风格' => [
  2058. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2059. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2060. ],
  2061. '暗黑悬疑风格' => [
  2062. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2063. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2064. ],
  2065. '治愈清新风格' => [
  2066. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2067. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2068. ]
  2069. ];
  2070. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2071. }
  2072. private function normalizeArtStyleInput($value): string
  2073. {
  2074. $value = trim((string)$value);
  2075. if ($value === '') {
  2076. return '';
  2077. }
  2078. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2079. return mb_strtolower($value, 'UTF-8');
  2080. }
  2081. private function replaceArtStyleSection(string $content, string $artStyle): string
  2082. {
  2083. if ($content === '' || $artStyle === '') {
  2084. return $content;
  2085. }
  2086. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2087. if (!preg_match($pattern, $content)) {
  2088. return $content;
  2089. }
  2090. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2091. }
  2092. /**
  2093. * DeepSeek流式输出处理方法
  2094. *
  2095. * @param array $post_data DeepSeek API请求参数
  2096. * @return \Generator 返回生成器,用于流式输出
  2097. */
  2098. private function unwrapJsonWrappedContent($content) {
  2099. $trimmed = ltrim((string)$content);
  2100. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2101. return $content;
  2102. }
  2103. $decoded = json_decode($trimmed, true);
  2104. if (!is_array($decoded)) {
  2105. return $content;
  2106. }
  2107. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2108. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2109. return $decoded[$key];
  2110. }
  2111. }
  2112. return $content;
  2113. }
  2114. private function deepSeekStreamResponse($post_data) {
  2115. // 设置最大输出tokens
  2116. $post_data['max_tokens'] = 300000;
  2117. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2118. $response = $client->post($this->url, [
  2119. 'json' => $post_data,
  2120. 'headers' => $this->headers,
  2121. 'stream' => true // 启用流式响应
  2122. ]);
  2123. $body = $response->getBody();
  2124. $fullContent = '';
  2125. $fullReasoningContent = '';
  2126. $usage = [];
  2127. $buffer = '';
  2128. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2129. // 逐行读取流式响应
  2130. while (!$body->eof()) {
  2131. $chunk = $body->read(1024); // 每次读取 1KB
  2132. $buffer .= $chunk;
  2133. // 按行分割
  2134. $lines = explode("\n", $buffer);
  2135. // 保留最后一个不完整的行
  2136. $buffer = array_pop($lines);
  2137. foreach ($lines as $line) {
  2138. $line = trim($line);
  2139. // 跳过空行
  2140. if (empty($line)) {
  2141. continue;
  2142. }
  2143. // 检查是否是 SSE 数据行
  2144. if (strpos($line, 'data: ') !== 0) {
  2145. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2146. continue;
  2147. }
  2148. $data = substr($line, 6); // 移除 "data: " 前缀
  2149. if ($data === '[DONE]') {
  2150. dLog('deepseek')->info('收到结束标记');
  2151. break 2; // 跳出两层循环
  2152. }
  2153. try {
  2154. $json = json_decode($data, true);
  2155. if (json_last_error() !== JSON_ERROR_NONE) {
  2156. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2157. continue;
  2158. }
  2159. if (isset($json['choices'][0]['delta'])) {
  2160. $delta = $json['choices'][0]['delta'];
  2161. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2162. if (isset($delta['reasoning_content'])) {
  2163. $fullReasoningContent .= $delta['reasoning_content'];
  2164. yield [
  2165. 'type' => 'reasoning',
  2166. 'content' => $delta['reasoning_content'],
  2167. 'full_reasoning' => $fullReasoningContent
  2168. ];
  2169. }
  2170. // 处理最终回答内容
  2171. if (isset($delta['content'])) {
  2172. $fullContent .= $delta['content'];
  2173. yield [
  2174. 'type' => 'content',
  2175. 'content' => $delta['content'],
  2176. ];
  2177. }
  2178. }
  2179. // 获取使用统计信息
  2180. if (isset($json['usage'])) {
  2181. $usage = $json['usage'];
  2182. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2183. }
  2184. } catch (\Exception $e) {
  2185. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2186. continue;
  2187. }
  2188. }
  2189. }
  2190. dLog('deepseek')->info('流式读取完成', [
  2191. 'content_length' => strlen($fullContent),
  2192. 'reasoning_length' => strlen($fullReasoningContent)
  2193. ]);
  2194. yield [
  2195. 'type' => 'done',
  2196. 'full_content' => $fullContent,
  2197. 'full_reasoning' => $fullReasoningContent,
  2198. 'usage' => $usage
  2199. ];
  2200. }
  2201. /**
  2202. * GPT 重试次数(env 可配置,默认 5 次)
  2203. */
  2204. private function gptRetryTimes()
  2205. {
  2206. return (int)env('GPT_RETRY_TIMES', 5);
  2207. }
  2208. /**
  2209. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2210. */
  2211. private function gptRetryInterval()
  2212. {
  2213. return (int)env('GPT_RETRY_INTERVAL', 10);
  2214. }
  2215. /**
  2216. * 判断 GPT 请求异常是否可重试
  2217. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2218. */
  2219. private function isGptRetryableException(\Exception $e)
  2220. {
  2221. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2222. return false;
  2223. }
  2224. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2225. $status = $e->getResponse()->getStatusCode();
  2226. return $status >= 500 || $status == 429;
  2227. }
  2228. return true;
  2229. }
  2230. /**
  2231. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2232. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2233. */
  2234. private function checkGptServiceAvailable()
  2235. {
  2236. $apiKey = env('GPT_54_API_KEY');
  2237. if (empty($apiKey)) {
  2238. return false;
  2239. }
  2240. try {
  2241. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2242. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2243. 'headers' => [
  2244. 'Authorization' => 'Bearer ' . $apiKey,
  2245. 'Content-Type' => 'application/json'
  2246. ]
  2247. ]);
  2248. $status = $response->getStatusCode();
  2249. return $status < 500 && $status != 429;
  2250. } catch (\Exception $e) {
  2251. return false;
  2252. }
  2253. }
  2254. /**
  2255. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2256. * 全部失败抛出友好错误
  2257. */
  2258. private function ensureGptServiceAvailable()
  2259. {
  2260. $maxRetries = $this->gptRetryTimes();
  2261. $interval = $this->gptRetryInterval();
  2262. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2263. if ($this->checkGptServiceAvailable()) {
  2264. return;
  2265. }
  2266. if ($attempt < $maxRetries) {
  2267. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2268. 'retry' => $attempt + 1,
  2269. 'max_retries' => $maxRetries
  2270. ]);
  2271. sleep($interval);
  2272. }
  2273. }
  2274. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2275. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2276. 'max_retries' => $maxRetries,
  2277. 'interval' => $interval
  2278. ]);
  2279. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2280. }
  2281. /**
  2282. * GPT 流式输出处理方法
  2283. *
  2284. * @param array $post_data GPT API请求参数
  2285. * @return \Generator 返回生成器,用于流式输出
  2286. */
  2287. private function gpt54StreamResponse($post_data) {
  2288. $apiKey = env('GPT_54_API_KEY');
  2289. if (empty($apiKey)) {
  2290. Utils::throwError('20003:GPT API Key未配置');
  2291. }
  2292. // 先探活,服务不可用时自动重试
  2293. $this->ensureGptServiceAvailable();
  2294. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2295. $headers = [
  2296. 'Authorization' => 'Bearer ' . $apiKey,
  2297. 'Content-Type' => 'application/json',
  2298. 'Accept' => 'text/event-stream'
  2299. ];
  2300. // 移除 thinking 参数,GPT-5.4 不支持
  2301. if (isset($post_data['thinking'])) {
  2302. unset($post_data['thinking']);
  2303. }
  2304. if (isset($post_data['reasoning_effort'])) {
  2305. unset($post_data['reasoning_effort']);
  2306. }
  2307. // 中转站不识别 response_format,可能被误转成 JSON 输出模式
  2308. if (isset($post_data['response_format'])) {
  2309. unset($post_data['response_format']);
  2310. }
  2311. $post_data['max_completion_tokens'] = 100000;
  2312. $maxRetries = $this->gptRetryTimes();
  2313. $interval = $this->gptRetryInterval();
  2314. $attempt = 0;
  2315. while (true) {
  2316. $fullContent = '';
  2317. $usage = [];
  2318. $buffer = '';
  2319. $suspectJsonWrap = false;
  2320. $pendingContent = '';
  2321. try {
  2322. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2323. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2324. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2325. 'json' => $post_data,
  2326. 'headers' => $headers,
  2327. 'stream' => true // 启用流式响应
  2328. ]);
  2329. $body = $response->getBody();
  2330. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2331. // 逐行读取流式响应
  2332. while (!$body->eof()) {
  2333. $chunk = $body->read(1024); // 每次读取 1KB
  2334. $buffer .= $chunk;
  2335. // 按行分割
  2336. $lines = explode("\n", $buffer);
  2337. // 保留最后一个不完整的行
  2338. $buffer = array_pop($lines);
  2339. foreach ($lines as $line) {
  2340. $line = trim($line);
  2341. // 跳过空行
  2342. if (empty($line)) {
  2343. continue;
  2344. }
  2345. // 检查是否是 SSE 数据行
  2346. if (strpos($line, 'data: ') !== 0) {
  2347. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2348. continue;
  2349. }
  2350. $data = substr($line, 6); // 移除 "data: " 前缀
  2351. if ($data === '[DONE]') {
  2352. dLog('deepseek')->info('收到结束标记');
  2353. break 2; // 跳出 foreach 和流读取循环
  2354. }
  2355. try {
  2356. $json = json_decode($data, true);
  2357. if (json_last_error() !== JSON_ERROR_NONE) {
  2358. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2359. continue;
  2360. }
  2361. if (isset($json['choices'][0]['delta'])) {
  2362. $delta = $json['choices'][0]['delta'];
  2363. // 处理回答内容
  2364. if (isset($delta['content'])) {
  2365. $fullContent .= $delta['content'];
  2366. $trimmed = ltrim($fullContent);
  2367. if (!$suspectJsonWrap && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2368. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2369. $suspectJsonWrap = true;
  2370. }
  2371. if (!$suspectJsonWrap) {
  2372. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2373. $chunkSize = 256;
  2374. $chunkLength = mb_strlen($delta['content']);
  2375. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2376. yield [
  2377. 'type' => 'content',
  2378. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2379. ];
  2380. }
  2381. } else {
  2382. $pendingContent .= $delta['content'];
  2383. }
  2384. }
  2385. }
  2386. // 获取使用统计信息
  2387. if (isset($json['usage'])) {
  2388. $usage = $json['usage'];
  2389. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2390. }
  2391. } catch (\Exception $e) {
  2392. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2393. continue;
  2394. }
  2395. }
  2396. }
  2397. dLog('deepseek')->info('流式读取完成', [
  2398. 'content_length' => strlen($fullContent)
  2399. ]);
  2400. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  2401. if ($suspectJsonWrap) {
  2402. $decoded = json_decode(trim($fullContent), true);
  2403. $unwrapped = null;
  2404. if (is_array($decoded)) {
  2405. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2406. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2407. $unwrapped = $decoded[$key];
  2408. break;
  2409. }
  2410. }
  2411. }
  2412. if ($unwrapped !== null) {
  2413. $fullContent = $unwrapped;
  2414. $chunkSize = 256;
  2415. $contentLength = mb_strlen($fullContent);
  2416. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  2417. yield [
  2418. 'type' => 'content',
  2419. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  2420. ];
  2421. }
  2422. } elseif ($pendingContent !== '') {
  2423. // 误判:补发暂缓内容,避免内容丢失
  2424. yield [
  2425. 'type' => 'content',
  2426. 'content' => $pendingContent,
  2427. ];
  2428. }
  2429. }
  2430. yield [
  2431. 'type' => 'done',
  2432. 'full_content' => $fullContent,
  2433. 'full_reasoning' => '',
  2434. 'usage' => $usage
  2435. ];
  2436. return;
  2437. } catch (\Exception $e) {
  2438. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2439. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2440. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2441. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2442. throw $e;
  2443. }
  2444. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2445. 'retry' => $attempt + 1,
  2446. 'max_retries' => $maxRetries,
  2447. 'error' => $e->getMessage()
  2448. ]);
  2449. sleep($interval);
  2450. $attempt++;
  2451. }
  2452. }
  2453. }
  2454. // 与推理模型对话
  2455. public function chatWithReasoner($data) {
  2456. $content = getProp($data, 'content');
  2457. $model = getProp($data, 'model', 'r1');
  2458. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2459. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2460. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2461. if ($model == 'r1') {
  2462. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2463. $thinkingMode = 'disabled';
  2464. } else {
  2465. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2466. $thinkingMode = 'disabled';
  2467. }
  2468. // 获取可选情感(根据音色可支持情感选)
  2469. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2470. $emotion_list = [];
  2471. foreach ($timbre_emotion as $emotion) {
  2472. $tmp = explode(',', $emotion);
  2473. $emotion_list = array_merge($emotion_list, $tmp);
  2474. }
  2475. $emotion_list = array_unique($emotion_list);
  2476. $emotion_str = implode('、', $emotion_list);
  2477. // // 获取可选情感
  2478. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2479. // $emotion_str = implode('、', $emotion_list);
  2480. // 是否启用情感
  2481. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2482. if ($enable_emotion) {
  2483. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2484. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2485. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2486. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2487. }else {
  2488. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2489. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2490. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2491. }
  2492. $messages = [
  2493. [
  2494. 'role' => 'system',
  2495. 'content' => $sys_content
  2496. ],
  2497. [
  2498. 'role' => 'user',
  2499. 'content' => $content
  2500. ]
  2501. ];
  2502. $post_data = [
  2503. 'model' => $model,
  2504. 'messages' => $messages,
  2505. // 'max_tokens' => 8192,
  2506. 'temperature' => 1,
  2507. 'frequency_penalty' => 0,
  2508. 'presence_penalty' => 0,
  2509. 'thinking' => ['type' => $thinkingMode],
  2510. 'response_format' => [
  2511. 'type' => 'text'
  2512. ],
  2513. 'stream' => false
  2514. ];
  2515. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2516. // 根据模型类型选择调用方法
  2517. $fullContent = '';
  2518. $usage = [];
  2519. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2520. // DeepSeek 官方模型使用 DeepSeek API
  2521. $chatResult = $this->chatOnly($post_data);
  2522. } else if (in_array($model, $this->gpt_text_models)) {
  2523. // GPT-5.4 模型使用 TokenRouter API
  2524. $chatResult = $this->gpt54ChatOnly($post_data);
  2525. } else {
  2526. // 其他模型使用火山引擎API
  2527. $chatResult = $this->volcEngineChatCompletion($post_data);
  2528. }
  2529. if (is_array($chatResult)) {
  2530. $fullContent = $chatResult['fullContent'];
  2531. $usage = $chatResult['usage'];
  2532. }
  2533. // 处理获取到的剧本数据
  2534. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2535. $result = [
  2536. 'origin_content' => $fullContent,
  2537. 'roles' => getProp($script_content, 'roles'),
  2538. 'words' => getProp($script_content, 'words'),
  2539. ];
  2540. return $result;
  2541. }
  2542. public function resetParagraphAudio($data) {
  2543. $bid = getProp($data, 'bid');
  2544. $cid = getProp($data, 'cid');
  2545. $version_id = getProp($data, 'version_id');
  2546. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2547. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2548. 'generate_status' => '待制作',
  2549. 'updated_at' => date('Y-m-d H:i:s')
  2550. ]);
  2551. }
  2552. public function saveParagraphAudio($data) {
  2553. $bid = getProp($data, 'bid');
  2554. $cid = getProp($data, 'cid');
  2555. $version_id = getProp($data, 'version_id');
  2556. $sequence = getProp($data, 'sequence');
  2557. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2558. // 获取所有情感
  2559. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2560. $emotion_list = array_flip($emotion_list);
  2561. // 获取音色支持情感
  2562. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2563. $timbre_emotion = explode(',', $timbre_emotion);
  2564. $emotion = getProp($data, 'emotion');
  2565. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2566. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2567. $list = [
  2568. 'bid' => $bid,
  2569. 'cid' => $cid,
  2570. 'version_id' => $version_id,
  2571. 'sequence' => $sequence,
  2572. 'role' => getProp($data, 'role'),
  2573. 'gender' => getProp($data, 'gender'),
  2574. 'text' => trim(getProp($data, 'text')),
  2575. 'emotion' => $emotion,
  2576. 'emotion_type' => $emotion_type,
  2577. 'voice_type' => getProp($data, 'voice_type'),
  2578. 'voice_name' => getProp($data, 'voice_name'),
  2579. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2580. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2581. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2582. 'pitch' => getProp($data, 'pitch', 0),
  2583. // 'paragraph_audio_url' => '',
  2584. 'generate_status' => '制作中',
  2585. 'error_msg' => '',
  2586. 'updated_at' => date('Y-m-d H:i:s')
  2587. ];
  2588. $continue = false;
  2589. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2590. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2591. $list['generate_status'] = '制作成功';
  2592. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2593. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2594. $continue = true;
  2595. }
  2596. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2597. if ($id) {
  2598. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2599. }else {
  2600. $list['created_at'] = date('Y-m-d H:i:s');
  2601. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2602. $boolen = $id ? true : false;
  2603. }
  2604. // 如果更新成功则加入查询队列
  2605. if ($boolen) {
  2606. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2607. Redis::sadd($redis_key, $id);
  2608. }
  2609. if ($boolen && !$continue) {
  2610. $boolen = false;
  2611. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2612. // 根据ID通过API通知合成音频
  2613. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2614. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2615. $response = $result->getBody()->getContents();
  2616. $response_arr = json_decode($response, true);
  2617. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2618. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2619. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2620. Utils::throwError('20003:通知火山生成段落音频失败');
  2621. }
  2622. $boolen = true;
  2623. }
  2624. return $boolen;
  2625. }
  2626. public function insertAudioEffect($data) {
  2627. $audio_id = getProp($data, 'audio_id');
  2628. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2629. $bid = getProp($chapter_audio, 'bid');
  2630. $version_id = getProp($chapter_audio, 'version_id');
  2631. $cid = getProp($chapter_audio, 'cid');
  2632. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2633. $audio_effect_json = getProp($data, 'audio_effect_json');
  2634. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2635. try {
  2636. DB::beginTransaction();
  2637. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2638. if (!$count) {
  2639. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2640. }else {
  2641. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2642. }
  2643. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2644. 'audio_effect_status' => '添加中',
  2645. 'audio_effect_json' => $audio_effect_json,
  2646. 'updated_at' => date('Y-m-d H:i:s')
  2647. ]);
  2648. if (!$boolen1) {
  2649. DB::rollBack();
  2650. Utils::throwError('20003:更新生成数据失败');
  2651. }
  2652. $id = DB::table('mp_audio_tasks')->insertGetId([
  2653. 'audio_id' => $audio_id,
  2654. 'generate_status' => '执行中',
  2655. 'generate_json' => json_encode([], 256),
  2656. 'bid' => $bid,
  2657. 'book_name' => getProp($chapter_audio, 'book_name'),
  2658. 'version_id' => $version_id,
  2659. 'version_name' => getProp($chapter_audio, 'version_name'),
  2660. 'cid' => $cid,
  2661. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2662. 'task_name' => $task_name,
  2663. 'created_at' => date('Y-m-d H:i:s'),
  2664. 'updated_at' => date('Y-m-d H:i:s')
  2665. ]);
  2666. if (!$id) {
  2667. DB::rollBack();
  2668. Utils::throwError('20003:创建任务失败');
  2669. }
  2670. }catch (\Exception $e) {
  2671. DB::rollBack();
  2672. Utils::throwError('20003:'.$e->getMessage());
  2673. }
  2674. DB::commit();
  2675. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2676. // 根据ID通过API通知合成音频
  2677. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2678. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2679. $response = $result->getBody()->getContents();
  2680. $response_arr = json_decode($response, true);
  2681. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2682. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2683. Log::info('通知火山插入音效失败: '.$error_msg);
  2684. Utils::throwError('20003:通知火山插入音效失败');
  2685. }
  2686. return true;
  2687. }
  2688. public function insertBgm($data) {
  2689. $audio_id = getProp($data, 'audio_id');
  2690. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2691. $bid = getProp($chapter_audio, 'bid');
  2692. $version_id = getProp($chapter_audio, 'version_id');
  2693. $cid = getProp($chapter_audio, 'cid');
  2694. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2695. $bgm_json = getProp($data, 'bgm_json');
  2696. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2697. if (!$bgm_json) {
  2698. $bgm_json = getProp($data, 'audio_effect_json');
  2699. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2700. }
  2701. try {
  2702. DB::beginTransaction();
  2703. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2704. if (!$count) {
  2705. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2706. }else {
  2707. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2708. }
  2709. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2710. 'bgm_status' => '添加中',
  2711. 'bgm_json' => $bgm_json,
  2712. 'updated_at' => date('Y-m-d H:i:s')
  2713. ]);
  2714. if (!$boolen1) {
  2715. DB::rollBack();
  2716. Utils::throwError('20003:更新生成数据失败');
  2717. }
  2718. $id = DB::table('mp_audio_tasks')->insertGetId([
  2719. 'audio_id' => $audio_id,
  2720. 'generate_status' => '执行中',
  2721. 'generate_json' => json_encode([], 256),
  2722. 'bid' => $bid,
  2723. 'book_name' => getProp($chapter_audio, 'book_name'),
  2724. 'version_id' => $version_id,
  2725. 'version_name' => getProp($chapter_audio, 'version_name'),
  2726. 'cid' => $cid,
  2727. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2728. 'task_name' => $task_name,
  2729. 'created_at' => date('Y-m-d H:i:s'),
  2730. 'updated_at' => date('Y-m-d H:i:s')
  2731. ]);
  2732. if (!$id) {
  2733. DB::rollBack();
  2734. Utils::throwError('20003:创建任务失败');
  2735. }
  2736. }catch (\Exception $e) {
  2737. DB::rollBack();
  2738. Utils::throwError('20003:'.$e->getMessage());
  2739. }
  2740. DB::commit();
  2741. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2742. // 根据ID通过API通知合成音频
  2743. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2744. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2745. $response = $result->getBody()->getContents();
  2746. $response_arr = json_decode($response, true);
  2747. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2748. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2749. Log::info('通知火山插入bgm失败: '.$error_msg);
  2750. Utils::throwError('20003:通知火山插入bgm失败');
  2751. }
  2752. return true;
  2753. }
  2754. public function getParagraphAudios($data) {
  2755. $bid = getProp($data, 'bid');
  2756. $cid = getProp($data, 'cid');
  2757. $version_id = getProp($data, 'version_id');
  2758. $sequence = getProp($data, 'sequence');
  2759. // 获取已生成的音频
  2760. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2761. if ($sequence) $query->where('sequence', $sequence);
  2762. $paragraph_audios = $query->orderBy('sequence')->get();
  2763. $result = [];
  2764. foreach($paragraph_audios as $item) {
  2765. $result[] = [
  2766. 'sequence' => getProp($item, 'sequence'),
  2767. 'role' => getProp($item, 'role'),
  2768. 'gender' => getProp($item, 'gender'),
  2769. 'text' => trim(getProp($item, 'text')),
  2770. 'emotion' => getProp($item, 'emotion'),
  2771. 'emotion_type' => getProp($item, 'emotion_type'),
  2772. 'voice_type' => getProp($item, 'voice_type'),
  2773. 'voice_name' => getProp($item, 'voice_name'),
  2774. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2775. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2776. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2777. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2778. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  2779. ];
  2780. }
  2781. return $result;
  2782. }
  2783. // 新增合成任务
  2784. public function addGenerateTask($data) {
  2785. $bid = getProp($data, 'bid');
  2786. $cid = getProp($data, 'cid');
  2787. $version_id = getProp($data, 'version_id');
  2788. $generate_json = getProp($data, 'generate_json');
  2789. // 获取已生成的音频
  2790. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  2791. $paragraph_list = [];
  2792. foreach($paragraph_audios as $item) {
  2793. $paragraph_list[getProp($item, 'sequence')] = [
  2794. 'role' => getProp($item, 'role'),
  2795. 'gender' => getProp($item, 'gender'),
  2796. 'text' => trim(getProp($item, 'text')),
  2797. 'emotion' => getProp($item, 'emotion'),
  2798. 'emotion_type' => getProp($item, 'emotion_type'),
  2799. 'voice_type' => getProp($item, 'voice_type'),
  2800. 'voice_name' => getProp($item, 'voice_name'),
  2801. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2802. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2803. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2804. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2805. ];
  2806. }
  2807. // 更新角色-音色信息
  2808. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  2809. $existed_role_info = json_decode($existed_role_info, true);
  2810. if (!$existed_role_info) $existed_role_info = [];
  2811. // 获取情感信息
  2812. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2813. $emotion_list = array_flip($emotion_list);
  2814. // 获取音色对应情感组
  2815. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  2816. $timbre_emotion_list = [];
  2817. foreach($timbre_emotions as $item) {
  2818. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  2819. }
  2820. // 构造生成音频的json
  2821. $words = json_decode($generate_json, true);
  2822. // 最终合成前的参数组
  2823. $mp_chapter_paragraph_audios = [];
  2824. $sequence = 1;
  2825. $complete_paragraph_sequences = [];
  2826. foreach($words as &$word) {
  2827. 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:参数格式有误');
  2828. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  2829. $role = getProp($word, 'role');
  2830. $word['gender'] = (int)$word['gender'];
  2831. // 判断音色对应情感是否支持,不支持则调整为中性
  2832. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  2833. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  2834. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  2835. if (isset($emotion_list[getProp($word, 'emotion')])) {
  2836. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  2837. }else {
  2838. $word['emotion'] = '中性';
  2839. $word['emotion_type'] = 'neutral';
  2840. }
  2841. $existed_role_info[$role] = [
  2842. 'timbre_type' => $word['voice_type'],
  2843. 'timbre_name' => $word['voice_name'],
  2844. 'emotion' => $word['emotion'],
  2845. 'emotion_type' => $word['emotion_type'],
  2846. 'speed_ratio' => $word['speed_ratio'],
  2847. 'loudness_ratio'=> $word['loudness_ratio'],
  2848. 'emotion_scale' => $word['emotion_scale'],
  2849. 'pitch' => $word['pitch']
  2850. ];
  2851. $word['paragraph_audio_url'] = '';
  2852. // 判断生成参数是否相同,相同则直接使用已生成的音频
  2853. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  2854. // 如果音频存在并且参数都未改变则使用已生成的音频
  2855. if (getProp($paragraph, 'paragraph_audio_url')) {
  2856. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  2857. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  2858. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  2859. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  2860. // {
  2861. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2862. // }
  2863. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2864. }
  2865. $tmp = $word;
  2866. // 组装章节分句音频数据
  2867. // $tmp['sequence'] = getProp($word, 'sequence');
  2868. // $tmp['text'] = getProp($word, 'text');
  2869. // $tmp['emotion'] = getProp($word, 'emotion');
  2870. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  2871. // $tmp['voice_name'] = getProp($word, 'voice_name');
  2872. // $tmp['voice_type'] = getProp($word, 'voice_type');
  2873. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  2874. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  2875. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  2876. $tmp['bid'] = $bid;
  2877. $tmp['version_id'] = $version_id;
  2878. $tmp['cid'] = $cid;
  2879. $tmp['sequence'] = $sequence;
  2880. $tmp['created_at'] = date('Y-m-d H:i:s');
  2881. $tmp['updated_at'] = date('Y-m-d H:i:s');
  2882. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  2883. $mp_chapter_paragraph_audios[] = $tmp;
  2884. $complete_paragraph_sequences[] = $sequence;
  2885. $sequence++;
  2886. }
  2887. $generate_json = json_encode($words, 256);
  2888. // 判断是否有未生成字幕的段落
  2889. $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();
  2890. if ($no_subtitle_sequences) {
  2891. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  2892. }
  2893. try {
  2894. DB::beginTransaction();
  2895. $role_info = json_encode($existed_role_info, 256);
  2896. $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')]);
  2897. if (!$boolen) {
  2898. DB::rollBack();
  2899. Utils::throwError('20003:更新角色信息失败');
  2900. }
  2901. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  2902. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  2903. if (!$count) {
  2904. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2905. }else {
  2906. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2907. }
  2908. $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')]);
  2909. if (!$boolen1) {
  2910. DB::rollBack();
  2911. Utils::throwError('20003:更新生成数据失败');
  2912. }
  2913. $id = DB::table('mp_audio_tasks')->insertGetId([
  2914. 'audio_id' => getProp($chapter_audio, 'id'),
  2915. 'generate_status' => '执行中',
  2916. 'generate_json' => $generate_json,
  2917. 'bid' => $bid,
  2918. 'book_name' => getProp($chapter_audio, 'book_name'),
  2919. 'version_id' => $version_id,
  2920. 'version_name' => getProp($chapter_audio, 'version_name'),
  2921. 'cid' => $cid,
  2922. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2923. 'task_name' => $task_name,
  2924. 'created_at' => date('Y-m-d H:i:s'),
  2925. 'updated_at' => date('Y-m-d H:i:s')
  2926. ]);
  2927. if (!$id) {
  2928. DB::rollBack();
  2929. Utils::throwError('20003:创建任务失败');
  2930. }
  2931. // 删除不在段落序号范围内的其他数据
  2932. if ($complete_paragraph_sequences) {
  2933. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  2934. }
  2935. // // 删除章节分句音频数据并重新插入
  2936. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  2937. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  2938. // if (!$boolen3) {
  2939. // DB::rollBack();
  2940. // Utils::throwError('20003:更新章节分句音频失败');
  2941. // }
  2942. } catch (\Exception $e) {
  2943. DB::rollBack();
  2944. Utils::throwError('20003:'.$e->getMessage());
  2945. }
  2946. DB::commit();
  2947. // 通知火山生成音频
  2948. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2949. // 根据ID通过API通知合成音频
  2950. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  2951. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  2952. $response = $result->getBody()->getContents();
  2953. $response_arr = json_decode($response, true);
  2954. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2955. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2956. Log::info('通知火山生成音频失败: '.$error_msg);
  2957. Utils::throwError('20003:通知火山生成音频失败');
  2958. }
  2959. return true;
  2960. }
  2961. public function timbreList($data) {
  2962. $gender = getProp($data, 'gender');
  2963. $timbre_name = getProp($data, 'voice_name');
  2964. $category_id = getProp($data, 'category_id');
  2965. $age_stage = getProp($data, 'age_stage');
  2966. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'age_stage', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  2967. if ($gender) {
  2968. $query->where('gender', $gender);
  2969. }
  2970. if ($timbre_name) {
  2971. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  2972. }
  2973. if ($category_id) {
  2974. $query->where(function ($query) use ($category_id) {
  2975. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  2976. });
  2977. }
  2978. if ($age_stage) {
  2979. $query->where('age_stage', $age_stage);
  2980. }
  2981. $list = $query->get()->map(function ($value) {
  2982. $value = (array)$value;
  2983. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2984. return $value;
  2985. })->toArray();
  2986. return $list;
  2987. }
  2988. // 生成火山临时token
  2989. public function setStsToken() {
  2990. // ************* 配置参数 *************
  2991. $method = 'GET';
  2992. $service = 'sts';
  2993. $host = 'open.volcengineapi.com';
  2994. $region = env('VOLC_REGION');
  2995. $endpoint = 'https://open.volcengineapi.com';
  2996. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2997. $access_key = env('VOLC_AK');
  2998. $secret_key = env('VOLC_SK');
  2999. // 获取缓存中的token,如果没有则请求接口
  3000. $token = Redis::get('volc_sts_token');
  3001. if (!$token) {
  3002. // 查询参数
  3003. $query_parameters = [
  3004. 'Action' => 'AssumeRole',
  3005. 'RoleSessionName' => 'user@zw',
  3006. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3007. 'Version' => '2018-01-01'
  3008. ];
  3009. // 生成URL编码的查询字符串
  3010. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3011. // 获取签名头信息
  3012. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3013. // 构建完整URL
  3014. $request_url = $endpoint . '?' . $request_parameters;
  3015. $client = new Client(['verify' => false]);
  3016. $response = $client->get($request_url, ['headers' => $headers]);
  3017. $response_arr = json_decode($response->getBody()->getContents(), true);
  3018. $result = [
  3019. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3020. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3021. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3022. 'Region' => env('VOLC_REGION'),
  3023. 'Endpoint' => env('VOLC_END_POINT'),
  3024. 'Bucket' => env('VOLC_BUCKET'),
  3025. ];
  3026. // 缓存token
  3027. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3028. return $result;
  3029. } else {
  3030. return json_decode($token, true);
  3031. }
  3032. // $response = $response['Response'];
  3033. // $access_key = $response['Credentials']['AccessKeyId'];
  3034. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3035. // $security_token = $response['Credentials']['SecurityToken'];
  3036. // $expiration = $response['Credentials']['Expiration'];
  3037. // dd($response_arr);
  3038. }
  3039. public function emotionGroups($data) {
  3040. $id = getProp($data, 'group_id');
  3041. $group_name = getProp($data, 'group_name');
  3042. $voice_type = getProp($data, 'voice_type');
  3043. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3044. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3045. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3046. if ($group_name) {
  3047. $query->where('group_name', 'like', "%{$group_name}%");
  3048. }
  3049. if ($id) {
  3050. $query->where('id', $id);
  3051. }
  3052. if ($voice_type) {
  3053. $query->where('voice_type', $voice_type);
  3054. }
  3055. return $query->orderBy('id')->get()->map(function ($value) {
  3056. return (array)$value;
  3057. })->toArray();
  3058. }
  3059. private function sign($key, $msg) {
  3060. return hash_hmac('sha256', $msg, $key, true);
  3061. }
  3062. // 生成签名密钥
  3063. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3064. $kDate = $this->sign($key, $dateStamp);
  3065. $kRegion = $this->sign($kDate, $regionName);
  3066. $kService = $this->sign($kRegion, $serviceName);
  3067. $kSigning = $this->sign($kService, 'request');
  3068. return $kSigning;
  3069. }
  3070. // 获取签名头信息
  3071. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3072. $contenttype = 'application/x-www-form-urlencoded';
  3073. $accept = 'application/json';
  3074. // 获取当前UTC时间
  3075. $t = new DateTime('now', new DateTimeZone('UTC'));
  3076. $xdate = $t->format('Ymd\THis\Z');
  3077. $datestamp = $t->format('Ymd');
  3078. // 1. 拼接规范请求串
  3079. $canonical_uri = '/';
  3080. $canonical_querystring = $request_parameters;
  3081. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3082. $signed_headers = 'content-type;host;x-date';
  3083. // 空请求体的SHA256哈希
  3084. $payload_hash = hash('sha256', '');
  3085. $canonical_request = implode("\n", [
  3086. $method,
  3087. $canonical_uri,
  3088. $canonical_querystring,
  3089. $canonical_headers,
  3090. $signed_headers,
  3091. $payload_hash
  3092. ]);
  3093. // 2. 拼接待签名字符串
  3094. $algorithm = 'HMAC-SHA256';
  3095. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3096. $hashed_canonical_request = hash('sha256', $canonical_request);
  3097. $string_to_sign = implode("\n", [
  3098. $algorithm,
  3099. $xdate,
  3100. $credential_scope,
  3101. $hashed_canonical_request
  3102. ]);
  3103. // 3. 计算签名
  3104. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3105. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3106. // 4. 添加签名到请求头
  3107. $authorization_header = sprintf(
  3108. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3109. $algorithm,
  3110. $access_key,
  3111. $credential_scope,
  3112. $signed_headers,
  3113. $signature
  3114. );
  3115. return [
  3116. 'Accept' => $accept,
  3117. 'Content-Type' => $contenttype,
  3118. 'X-Date' => $xdate,
  3119. 'Authorization' => $authorization_header
  3120. ];
  3121. }
  3122. // 文字合成语音(火山引擎)
  3123. public function tts($data) {
  3124. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3125. $headers = [
  3126. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3127. 'Content-Type' => 'application/json; charset=UTF-8'
  3128. ];
  3129. $post_data = [
  3130. 'app' => [
  3131. 'appid' => env('VOLC_APPID'),
  3132. 'token' => env('VOLC_TOKEN'),
  3133. 'cluster' => 'volcano_tts'
  3134. ],
  3135. 'user' => [
  3136. 'uid' => 'mp_audio'
  3137. ],
  3138. // 'audio' => [
  3139. // 'voice_type' =>
  3140. // ],
  3141. ];
  3142. }
  3143. public function scriptList($data) {
  3144. $uid = Site::getUid();
  3145. $script_id = getProp($data, 'script_id');
  3146. $script_name = getProp($data, 'script_name');
  3147. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3148. if ($script_id) {
  3149. $query->where('id', $script_id);
  3150. }
  3151. if ($script_name) {
  3152. $query->where('script_name', 'like', "%{$script_name}%");
  3153. }
  3154. return $query->orderBy('created_at', 'desc')->paginate(12);
  3155. }
  3156. public function scripts($data) {
  3157. $uid = Site::getUid();
  3158. $script_id = getProp($data, 'script_id');
  3159. $script_name = getProp($data, 'script_name');
  3160. $is_products = getProp($data, 'is_products');
  3161. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3162. if ($script_id) {
  3163. $query->where('id', $script_id);
  3164. }
  3165. if ($is_products !== '') {
  3166. $query->where('is_products', $is_products);
  3167. }
  3168. if ($script_name) {
  3169. $query->where('script_name', 'like', "%{$script_name}%");
  3170. }
  3171. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3172. return (array)$value;
  3173. })->toArray();
  3174. }
  3175. public function scriptInfo($data) {
  3176. $uid = Site::getUid();
  3177. $script_id = getProp($data, 'script_id');
  3178. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3179. // ->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();
  3180. ->selectRaw('id as script_id, script_name')->first();
  3181. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3182. $script = (array)$script;
  3183. // 获取分集组信息
  3184. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3185. ->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')
  3186. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3187. $value = (array)$value;
  3188. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3189. return (array)$value;
  3190. })->toArray();
  3191. $script['group'] = $groups;
  3192. return $script;
  3193. }
  3194. public function createScript($data) {
  3195. $script_name = getProp($data, 'script_name');
  3196. $uid = Site::getUid(); // 获取当前用户ID
  3197. $cpid = Site::getCpid(); // 获取当前公司组ID
  3198. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3199. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3200. $script_name .= '_'.date('YmdHis');
  3201. }
  3202. return DB::table('mp_scripts')->insertGetId([
  3203. 'script_name' => $script_name,
  3204. 'user_id' => $uid,
  3205. 'cpid' => $cpid,
  3206. 'created_at' => date('Y-m-d H:i:s'),
  3207. 'updated_at' => date('Y-m-d H:i:s')
  3208. ]);
  3209. }
  3210. public function editScript($data) {
  3211. $script_id = getProp($data, 'script_id');
  3212. $script_name = getProp($data, 'script_name');
  3213. $uid = Site::getUid(); // 获取当前用户ID
  3214. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3215. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3216. if ($id && (int)$id !== (int)$script_id) {
  3217. $script_name .= '_'.date('YmdHis');
  3218. }
  3219. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3220. 'script_name' => $script_name,
  3221. 'updated_at' => date('Y-m-d H:i:s')
  3222. ]);
  3223. }
  3224. public function delScript($data) {
  3225. $script_id = getProp($data, 'script_id');
  3226. $uid = Site::getUid(); // 获取当前用户ID
  3227. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3228. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3229. 'is_deleted' => 1,
  3230. 'updated_at' => date('Y-m-d H:i:s')
  3231. ]);
  3232. }
  3233. public function createEpisode($data) {
  3234. $script_id = getProp($data, 'script_id');
  3235. $group_name = getProp($data, 'group_name');
  3236. $remark = getProp($data, 'remark');
  3237. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3238. $uid = Site::getUid(); // 获取当前用户ID
  3239. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3240. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3241. $group_name .= '_'.date('YmdHis');
  3242. }
  3243. return DB::table('mp_script_episode_group')->insertGetId([
  3244. 'script_id' => $script_id,
  3245. 'group_name' => $group_name,
  3246. 'user_id' => $uid,
  3247. 'remark' => $remark,
  3248. 'created_at' => date('Y-m-d H:i:s'),
  3249. 'updated_at' => date('Y-m-d H:i:s')
  3250. ]);
  3251. }
  3252. public function editEpisode($data) {
  3253. $group_id = getProp($data, 'group_id');
  3254. $start_episode_number = getProp($data, 'start_episode_number');
  3255. $end_episode_number = getProp($data, 'end_episode_number');
  3256. $group_name = getProp($data, 'group_name');
  3257. $uid = Site::getUid(); // 获取当前用户ID
  3258. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3259. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3260. if ($id && (int)$id !== (int)$group_id) {
  3261. $group_name .= '_'.date('YmdHis');
  3262. }
  3263. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3264. 'group_name' => $group_name,
  3265. 'start_episode_number' => $start_episode_number,
  3266. 'end_episode_number' => $end_episode_number,
  3267. 'updated_at' => date('Y-m-d H:i:s')
  3268. ]);
  3269. }
  3270. public function delEpisode($data) {
  3271. $group_id = getProp($data, 'group_id');
  3272. $uid = Site::getUid(); // 获取当前用户ID
  3273. if (!$group_id) Utils::throwError('20003:请选择分集');
  3274. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3275. 'is_deleted' => 1,
  3276. 'updated_at' => date('Y-m-d H:i:s')
  3277. ]);
  3278. }
  3279. /**
  3280. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3281. *
  3282. * @param array $data 包含以下参数:
  3283. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3284. * - question: 用户问题(可选)
  3285. * - model: 使用的模型(r1 或 v3,默认 v3)
  3286. * @return \Generator 返回生成器,用于流式输出
  3287. */
  3288. public function generateEpisodes($data) {
  3289. $script_id = getProp($data, 'script_id');
  3290. $group_id = getProp($data, 'group_id');
  3291. // $file = getProp($data, 'file');
  3292. $file = '';
  3293. $content = getProp($data, 'content', '');
  3294. // $bid = getProp($data, 'bid', 0);
  3295. $bid = 0;
  3296. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3297. if (!$group) {
  3298. Utils::throwError('20003:剧本分集不存在');
  3299. }
  3300. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3301. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3302. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3303. $prompt = getProp($data, 'prompt');
  3304. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3305. $model = getProp($data, 'model');
  3306. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3307. Utils::throwError('20003:该模型不存在!');
  3308. }
  3309. // 检查是否存在重叠的剧集序号范围
  3310. $exists_groups = DB::table('mp_script_episode_group')
  3311. ->where('script_id', $script_id)
  3312. ->where('id', '<>', $group_id) // 排除当前组
  3313. ->where('is_deleted', 0)
  3314. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3315. // 检查新范围是否与现有范围重叠
  3316. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3317. // 新范围的开始在现有范围内
  3318. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3319. ->where('end_episode_number', '>=', $start_episode_sequence);
  3320. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3321. // 新范围的结束在现有范围内
  3322. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3323. ->where('end_episode_number', '>=', $end_episode_sequence);
  3324. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3325. // 新范围完全包含现有范围
  3326. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3327. ->where('end_episode_number', '<=', $end_episode_sequence);
  3328. });
  3329. })
  3330. ->select('start_episode_number', 'end_episode_number')
  3331. ->get();
  3332. if ($exists_groups->isNotEmpty()) {
  3333. $conflict_ranges = [];
  3334. foreach ($exists_groups as $group) {
  3335. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3336. }
  3337. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3338. }
  3339. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3340. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3341. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3342. if ($model === 'deepseek-chat') {
  3343. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3344. $model = 'deepseek-v4-flash';
  3345. $thinkingMode = 'disabled';
  3346. } elseif ($model === 'deepseek-reasoner') {
  3347. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3348. $model = 'deepseek-v4-flash';
  3349. $thinkingMode = 'enabled';
  3350. }
  3351. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3352. if (!$script) {
  3353. Utils::throwError('20003:剧本不存在');
  3354. }
  3355. $content = getProp($group, 'content');
  3356. if (!$file && !$content && !$bid) {
  3357. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3358. }
  3359. // 提取文件内容
  3360. if ($file) {
  3361. $content = $this->extractFileContent($file);
  3362. if (!$content) {
  3363. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3364. }
  3365. } elseif ($bid) {
  3366. $content = $this->getContentByBid($bid);
  3367. if (!$content) {
  3368. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3369. }
  3370. } elseif ($content) {
  3371. $content = filterContent($content);
  3372. } elseif ($prompt) {
  3373. $content = filterContent($prompt);
  3374. } else {
  3375. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3376. }
  3377. // 构建消息
  3378. $messages = [
  3379. $this->sys_message,
  3380. [
  3381. 'role' => 'user',
  3382. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3383. ]
  3384. ];
  3385. $post_data = [
  3386. 'model' => $model,
  3387. 'messages' => $messages,
  3388. // 'max_tokens' => 8192,
  3389. 'temperature' => 0.7,
  3390. 'frequency_penalty' => 0,
  3391. 'presence_penalty' => 0,
  3392. 'thinking' => ['type' => $thinkingMode],
  3393. 'response_format' => ['type' => 'text'],
  3394. 'stream' => true
  3395. ];
  3396. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3397. // 根据模型类型选择调用方法
  3398. $fullContent = '';
  3399. $fullReasoningContent = '';
  3400. $usage = [];
  3401. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3402. // DeepSeek 官方模型使用 DeepSeek API
  3403. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3404. } else if (in_array($model, $this->gpt_text_models)) {
  3405. // GPT-5.4 模型使用 TokenRouter API
  3406. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3407. } else if (in_array($model, $this->gemini_text_models)) {
  3408. // Gemini 模型使用 Gemini API
  3409. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3410. } else {
  3411. // 其他模型使用火山引擎API
  3412. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3413. }
  3414. // 处理流式输出
  3415. foreach ($streamGenerator as $chunk) {
  3416. if (isset($chunk['type'])) {
  3417. if ($chunk['type'] === 'done') {
  3418. // 最终结果
  3419. $fullContent = $chunk['full_content'];
  3420. $fullReasoningContent = $chunk['full_reasoning'];
  3421. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3422. } else {
  3423. // 逐块yield数据
  3424. yield $chunk;
  3425. }
  3426. }
  3427. }
  3428. dLog('deepseek')->info('完整内容: '.$fullContent);
  3429. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3430. // 处理完整内容并返回最终结果
  3431. $script_arr = [];
  3432. if ($fullContent) {
  3433. $script_arr = extractScriptContent($fullContent);
  3434. }
  3435. logDB('deepseek', 'info', '解析内容', $script_arr);
  3436. if (!$script_arr['episodes']) {
  3437. Utils::throwError('20003:未生成剧本相关信息');
  3438. // yield [
  3439. // 'type' => 'done',
  3440. // 'script' => $script_arr,
  3441. // 'msg' => '未生成剧本相关信息',
  3442. // 'answer' => $fullContent,
  3443. // 'reasoning' => $fullReasoningContent,
  3444. // 'usage' => $usage
  3445. // ];
  3446. // return ;
  3447. }
  3448. try {
  3449. DB::beginTransaction();
  3450. // // 返回前保存剧本内容
  3451. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3452. // 'content' => $content,
  3453. // 'updated_at' => date('Y-m-d H:i:s')
  3454. // ]);
  3455. // if (!$boolen) {
  3456. // Utils::throwError('20003:保存剧本内容失败');
  3457. // }
  3458. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3459. // 'start_episode_number' => $start_episode_sequence,
  3460. // 'end_episode_number' => $end_episode_sequence,
  3461. // 'updated_at' => date('Y-m-d H:i:s')
  3462. // ]);
  3463. // if (!$boolen1) {
  3464. // Utils::throwError('20003:保存分集失败');
  3465. // }
  3466. $episode_content = '';
  3467. $episodes = [];
  3468. foreach ($script_arr['episodes'] as $item) {
  3469. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3470. // $episodes[] = [
  3471. // 'script_id' => $script_id,
  3472. // 'episode_number' => $item['episode_number'],
  3473. // 'episode_name' => $item['episode_name'],
  3474. // 'episode_content' => $item['episode_content'],
  3475. // 'created_at' => date('Y-m-d H:i:s'),
  3476. // 'updated_at' => date('Y-m-d H:i:s'),
  3477. // ];
  3478. }
  3479. if ($episode_content) {
  3480. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3481. 'episode_content' => $episode_content,
  3482. 'updated_at' => date('Y-m-d H:i:s')
  3483. ]);
  3484. if (!$boolen2) {
  3485. Utils::throwError('20003:保存分集内容失败');
  3486. }
  3487. }else {
  3488. Utils::throwError('20003:分集剧本解析失败');
  3489. }
  3490. }catch (\Exception $e) {
  3491. DB::rollBack();
  3492. Utils::throwError('20003:'.$e->getMessage());
  3493. }
  3494. DB::commit();
  3495. yield [
  3496. 'type' => 'done',
  3497. 'script' => $script_arr,
  3498. 'episode_content' => $episode_content,
  3499. 'answer' => $fullContent,
  3500. 'reasoning' => $fullReasoningContent,
  3501. 'usage' => $usage
  3502. ];
  3503. }
  3504. public function chatWithFileStream($data) {
  3505. $script_id = getProp($data, 'script_id');
  3506. $group_id = getProp($data, 'group_id');
  3507. $file = getProp($data, 'file');
  3508. $content = getProp($data, 'content', '');
  3509. $bid = getProp($data, 'bid', 0);
  3510. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3511. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3512. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3513. $prompt = getProp($data, 'prompt');
  3514. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3515. if (!empty($prompt)) {
  3516. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3517. }
  3518. $question = getProp($data, 'question', $baseQuestion);
  3519. $model = getProp($data, 'model');
  3520. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3521. Utils::throwError('20003:该模型不存在!');
  3522. }
  3523. // 检查是否存在重叠的剧集序号范围
  3524. $exists_groups = DB::table('mp_script_episode_group')
  3525. ->where('script_id', $script_id)
  3526. ->where('id', '<>', $group_id)
  3527. ->where('is_deleted', 0)
  3528. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3529. // 检查新范围是否与现有范围重叠
  3530. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3531. // 新范围的开始在现有范围内
  3532. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3533. ->where('end_episode_number', '>=', $start_episode_sequence);
  3534. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3535. // 新范围的结束在现有范围内
  3536. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3537. ->where('end_episode_number', '>=', $end_episode_sequence);
  3538. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3539. // 新范围完全包含现有范围
  3540. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3541. ->where('end_episode_number', '<=', $end_episode_sequence);
  3542. });
  3543. })
  3544. ->select('start_episode_number', 'end_episode_number')
  3545. ->get();
  3546. if ($exists_groups->isNotEmpty()) {
  3547. $conflict_ranges = [];
  3548. foreach ($exists_groups as $group) {
  3549. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3550. }
  3551. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3552. }
  3553. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3554. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3555. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3556. if ($model === 'deepseek-chat') {
  3557. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3558. $model = 'deepseek-v4-flash';
  3559. $thinkingMode = 'disabled';
  3560. } elseif ($model === 'deepseek-reasoner') {
  3561. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3562. $model = 'deepseek-v4-flash';
  3563. $thinkingMode = 'enabled';
  3564. }
  3565. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3566. if (!$script) {
  3567. Utils::throwError('20003:剧本不存在');
  3568. }
  3569. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3570. if (!$group) {
  3571. Utils::throwError('20003:剧本分集不存在');
  3572. }
  3573. if (!$file && !$content && !$bid) {
  3574. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3575. }
  3576. // 提取文件内容
  3577. if ($file) {
  3578. $content = $this->extractFileContent($file);
  3579. if (!$content) {
  3580. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3581. }
  3582. } elseif ($bid) {
  3583. $content = $this->getContentByBid($bid);
  3584. if (!$content) {
  3585. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3586. }
  3587. } elseif ($content) {
  3588. $content = filterContent($content);
  3589. } elseif ($prompt) {
  3590. $content = filterContent($prompt);
  3591. } else {
  3592. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3593. }
  3594. // 构建消息
  3595. $messages = [
  3596. [
  3597. 'role' => 'system',
  3598. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3599. 强制要求:\n
  3600. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3601. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3602. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3603. 普通要求:\n
  3604. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3605. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3606. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3607. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3608. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3609. 示例如下:\n
  3610. ###剧本名:西昆仑
  3611. ###故事梗概
  3612. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3613. ###剧本亮点
  3614. 亮点1:绝境奇药,生死一线
  3615. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3616. 亮点2:结拜兄妹,化解尴尬
  3617. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3618. 亮点3:纤发夺命,情愫暗涌
  3619. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3620. ###人物关系
  3621. 阿雪与梁萧之间存在兄妹之情。
  3622. ###核心矛盾
  3623. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3624. ###主体列表
  3625. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3626. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3627. 阴阳球:天地异宝,能化生精气,救人于危难。
  3628. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3629. ###美术风格
  3630. 基础画风风格词:厚涂古风
  3631. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3632. ###场景列表
  3633. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3634. [
  3635. 'role' => 'user',
  3636. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3637. ]
  3638. ];
  3639. $post_data = [
  3640. 'model' => $model,
  3641. 'messages' => $messages,
  3642. // 'max_tokens' => 8192,
  3643. 'temperature' => 0.7,
  3644. 'frequency_penalty' => 0,
  3645. 'presence_penalty' => 0,
  3646. 'thinking' => ['type' => $thinkingMode],
  3647. 'response_format' => ['type' => 'text'],
  3648. 'stream' => true
  3649. ];
  3650. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3651. // 根据模型类型选择调用方法
  3652. $fullContent = '';
  3653. $fullReasoningContent = '';
  3654. $usage = [];
  3655. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3656. // DeepSeek 官方模型使用 DeepSeek API
  3657. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3658. } else if (in_array($model, $this->gpt_text_models)) {
  3659. // GPT-5.4 模型使用 TokenRouter API
  3660. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3661. } else if (in_array($model, $this->gemini_text_models)) {
  3662. // Gemini 模型使用 Gemini API
  3663. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3664. } else {
  3665. // 其他模型使用火山引擎API
  3666. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3667. }
  3668. // 处理流式输出
  3669. foreach ($streamGenerator as $chunk) {
  3670. if (isset($chunk['type'])) {
  3671. if ($chunk['type'] === 'done') {
  3672. // 最终结果
  3673. $fullContent = $chunk['full_content'];
  3674. $fullReasoningContent = $chunk['full_reasoning'];
  3675. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3676. } else {
  3677. // 逐块yield数据
  3678. yield $chunk;
  3679. }
  3680. }
  3681. }
  3682. dLog('deepseek')->info('完整内容: '.$fullContent);
  3683. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3684. // 处理完整内容并返回最终结果
  3685. $script_arr = [];
  3686. if ($fullContent) {
  3687. $script_arr = extractScriptContent($fullContent);
  3688. }
  3689. logDB('deepseek', 'info', '解析内容', $script_arr);
  3690. if (!$script_arr['roles']) {
  3691. Utils::throwError('20003:未生成剧本相关信息');
  3692. // yield [
  3693. // 'type' => 'done',
  3694. // 'script' => $script_arr,
  3695. // 'msg' => '未生成剧本相关信息',
  3696. // 'answer' => $fullContent,
  3697. // 'reasoning' => $fullReasoningContent,
  3698. // 'usage' => $usage
  3699. // ];
  3700. }
  3701. try {
  3702. DB::beginTransaction();
  3703. // // 返回前保存剧本内容
  3704. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3705. // 'content' => $content,
  3706. // 'status' => '解析完成',
  3707. // 'updated_at' => date('Y-m-d H:i:s')
  3708. // ]);
  3709. // if (!$boolen) {
  3710. // Utils::throwError('20003:保存剧本内容失败');
  3711. // }
  3712. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3713. 'start_episode_number' => $start_episode_sequence,
  3714. 'end_episode_number' => $end_episode_sequence,
  3715. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3716. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3717. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3718. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3719. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3720. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3721. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3722. 'status' => '解析完成',
  3723. 'content' => $content,
  3724. 'updated_at' => date('Y-m-d H:i:s')
  3725. ]);
  3726. if (!$boolen1) {
  3727. Utils::throwError('20003:保存分集失败');
  3728. }
  3729. // $episodes = [];
  3730. // foreach ($script_arr['episodes'] as $item) {
  3731. // $episodes[] = [
  3732. // 'script_id' => $script_id,
  3733. // 'episode_number' => $item['episode_number'],
  3734. // 'episode_name' => $item['episode_name'],
  3735. // 'episode_content' => $item['episode_content'],
  3736. // 'created_at' => date('Y-m-d H:i:s'),
  3737. // 'updated_at' => date('Y-m-d H:i:s'),
  3738. // ];
  3739. // }
  3740. // if ($episodes) {
  3741. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3742. // if (!$boolen2) {
  3743. // Utils::throwError('20003:保存分集内容失败');
  3744. // }
  3745. // }else {
  3746. // Utils::throwError('20003:分集剧本解析失败');
  3747. // }
  3748. }catch (\Exception $e) {
  3749. DB::rollBack();
  3750. Utils::throwError('20003:'.$e->getMessage());
  3751. }
  3752. DB::commit();
  3753. yield [
  3754. 'type' => 'done',
  3755. 'script' => $script_arr,
  3756. 'answer' => $fullContent,
  3757. 'reasoning' => $fullReasoningContent,
  3758. 'usage' => $usage
  3759. ];
  3760. }
  3761. /**
  3762. * 上传文件识别文字内容并与 DeepSeek 进行对话
  3763. *
  3764. * @param array $data 包含以下参数:
  3765. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3766. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  3767. * - model: 使用的模型(r1 或 v3,默认 v3)
  3768. * @return array
  3769. */
  3770. public function chatWithFile($data) {
  3771. $script_id = getProp($data, 'script_id');
  3772. $file = getProp($data, 'file');
  3773. $content = getProp($data, 'content', '');
  3774. $bid = getProp($data, 'bid', 0);
  3775. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3776. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3777. $prompt = getProp($data, 'prompt');
  3778. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3779. if (!empty($prompt)) {
  3780. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3781. }
  3782. $question = getProp($data, 'question', $baseQuestion);
  3783. // 处理文本模型
  3784. $model = getProp($data, 'model');
  3785. if (!$model) {
  3786. // 用户没有输入,使用默认值
  3787. $model = 'doubao-seed-2-0-mini-260215';
  3788. }
  3789. // 验证模型是否在可用模型表中
  3790. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3791. $model = 'doubao-seed-2-0-mini-260215';
  3792. }
  3793. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3794. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3795. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3796. if ($model === 'deepseek-chat') {
  3797. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3798. $model = 'deepseek-v4-flash';
  3799. $thinkingMode = 'disabled';
  3800. } elseif ($model === 'deepseek-reasoner') {
  3801. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3802. $model = 'deepseek-v4-flash';
  3803. $thinkingMode = 'enabled';
  3804. }
  3805. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3806. if (!$script) {
  3807. Utils::throwError('20003:剧本不存在');
  3808. }
  3809. if (!$file && !$content && !$bid) {
  3810. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3811. }
  3812. // 提取文件内容
  3813. if ($file) {
  3814. $content = $this->extractFileContent($file);
  3815. if (!$content) {
  3816. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3817. }
  3818. } elseif ($bid) {
  3819. $content = $this->getContentByBid($bid);
  3820. if (!$content) {
  3821. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3822. }
  3823. } elseif ($content) {
  3824. $content = filterContent($content);
  3825. } elseif ($prompt) {
  3826. $content = filterContent($prompt);
  3827. } else {
  3828. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3829. }
  3830. // 构建消息
  3831. $messages = [
  3832. $this->sys_message,
  3833. [
  3834. 'role' => 'user',
  3835. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3836. ]
  3837. ];
  3838. $post_data = [
  3839. 'model' => $model,
  3840. 'messages' => $messages,
  3841. // 'max_tokens' => 8192,
  3842. 'temperature' => 0.7,
  3843. 'frequency_penalty' => 0,
  3844. 'presence_penalty' => 0,
  3845. 'thinking' => ['type' => $thinkingMode],
  3846. 'response_format' => ['type' => 'text'],
  3847. 'stream' => false
  3848. ];
  3849. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3850. // 根据模型类型选择调用方法
  3851. $fullContent = '';
  3852. $usage = [];
  3853. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3854. // DeepSeek 官方模型使用 DeepSeek API
  3855. $chatResult = $this->chatOnly($post_data);
  3856. } else if (in_array($model, $this->gpt_text_models)) {
  3857. // GPT-5.4 模型使用 TokenRouter API
  3858. $chatResult = $this->gpt54ChatOnly($post_data);
  3859. } else {
  3860. // 其他模型使用火山引擎API
  3861. $chatResult = $this->volcEngineChatCompletion($post_data);
  3862. }
  3863. if (is_array($chatResult)) {
  3864. $fullContent = $chatResult['fullContent'];
  3865. $usage = $chatResult['usage'];
  3866. }
  3867. $script_arr = [];
  3868. // 处理结果
  3869. if ($fullContent) {
  3870. $script_arr = extractScriptContent($fullContent);
  3871. }
  3872. // 返回前保存剧本内容
  3873. DB::table('mp_scripts')->where('id', $script_id)->update([
  3874. 'content' => $content,
  3875. 'updated_at' => date('Y-m-d H:i:s')
  3876. ]);
  3877. return [
  3878. 'script' => $script_arr,
  3879. 'answer' => $fullContent,
  3880. 'usage' => $usage
  3881. ];
  3882. }
  3883. public function getEpisodeContent($data) {
  3884. $group_id = getProp($data, 'group_id');
  3885. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  3886. }
  3887. public function saveEpisodeContent($data) {
  3888. $script_id = getProp($data, 'script_id');
  3889. $group_id = getProp($data, 'group_id');
  3890. $start_episode_sequence = getProp($data, 'start_episode_number');
  3891. $end_episode_sequence = getProp($data, 'end_episode_number');
  3892. // 检查是否存在重叠的剧集序号范围
  3893. $exists_groups = DB::table('mp_script_episode_group')
  3894. ->where('script_id', $script_id)
  3895. ->where('id', '<>', $group_id) // 排除当前组
  3896. ->where('is_deleted', 0)
  3897. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3898. // 检查新范围是否与现有范围重叠
  3899. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3900. // 新范围的开始在现有范围内
  3901. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3902. ->where('end_episode_number', '>=', $start_episode_sequence);
  3903. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3904. // 新范围的结束在现有范围内
  3905. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3906. ->where('end_episode_number', '>=', $end_episode_sequence);
  3907. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3908. // 新范围完全包含现有范围
  3909. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3910. ->where('end_episode_number', '<=', $end_episode_sequence);
  3911. });
  3912. })
  3913. ->select('start_episode_number', 'end_episode_number')
  3914. ->get();
  3915. if ($exists_groups->isNotEmpty()) {
  3916. $conflict_ranges = [];
  3917. foreach ($exists_groups as $group) {
  3918. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3919. }
  3920. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3921. }
  3922. $episode_content = getProp($data, 'episode_content');
  3923. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  3924. 'content' => $episode_content,
  3925. 'start_episode_number' => $start_episode_sequence,
  3926. 'end_episode_number' => $end_episode_sequence,
  3927. 'updated_at' => date('Y-m-d H:i:s')
  3928. ]);
  3929. $script_arr =getProp($data, 'script', []);
  3930. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  3931. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3932. $script_id = getProp($data, 'script_id');
  3933. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  3934. try {
  3935. DB::beginTransaction();
  3936. $update_data = [
  3937. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3938. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3939. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3940. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3941. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3942. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3943. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3944. 'status' => 3,
  3945. 'start_episode_sequence' => $start_episode_sequence,
  3946. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  3947. 'episode_num' => count($script_arr['episodes']),
  3948. 'updated_at' => date('Y-m-d H:i:s')
  3949. ];
  3950. // 保存剧本内容
  3951. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  3952. if (!$boolen) {
  3953. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  3954. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  3955. Utils::throwError('20003:剧本内容保存失败');
  3956. }
  3957. // 保存分集内容
  3958. // 删除历史分集内容
  3959. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  3960. $episodes = [];
  3961. $sequence = 1;
  3962. foreach ($script_arr['episodes'] as $episode) {
  3963. $segment_number = 1;
  3964. foreach($episode['segments'] as $segment) {
  3965. $episodes[] = [
  3966. 'script_id' => $script_id,
  3967. 'episode_number' => $episode['episode_number'],
  3968. 'title' => $episode['title'],
  3969. // 'content' => $episode['content'],
  3970. 'content' => '',
  3971. 'segment_number' => $segment_number,
  3972. 'segment_content' => $segment['segment_content'],
  3973. 'sequence' => $sequence,
  3974. 'created_at' => date('Y-m-d H:i:s'),
  3975. 'updated_at' => date('Y-m-d H:i:s')
  3976. ];
  3977. $sequence++;
  3978. $segment_number++;
  3979. }
  3980. }
  3981. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3982. if (!$boolen2) {
  3983. dLog('deepseek')->info('分集内容保存失败', $episodes);
  3984. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  3985. Utils::throwError('20003:分集内容保存失败');
  3986. }
  3987. } catch (\Exception $e) {
  3988. DB::rollBack();
  3989. Utils::throwError('20003:'.$e->getMessage());
  3990. }
  3991. DB::commit();
  3992. return true;
  3993. }
  3994. public function getBookContent($data) {
  3995. $bid = getProp($data, 'bid');
  3996. $start_sequence = getProp($data, 'start_sequence');
  3997. $end_sequence = getProp($data, 'end_sequence');
  3998. $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])
  3999. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4000. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4001. return $return_content;
  4002. }
  4003. public function exportScript($data) {
  4004. $filename = getProp($data, 'filename');
  4005. $script_id = getProp($data, 'script_id');
  4006. $group_id = getProp($data, 'group_id');
  4007. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4008. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4009. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4010. $script = (array)$script;
  4011. // 获取分集组信息
  4012. if ($group_id) {
  4013. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4014. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4015. ->get()->map(function($value) {
  4016. return (array)$value;
  4017. })->toArray();
  4018. }else {
  4019. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4020. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4021. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4022. return (array)$value;
  4023. })->toArray();
  4024. }
  4025. if (!$groups) Utils::throwError('20003:分集不存在');
  4026. $script['group'] = $groups;
  4027. $export_type = getProp($data, 'export_type', 'txt');
  4028. // 生成文件名
  4029. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4030. // 根据导出类型生成不同格式的文件
  4031. switch ($export_type) {
  4032. case 'txt':
  4033. return $this->exportScriptAsTxt($script, $filename);
  4034. case 'pdf':
  4035. return $this->exportScriptAsPdf($script, $filename);
  4036. default:
  4037. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4038. }
  4039. }
  4040. /**
  4041. * 导出剧本为TXT格式
  4042. */
  4043. private function exportScriptAsTxt($script, $filename) {
  4044. // 构建TXT内容
  4045. $content = $this->buildScriptContent($script);
  4046. // 设置响应头,直接下载
  4047. header('Content-Type: text/plain; charset=utf-8');
  4048. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4049. header('Content-Length: ' . strlen($content));
  4050. // 输出内容并结束
  4051. echo $content;
  4052. exit();
  4053. }
  4054. /**
  4055. * 导出剧本为PDF格式
  4056. */
  4057. private function exportScriptAsPdf($script, $filename) {
  4058. // 使用HTML转PDF的方式来更好地支持中文
  4059. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4060. // 创建PDF实例
  4061. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4062. // 设置文档信息
  4063. $pdf->SetCreator('剧本导出系统');
  4064. $pdf->SetAuthor('系统');
  4065. $pdf->SetTitle($script['script_name']);
  4066. $pdf->SetSubject('剧本导出');
  4067. // 设置边距
  4068. $pdf->SetMargins(15, 15, 15);
  4069. $pdf->SetAutoPageBreak(TRUE, 15);
  4070. // 添加页面
  4071. $pdf->AddPage();
  4072. // 注册并使用 simsun.ttf 字体
  4073. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4074. // 使用HTML内容生成PDF
  4075. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4076. // 直接输出PDF文件供下载
  4077. header('Content-Type: application/pdf');
  4078. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4079. // 直接输出PDF内容
  4080. $pdf->Output($filename . '.pdf', 'D');
  4081. exit();
  4082. }
  4083. /**
  4084. * 构建用于PDF的HTML内容
  4085. */
  4086. private function buildScriptHtmlForPdf($script) {
  4087. $html = '<style>
  4088. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4089. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4090. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4091. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4092. .info { margin-bottom: 8px; }
  4093. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4094. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4095. .segment { margin-bottom: 10px; margin-left: 20px; }
  4096. .episode-content { white-space: pre-wrap; }
  4097. </style>';
  4098. // 标题
  4099. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4100. // 处理分组数据
  4101. if (!empty($script['group']) && is_array($script['group'])) {
  4102. $groups = (array)$script['group'];
  4103. foreach ($groups as $group) {
  4104. $html .= '<div class="group">';
  4105. // 分组标题
  4106. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4107. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4108. // 故事梗概
  4109. if (!empty($group['intro'])) {
  4110. $html .= '<h3>故事梗概</h3>';
  4111. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4112. }
  4113. // 剧本亮点
  4114. if (!empty($group['highlights'])) {
  4115. $html .= '<h3>剧本亮点</h3>';
  4116. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4117. }
  4118. // 人物关系
  4119. if (!empty($group['role_relationship'])) {
  4120. $html .= '<h3>人物关系</h3>';
  4121. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4122. }
  4123. // 核心矛盾
  4124. if (!empty($group['core_contradiction'])) {
  4125. $html .= '<h3>核心矛盾</h3>';
  4126. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4127. }
  4128. // 主体列表
  4129. if (!empty($group['roles']) && is_array($group['roles'])) {
  4130. $html .= '<h3>主体列表</h3>';
  4131. $html .= '<ul>';
  4132. foreach ($group['roles'] as $role) {
  4133. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4134. }
  4135. $html .= '</ul>';
  4136. }
  4137. // 美术风格
  4138. if (!empty($group['art_style'])) {
  4139. $html .= '<h3>美术风格</h3>';
  4140. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4141. }
  4142. // 场景列表
  4143. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4144. $html .= '<h3>场景列表</h3>';
  4145. $html .= '<ul>';
  4146. foreach ($group['scenes'] as $scene) {
  4147. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4148. }
  4149. $html .= '</ul>';
  4150. }
  4151. // 分集剧本
  4152. if (!empty($group['episode_content'])) {
  4153. $html .= '<h3>分集剧本</h3>';
  4154. // 去除零宽字符和其他不可见字符
  4155. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4156. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4157. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4158. }
  4159. $html .= '</div>';
  4160. }
  4161. }
  4162. return $html;
  4163. }
  4164. /**
  4165. * 构建PDF内容
  4166. */
  4167. private function buildPdfContent($pdf, $script) {
  4168. // 标题
  4169. $pdf->SetFont('dejavusans', 'B', 18);
  4170. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4171. $pdf->Ln(5);
  4172. // 基本信息
  4173. $pdf->SetFont('dejavusans', '', 12);
  4174. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4175. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4176. $pdf->Ln(5);
  4177. // 剧本简介
  4178. if (!empty($script['intro'])) {
  4179. $pdf->SetFont('dejavusans', 'B', 14);
  4180. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4181. $pdf->SetFont('dejavusans', '', 12);
  4182. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4183. $pdf->Ln(3);
  4184. }
  4185. // 亮点
  4186. if (!empty($script['highlights'])) {
  4187. $pdf->SetFont('dejavusans', 'B', 14);
  4188. $pdf->Cell(0, 10, '亮点', 0, 1);
  4189. $pdf->SetFont('dejavusans', '', 12);
  4190. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4191. $pdf->Ln(3);
  4192. }
  4193. // 核心矛盾
  4194. if (!empty($script['core_contradiction'])) {
  4195. $pdf->SetFont('dejavusans', 'B', 14);
  4196. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4197. $pdf->SetFont('dejavusans', '', 12);
  4198. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4199. $pdf->Ln(3);
  4200. }
  4201. // 艺术风格
  4202. if (!empty($script['art_style'])) {
  4203. $pdf->SetFont('dejavusans', 'B', 14);
  4204. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4205. $pdf->SetFont('dejavusans', '', 12);
  4206. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4207. $pdf->Ln(3);
  4208. }
  4209. // 备注
  4210. if (!empty($script['remark'])) {
  4211. $pdf->SetFont('dejavusans', 'B', 14);
  4212. $pdf->Cell(0, 10, '备注', 0, 1);
  4213. $pdf->SetFont('dejavusans', '', 12);
  4214. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4215. $pdf->Ln(3);
  4216. }
  4217. // 角色列表
  4218. if (!empty($script['roles']) && is_array($script['roles'])) {
  4219. $pdf->SetFont('dejavusans', 'B', 14);
  4220. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4221. $pdf->SetFont('dejavusans', '', 12);
  4222. foreach ($script['roles'] as $index => $role) {
  4223. if (is_array($role) || is_object($role)) {
  4224. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4225. } else {
  4226. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4227. }
  4228. }
  4229. $pdf->Ln(3);
  4230. }
  4231. // 角色关系
  4232. if (!empty($script['role_relationship'])) {
  4233. $pdf->SetFont('dejavusans', 'B', 14);
  4234. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4235. $pdf->SetFont('dejavusans', '', 12);
  4236. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4237. $pdf->Ln(3);
  4238. }
  4239. // 场景列表
  4240. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4241. $pdf->SetFont('dejavusans', 'B', 14);
  4242. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4243. $pdf->SetFont('dejavusans', '', 12);
  4244. foreach ($script['scenes'] as $index => $scene) {
  4245. if (is_array($scene) || is_object($scene)) {
  4246. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4247. } else {
  4248. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4249. }
  4250. }
  4251. $pdf->Ln(5);
  4252. }
  4253. // 分集内容
  4254. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4255. $pdf->SetFont('dejavusans', 'B', 16);
  4256. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4257. $pdf->Ln(3);
  4258. foreach ($script['episodes'] as $episode) {
  4259. // 检查是否需要新页面
  4260. if ($pdf->GetY() > 250) {
  4261. $pdf->AddPage();
  4262. }
  4263. $pdf->SetFont('dejavusans', 'B', 14);
  4264. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4265. if (!empty($episode['title'])) {
  4266. $episodeTitle .= ':' . $episode['title'];
  4267. }
  4268. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4269. // 处理分段内容
  4270. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4271. $pdf->SetFont('dejavusans', '', 12);
  4272. foreach ($episode['segments'] as $segment) {
  4273. if (!empty($segment['segment_content'])) {
  4274. // 如果有分段编号,显示分段标题
  4275. if (!empty($segment['segment_number'])) {
  4276. $pdf->SetFont('dejavusans', 'B', 12);
  4277. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4278. $pdf->SetFont('dejavusans', '', 12);
  4279. }
  4280. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4281. $pdf->Ln(2);
  4282. }
  4283. }
  4284. }
  4285. $pdf->Ln(5);
  4286. }
  4287. }
  4288. }
  4289. /**
  4290. * 构建剧本文本内容
  4291. */
  4292. private function buildScriptContent($script) {
  4293. $content = '';
  4294. $groups = $script['group'];
  4295. $groups = (array)$groups;
  4296. foreach ($groups as $group) {
  4297. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4298. // 剧本基本信息
  4299. if (!empty($group['intro'])) {
  4300. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4301. }
  4302. if (!empty($group['highlights'])) {
  4303. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4304. }
  4305. if (!empty($group['role_relationship'])) {
  4306. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4307. }
  4308. if (!empty($group['core_contradiction'])) {
  4309. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4310. }
  4311. if (!empty($group['roles']) && is_array($group['roles'])) {
  4312. $content .= "###主体列表\n";
  4313. foreach ($group['roles'] as $role) {
  4314. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4315. }
  4316. $content .= "\n\n";
  4317. }
  4318. if (!empty($group['art_style'])) {
  4319. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4320. }
  4321. // 场景信息
  4322. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4323. $content .= "###场景列表\n";
  4324. foreach ($group['scenes'] as $scene) {
  4325. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4326. }
  4327. $content .= "\n\n";
  4328. }
  4329. // 分集内容
  4330. if (!empty($group['episode_content'])) {
  4331. $content .= "###分集剧本\n";
  4332. $content .= $group['episode_content'];
  4333. // foreach ($script['episodes'] as $episode) {
  4334. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4335. // // if (!empty($episode['episode_name'])) {
  4336. // // $content .= ":" . $episode['episode_name'];
  4337. // // }
  4338. // // $content .= "\n";
  4339. // $content .= $episode['episode_content'] . "\n\n";
  4340. // }
  4341. }
  4342. }
  4343. return $content;
  4344. }
  4345. /**
  4346. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4347. *
  4348. * @param array $data 包含以下参数:
  4349. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4350. * - question: 用户问题(可选)
  4351. * - model: 使用的模型(r1 或 v3,默认 v3)
  4352. * @return \Generator 返回生成器,用于流式输出
  4353. */
  4354. public function addChat($data) {
  4355. $uid = Site::getUid();
  4356. $anime_id = getProp($data, 'anime_id');
  4357. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4358. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4359. if (!$anime) Utils::throwError('20003:对话不存在');
  4360. $file = getProp($data, 'file');
  4361. $content = getProp($data, 'content', '');
  4362. $bid = getProp($data, 'bid', 0);
  4363. $script_id = getProp($data, 'script_id', 0);
  4364. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4365. $prompt = getProp($data, 'prompt');
  4366. $user_anime_name = getProp($anime, 'anime_name');
  4367. // 处理文本模型
  4368. $model = getProp($data, 'model');
  4369. if (!$model) {
  4370. // 用户没有输入,从anime表获取
  4371. $model = getProp($anime, 'model');
  4372. if (!$model) {
  4373. // anime表也没有,使用默认值
  4374. $model = 'doubao-seed-2-0-mini-260215';
  4375. }
  4376. }
  4377. // 验证模型是否在可用模型表中
  4378. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4379. $model = 'doubao-seed-2-0-mini-260215';
  4380. }
  4381. $is_multi = getProp($anime, 'is_multi');
  4382. $is_single = (int)$is_multi !== 1;
  4383. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4384. if ($prompt) {
  4385. $question .= "本次修改要求如下:\n{$prompt}";
  4386. }
  4387. // if (!$file && !$content && !$bid) {
  4388. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4389. // }
  4390. // 提取文件内容
  4391. if ($file) {
  4392. $content = $this->extractFileContent($file);
  4393. if (!$content) {
  4394. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4395. }
  4396. } elseif ($script_id) {
  4397. $content = $this->getContentByScriptId($script_id);
  4398. if (!$content) {
  4399. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4400. }
  4401. } elseif ($bid) {
  4402. $content = $this->getContentByBid($bid);
  4403. if (!$content) {
  4404. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4405. }
  4406. } elseif ($content) {
  4407. $content = filterContent($content);
  4408. } else {
  4409. $content = getProp($anime, 'content');
  4410. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4411. $need_generate_content = true;
  4412. }
  4413. }
  4414. // 美术风格
  4415. $input_art_style = getProp($data, 'art_style');
  4416. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4417. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4418. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4419. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4420. 中年女:邻居阿姨
  4421. 老年男:幽默大爷
  4422. 老年女:婆婆
  4423. 萌娃:奶气萌娃";
  4424. // 判断是否需要生成原文内容
  4425. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4426. // 如果需要生成原文内容,添加额外的要求
  4427. $content_generation_requirement = $need_generate_content
  4428. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4429. : "";
  4430. // 美术风格
  4431. if (!$mappedArtStyle) {
  4432. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4433. }else {
  4434. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4435. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4436. }else {
  4437. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4438. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4439. }
  4440. }
  4441. $systemPrompt = $is_single
  4442. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4443. 强制要求:
  4444. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4445. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4446. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4447. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4448. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4449. 普通要求:
  4450. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4451. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4452. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4453. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4454. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4455. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4456. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4457. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4458. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4459. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4460. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4461. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4462. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4463. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4464. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4465. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4466. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4467. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4468. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4469. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4470. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4471. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4472. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4473. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4474. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4475. 5.{$mappedArtStyle_prompt}\n\n
  4476. 示例如下:\n
  4477. ###剧本名:西昆仑
  4478. ###故事梗概
  4479. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4480. ###剧本亮点
  4481. 亮点1:绝境奇药,生死一线
  4482. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4483. 亮点2:结拜兄妹,化解尴尬
  4484. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4485. 亮点3:纤发夺命,情愫暗涌
  4486. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4487. ###人物关系
  4488. 阿雪与梁萧之间存在兄妹之情。
  4489. ###核心矛盾
  4490. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4491. ###主体列表
  4492. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4493. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4494. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4495. 姿态:站立。}{{甜心小美}}
  4496. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4497. 全景,正面拍摄,青年女性,亚洲人。
  4498. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4499. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4500. 姿态:站立。}{{阳光青年}}
  4501. ###美术风格
  4502. 基础画风风格词:厚涂古风
  4503. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4504. ###场景列表
  4505. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4506. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4507. 无人物。}
  4508. ###分镜剧本
  4509. ##第1幕:徐家老旧厨房 白天 室内
  4510. 分镜1
  4511. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4512. 场景:徐家老旧厨房
  4513. 构图设计:全景,低角度仰视
  4514. 运镜调度:手持拍摄
  4515. 配音角色:旁白
  4516. 出镜角色:许芸-校服装、徐母
  4517. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4518. 画面类型:普通画面
  4519. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4520. 分镜2
  4521. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4522. 场景:徐家老旧厨房
  4523. 构图设计:近景,徐母面部特写
  4524. 运镜调度:固定镜头
  4525. 配音角色:徐母
  4526. 出镜角色:徐母
  4527. 台词内容:问我夜不归宿死哪儿去了。
  4528. 画面类型:对口型
  4529. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4530. ##第2幕:徐家简陋客厅 黄昏 室内
  4531. 分镜3
  4532. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4533. 场景:徐家简陋客厅
  4534. 构图设计:全景,景深虚化
  4535. 运镜调度:固定镜头
  4536. 配音角色:旁白
  4537. 出镜角色:无
  4538. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4539. 画面类型:普通画面
  4540. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4541. 分镜4
  4542. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4543. 场景:徐家简陋客厅
  4544. 构图设计:特写,火车票
  4545. 运镜调度:固定镜头
  4546. 配音角色:旁白
  4547. 出镜角色:无
  4548. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4549. 画面类型:普通画面
  4550. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4551. "
  4552. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4553. 强制要求:\n
  4554. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4555. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4556. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4557. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4558. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4559. 普通要求:\n
  4560. 1.剧本名(必须生成)必须与文档内容高度相关
  4561. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4562. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4563. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4564. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4565. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4566. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4567. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4568. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4569. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4570. 4.{$mappedArtStyle_prompt}\n\n
  4571. 示例如下:\n
  4572. ###剧本名:西昆仑
  4573. ###故事梗概
  4574. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4575. ###剧本亮点
  4576. 亮点1:绝境奇药,生死一线
  4577. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4578. 亮点2:结拜兄妹,化解尴尬
  4579. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4580. 亮点3:纤发夺命,情愫暗涌
  4581. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4582. ###人物关系
  4583. 阿雪与梁萧之间存在兄妹之情。
  4584. ###核心矛盾
  4585. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4586. ###主体列表
  4587. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4588. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4589. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4590. 姿态:站立。}{{甜心小美}}
  4591. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4592. 全景,正面拍摄,青年女性,亚洲人。
  4593. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4594. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4595. 姿态:站立。}{{阳光青年}}
  4596. ###美术风格
  4597. 基础画风风格词:厚涂古风
  4598. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4599. ###场景列表
  4600. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4601. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4602. 无人物。}";
  4603. // 构建消息
  4604. $messages = [
  4605. [
  4606. 'role' => 'system',
  4607. 'content' => $systemPrompt
  4608. ],
  4609. [
  4610. 'role' => 'user',
  4611. 'content' => "以下是文档内容:
  4612. {$content}
  4613. 用户问题:
  4614. {$question}"
  4615. ]
  4616. ];
  4617. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4618. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4619. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4620. if ($model === 'deepseek-chat') {
  4621. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4622. $model = 'deepseek-v4-flash';
  4623. $thinkingMode = 'disabled';
  4624. } elseif ($model === 'deepseek-reasoner') {
  4625. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4626. $model = 'deepseek-v4-flash';
  4627. $thinkingMode = 'enabled';
  4628. }
  4629. $post_data = [
  4630. 'model' => $model,
  4631. 'messages' => $messages,
  4632. // 'max_tokens' => 8192,
  4633. 'temperature' => 0.7,
  4634. 'frequency_penalty' => 0,
  4635. 'presence_penalty' => 0,
  4636. 'response_format' => ['type' => 'text'],
  4637. 'thinking' => ['type'=>$thinkingMode],
  4638. 'stream' => true // 启用流式输出
  4639. ];
  4640. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4641. // 根据模型类型选择调用方法
  4642. $fullContent = '';
  4643. $fullReasoningContent = '';
  4644. $usage = [];
  4645. try {
  4646. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4647. // DeepSeek 官方模型使用 DeepSeek API
  4648. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4649. } else if (in_array($model, $this->gpt_text_models)) {
  4650. // GPT-5.4 模型使用 TokenRouter API
  4651. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4652. } else if (in_array($model, $this->gemini_text_models)) {
  4653. // Gemini 模型使用 Gemini API
  4654. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4655. } else {
  4656. // 其他模型使用火山引擎API
  4657. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4658. }
  4659. // 验证返回值类型
  4660. if (!is_iterable($streamGenerator)) {
  4661. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4662. dLog('deepseek')->error('addChat流式生成器无效', [
  4663. 'generator_type' => $errorType,
  4664. 'model' => $model,
  4665. 'anime_id' => $anime_id
  4666. ]);
  4667. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4668. 'type' => $errorType,
  4669. 'model' => $model
  4670. ]);
  4671. yield [
  4672. 'type' => 'error',
  4673. 'script' => [],
  4674. 'episode' => [],
  4675. 'answer' => '',
  4676. 'reasoning' => '',
  4677. 'usage' => [],
  4678. 'error' => '接口返回数据异常,请重新请求'
  4679. ];
  4680. return;
  4681. }
  4682. // 处理流式输出
  4683. foreach ($streamGenerator as $chunk) {
  4684. if (isset($chunk['type'])) {
  4685. if ($chunk['type'] === 'done') {
  4686. // 最终结果
  4687. $fullContent = $chunk['full_content'];
  4688. $fullReasoningContent = $chunk['full_reasoning'];
  4689. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4690. } else {
  4691. // 逐块yield数据
  4692. yield $chunk;
  4693. }
  4694. }
  4695. }
  4696. } catch (\Exception $e) {
  4697. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4698. 'model' => $model,
  4699. 'anime_id' => $anime_id,
  4700. 'trace' => $e->getTraceAsString()
  4701. ]);
  4702. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4703. 'error' => $e->getMessage(),
  4704. 'model' => $model
  4705. ]);
  4706. yield [
  4707. 'type' => 'error',
  4708. 'script' => [],
  4709. 'episode' => [],
  4710. 'answer' => '',
  4711. 'reasoning' => '',
  4712. 'usage' => [],
  4713. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4714. ];
  4715. return;
  4716. }
  4717. dLog('deepseek')->info('完整内容: '.$fullContent);
  4718. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4719. // 处理完整内容并返回最终结果
  4720. $script_arr = [];
  4721. if ($fullContent) {
  4722. $script_arr = handleScriptContent($fullContent);
  4723. dLog('deepseek')->info('解析内容', $script_arr);
  4724. logDB('deepseek', 'info', '解析内容', $script_arr);
  4725. }
  4726. if (empty($script_arr['roles'])) {
  4727. // 未生成剧本相关内容,保存对话记录并返回提示
  4728. dLog('deepseek')->info('未生成剧本相关的内容');
  4729. try {
  4730. DB::beginTransaction();
  4731. $now = date('Y-m-d H:i:s');
  4732. // 保存对话记录
  4733. $records = [
  4734. [
  4735. 'uid' => $uid,
  4736. 'anime_id' => $anime_id,
  4737. 'sequence' => 0,
  4738. 'role' => 'user',
  4739. 'content' => $prompt,
  4740. 'created_at' => $now,
  4741. 'updated_at' => $now
  4742. ],
  4743. [
  4744. 'uid' => $uid,
  4745. 'anime_id' => $anime_id,
  4746. 'sequence' => 0,
  4747. 'role' => 'assistant',
  4748. // 'content' => $fullContent,
  4749. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  4750. 'created_at' => $now,
  4751. 'updated_at' => $now
  4752. ]
  4753. ];
  4754. DB::table('mp_anime_records')->insert($records);
  4755. DB::commit();
  4756. } catch (\Exception $e) {
  4757. DB::rollBack();
  4758. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4759. }
  4760. yield [
  4761. 'type' => 'done',
  4762. 'script' => [],
  4763. 'episode' => [],
  4764. 'answer' => $fullContent,
  4765. 'reasoning' => $fullReasoningContent,
  4766. 'usage' => $usage,
  4767. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4768. ];
  4769. return;
  4770. }
  4771. // 如果需要生成原文内容,从script_arr中提取
  4772. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4773. $content = $script_arr['content'];
  4774. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  4775. if (!$content) {
  4776. yield [
  4777. 'type' => 'done',
  4778. 'script' => [],
  4779. 'episode' => [],
  4780. 'answer' => $fullContent,
  4781. 'reasoning' => $fullReasoningContent,
  4782. 'usage' => $usage,
  4783. 'error' => '未生成剧本内容,请调整提示词再试'
  4784. ];
  4785. return;
  4786. }
  4787. }
  4788. // 替换美术风格
  4789. if ($mappedArtStyle !== '') {
  4790. $script_arr['art_style'] = $mappedArtStyle;
  4791. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4792. }
  4793. // 新建动漫
  4794. if ($user_anime_name == '新剧本策划') {
  4795. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  4796. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  4797. // if (!$anime_name) {
  4798. // // 未识别到剧本名,保存对话记录并返回提示
  4799. // dLog('deepseek')->info('未能识别到剧本名称');
  4800. // try {
  4801. // DB::beginTransaction();
  4802. // $now = date('Y-m-d H:i:s');
  4803. // // 保存对话记录
  4804. // $records = [
  4805. // [
  4806. // 'uid' => $uid,
  4807. // 'anime_id' => $anime_id,
  4808. // 'sequence' => 0,
  4809. // 'role' => 'user',
  4810. // 'content' => $prompt,
  4811. // 'created_at' => $now,
  4812. // 'updated_at' => $now
  4813. // ],
  4814. // [
  4815. // 'uid' => $uid,
  4816. // 'anime_id' => $anime_id,
  4817. // 'sequence' => 0,
  4818. // 'role' => 'assistant',
  4819. // 'content' => '未能生成剧本名称,请重试',
  4820. // 'created_at' => $now,
  4821. // 'updated_at' => $now
  4822. // ]
  4823. // ];
  4824. // DB::table('mp_anime_records')->insert($records);
  4825. // DB::commit();
  4826. // } catch (\Exception $e) {
  4827. // DB::rollBack();
  4828. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4829. // }
  4830. // yield [
  4831. // 'type' => 'done',
  4832. // 'script' => [],
  4833. // 'episode' => [],
  4834. // 'answer' => $fullContent,
  4835. // 'reasoning' => $fullReasoningContent,
  4836. // 'usage' => $usage,
  4837. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  4838. // ];
  4839. // return;
  4840. // }
  4841. // 确认对话名称唯一性
  4842. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4843. $anime_name = $anime_name . '_' . date('YmdHis');
  4844. }
  4845. }else {
  4846. $anime_name = $user_anime_name;
  4847. }
  4848. $table_data = [
  4849. 'user_id' => $uid,
  4850. 'anime_name' => $anime_name,
  4851. 'model' => $model,
  4852. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4853. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4854. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4855. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4856. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4857. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4858. 'art_style_type' => $input_art_style,
  4859. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4860. 'status' => '解析完成',
  4861. 'content' => $content,
  4862. 'is_multi' => $is_multi,
  4863. 'ace_mode' => $ace_mode,
  4864. 'generate_status' => '待执行',
  4865. 'updated_at' => date('Y-m-d H:i:s')
  4866. ];
  4867. if ($table_data['content']) {
  4868. $chapters = splitContent($table_data['content']);
  4869. $chapter_count = count($chapters);
  4870. if ($chapter_count > 0) {
  4871. $table_data['start_episode_sequence'] = 1;
  4872. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4873. }
  4874. }
  4875. // 如果有剧本ID则进行绑定
  4876. if ($script_id) {
  4877. $table_data['script_id'] = $script_id;
  4878. }
  4879. $single_episode = [];
  4880. try {
  4881. DB::beginTransaction();
  4882. $now = date('Y-m-d H:i:s');
  4883. // 更新动漫大纲
  4884. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4885. if (!$boolen) {
  4886. dLog('deepseek')->info('动漫保存失败', $table_data);
  4887. Utils::throwError('20003:动漫保存失败');
  4888. }
  4889. // 保存对话记录
  4890. $records = [
  4891. [
  4892. 'uid' => $uid,
  4893. 'anime_id' => $anime_id,
  4894. 'sequence' => 0,
  4895. 'role' => 'user',
  4896. 'content' => $prompt,
  4897. 'created_at' => date('Y-m-d H:i:s'),
  4898. 'updated_at' => date('Y-m-d H:i:s')
  4899. ],
  4900. [
  4901. 'uid' => $uid,
  4902. 'anime_id' => $anime_id,
  4903. 'sequence' => 0,
  4904. 'role' => 'assistant',
  4905. 'content' => $fullContent,
  4906. 'created_at' => date('Y-m-d H:i:s'),
  4907. 'updated_at' => date('Y-m-d H:i:s')
  4908. ]
  4909. ];
  4910. // 保存对话记录
  4911. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4912. if (!$boolen3) {
  4913. Utils::throwError('20003:对话记录保存失败');
  4914. }
  4915. if ($is_single) {
  4916. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4917. if (empty($episode_arr['acts'])) {
  4918. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4919. }
  4920. $saveResult = $this->saveEpisodeVersionData(
  4921. $anime_id,
  4922. 1,
  4923. $episode_arr,
  4924. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4925. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4926. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4927. null,
  4928. null,
  4929. false,
  4930. $content,
  4931. $now
  4932. );
  4933. $single_episode = $saveResult['episode'];
  4934. $episode_id = $saveResult['episode_id'];
  4935. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4936. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4937. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4938. 'props' => json_encode($saveResult['merged_props'], 256),
  4939. 'updated_at' => $now
  4940. ]);
  4941. if ($boolen5 === false) {
  4942. Utils::throwError('20003:单剧集主表资源同步失败');
  4943. }
  4944. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4945. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4946. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4947. $episode_record_content = '确认分镜大纲';
  4948. if ($content !== '') {
  4949. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4950. }
  4951. $episode_records = [
  4952. [
  4953. 'uid' => $uid,
  4954. 'anime_id' => $anime_id,
  4955. 'role' => 'user',
  4956. 'content' => $episode_record_content,
  4957. 'sequence' => 1,
  4958. 'episode_id' => $episode_id,
  4959. 'created_at' => $now,
  4960. 'updated_at' => $now
  4961. ],
  4962. [
  4963. 'uid' => $uid,
  4964. 'anime_id' => $anime_id,
  4965. 'role' => 'assistant',
  4966. 'content' => $fullContent,
  4967. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4968. 'sequence' => 1,
  4969. 'episode_id' => $episode_id,
  4970. 'created_at' => $now,
  4971. 'updated_at' => $now
  4972. ]
  4973. ];
  4974. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4975. if (!$boolen4) {
  4976. Utils::throwError('20003:单剧集分镜记录保存失败');
  4977. }
  4978. }
  4979. }catch (\Exception $e) {
  4980. DB::rollBack();
  4981. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4982. yield [
  4983. 'type' => 'done',
  4984. 'answer' => $fullContent,
  4985. 'reasoning' => $fullReasoningContent,
  4986. 'usage' => $usage,
  4987. 'error' => $e->getMessage(),
  4988. ];
  4989. return;
  4990. }
  4991. DB::commit();
  4992. dLog('deepseek')->info('保存完毕');
  4993. if ($is_single && !empty($single_episode)) {
  4994. // $this->batchSetGlobalRoleImg([
  4995. // 'anime_id' => $anime_id,
  4996. // ]);
  4997. // $this->batchSetGlobalSceneImg([
  4998. // 'anime_id' => $anime_id,
  4999. // ]);
  5000. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5001. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5002. }
  5003. $table_data['anime_id'] = $anime_id;
  5004. $table_data['roles'] = json_decode($table_data['roles'], true);
  5005. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5006. // $table_data['episodes'] = $script_arr['episodes'];
  5007. unset($table_data['created_at']);
  5008. unset($table_data['updated_at']);
  5009. unset($table_data['status']);
  5010. dLog('deepseek')->info('开始返回');
  5011. yield [
  5012. 'type' => 'done',
  5013. 'script' => $table_data,
  5014. 'episode' => $single_episode,
  5015. 'answer' => $fullContent,
  5016. 'reasoning' => $fullReasoningContent,
  5017. 'usage' => $usage
  5018. ];
  5019. }
  5020. public function reGenerateAnime($data) {
  5021. $uid = Site::getUid();
  5022. $file = getProp($data, 'file');
  5023. $content = getProp($data, 'content', '');
  5024. $bid = getProp($data, 'bid', 0);
  5025. $script_id = getProp($data, 'script_id', 0);
  5026. $anime_id = getProp($data, 'anime_id');
  5027. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5028. if (!$anime) {
  5029. Utils::throwError('20003:该对话不存在');
  5030. }
  5031. $user_anime_name = getProp($anime, 'anime_name');
  5032. $prompt = getProp($data, 'prompt');
  5033. // 处理文本模型
  5034. $model = getProp($data, 'model');
  5035. if (!$model) {
  5036. // 用户没有输入,从anime表获取
  5037. $model = getProp($anime, 'model');
  5038. if (!$model) {
  5039. // anime表也没有,使用默认值
  5040. $model = 'doubao-seed-2-0-mini-260215';
  5041. }
  5042. }
  5043. // 验证模型是否在可用模型表中
  5044. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5045. $model = 'doubao-seed-2-0-mini-260215';
  5046. }
  5047. $is_multi = getProp($anime, 'is_multi', 1);
  5048. $is_single = (int)$is_multi !== 1;
  5049. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5050. if ($is_single) {
  5051. $episode_exists = DB::table('mp_anime_episodes')
  5052. ->where('anime_id', $anime_id)
  5053. ->where('sequence', 1)
  5054. ->exists();
  5055. if ($episode_exists) {
  5056. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5057. }
  5058. }
  5059. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5060. if ($prompt) {
  5061. $question .= "本次修改要求如下:\n{$prompt}";
  5062. }
  5063. // 提取文件内容
  5064. if ($file) {
  5065. $content = $this->extractFileContent($file);
  5066. if (!$content) {
  5067. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5068. }
  5069. } elseif ($script_id) {
  5070. $content = $this->getContentByScriptId($script_id);
  5071. if (!$content) {
  5072. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5073. }
  5074. } elseif ($bid) {
  5075. $content = $this->getContentByBid($bid);
  5076. if (!$content) {
  5077. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5078. }
  5079. } elseif ($content) {
  5080. $content = filterContent($content);
  5081. }else {
  5082. $content = filterContent(getProp($anime, 'content'));
  5083. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5084. $need_generate_content = true;
  5085. }
  5086. }
  5087. // 判断是否需要生成原文内容
  5088. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5089. // 如果需要生成原文内容,添加额外的要求
  5090. $content_generation_requirement = $need_generate_content
  5091. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5092. : "";
  5093. // 美术风格
  5094. $input_art_style = getProp($anime, 'art_style');
  5095. if (!$input_art_style) {
  5096. $input_art_style = getProp($data, 'art_style');
  5097. }
  5098. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5099. // 美术风格
  5100. if (!$mappedArtStyle) {
  5101. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5102. }else {
  5103. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5104. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5105. }else {
  5106. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5107. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5108. }
  5109. }
  5110. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5111. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5112. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5113. 中年女:邻居阿姨
  5114. 老年男:幽默大爷
  5115. 老年女:婆婆
  5116. 萌娃:奶气萌娃";
  5117. $system_message = ['role'=>'system', 'content'=>$is_single
  5118. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5119. 强制要求:
  5120. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5121. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5122. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5123. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5124. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5125. 普通要求:
  5126. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5127. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5128. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5129. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5130. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5131. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5132. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5133. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5134. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5135. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5136. 3.$mappedArtStyle_prompt\n\n
  5137. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5138. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5139. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5140. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5141. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5142. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5143. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5144. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5145. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5146. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5147. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5148. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5149. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5150. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5151. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5152. 示例如下:\n
  5153. ###剧本名:西昆仑
  5154. ###故事梗概
  5155. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5156. ###剧本亮点
  5157. 亮点1:绝境奇药,生死一线
  5158. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5159. 亮点2:结拜兄妹,化解尴尬
  5160. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5161. 亮点3:纤发夺命,情愫暗涌
  5162. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5163. ###人物关系
  5164. 阿雪与梁萧之间存在兄妹之情。
  5165. ###核心矛盾
  5166. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5167. ###主体列表
  5168. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5169. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5170. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5171. 姿态:站立。}{{甜心小美}}
  5172. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5173. 全景,正面拍摄,青年女性,亚洲人。
  5174. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5175. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5176. 姿态:站立。}{{阳光青年}}
  5177. ###美术风格
  5178. 基础画风风格词:厚涂古风
  5179. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5180. ###场景列表
  5181. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5182. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5183. 无人物。}
  5184. ###分镜剧本
  5185. ##第1幕:徐家老旧厨房 白天 室内
  5186. 分镜1
  5187. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5188. 场景:徐家老旧厨房
  5189. 构图设计:全景,低角度仰视
  5190. 运镜调度:手持拍摄
  5191. 配音角色:旁白
  5192. 出镜角色:许芸-校服装、徐母
  5193. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5194. 画面类型:普通画面
  5195. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5196. 分镜2
  5197. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5198. 场景:徐家老旧厨房
  5199. 构图设计:近景,徐母面部特写
  5200. 运镜调度:固定镜头
  5201. 配音角色:徐母
  5202. 出镜角色:徐母
  5203. 台词内容:问我夜不归宿死哪儿去了。
  5204. 画面类型:对口型
  5205. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5206. ##第2幕:徐家简陋客厅 黄昏 室内
  5207. 分镜3
  5208. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5209. 场景:徐家简陋客厅
  5210. 构图设计:全景,景深虚化
  5211. 运镜调度:固定镜头
  5212. 配音角色:旁白
  5213. 出镜角色:无
  5214. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5215. 画面类型:普通画面
  5216. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5217. 分镜4
  5218. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5219. 场景:徐家简陋客厅
  5220. 构图设计:特写,火车票
  5221. 运镜调度:固定镜头
  5222. 配音角色:旁白
  5223. 出镜角色:无
  5224. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5225. 画面类型:普通画面
  5226. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5227. "
  5228. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5229. 强制要求:\n
  5230. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5231. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5232. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5233. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5234. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5235. 普通要求:\n
  5236. 1.剧本名(必须生成)必须与文档内容高度相关
  5237. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5238. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5239. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5240. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5241. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5242. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5243. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5244. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5245. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5246. 4.$mappedArtStyle_prompt\n\n
  5247. 示例如下:\n
  5248. ###剧本名:西昆仑
  5249. ###故事梗概
  5250. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5251. ###剧本亮点
  5252. 亮点1:绝境奇药,生死一线
  5253. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5254. 亮点2:结拜兄妹,化解尴尬
  5255. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5256. 亮点3:纤发夺命,情愫暗涌
  5257. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5258. ###人物关系
  5259. 阿雪与梁萧之间存在兄妹之情。
  5260. ###核心矛盾
  5261. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5262. ###主体列表
  5263. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5264. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5265. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5266. 姿态:站立。}{{甜心小美}}
  5267. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5268. 全景,正面拍摄,青年女性,亚洲人。
  5269. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5270. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5271. 姿态:站立。}{{阳光青年}}
  5272. ###美术风格
  5273. 基础画风风格词:厚涂古风
  5274. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5275. ###场景列表
  5276. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5277. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5278. 无人物。}"];
  5279. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5280. $episode_count = $this->extractEpisodeNumber($prompt);
  5281. if ((int)getProp($anime, 'is_multi') !== 1) {
  5282. yield [
  5283. 'type' => 'done',
  5284. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5285. 'reasoning' => '',
  5286. 'usage' => []
  5287. ];
  5288. return;
  5289. }
  5290. if ($episode_count) {
  5291. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5292. $system_message = [
  5293. 'role' => 'system',
  5294. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5295. 强制要求:\n
  5296. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5297. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5298. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5299. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5300. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5301. 普通要求:\n
  5302. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5303. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5304. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5305. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5306. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5307. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5308. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5309. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5310. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5311. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5312. 示例如下:\n
  5313. ###剧本名:西昆仑
  5314. ###故事梗概
  5315. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5316. ###剧本亮点
  5317. 亮点1:绝境奇药,生死一线
  5318. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5319. 亮点2:结拜兄妹,化解尴尬
  5320. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5321. 亮点3:纤发夺命,情愫暗涌
  5322. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5323. ###人物关系
  5324. 阿雪与梁萧之间存在兄妹之情。
  5325. ###核心矛盾
  5326. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5327. ###主体列表
  5328. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5329. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5330. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5331. 姿态:站立。}{{甜心小美}}
  5332. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5333. 全景,正面拍摄,青年女性,亚洲人。
  5334. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5335. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5336. 姿态:站立。}{{阳光青年}}
  5337. ###美术风格
  5338. 基础画风风格词:厚涂古风
  5339. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5340. ###场景列表
  5341. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5342. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5343. 无人物。}
  5344. ###分集详细内容
  5345. ##第1章 重生
  5346. 我重生了。
  5347. 源于一个男人偏执的暗恋。
  5348. ##第2章 相救
  5349. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5350. 我眼睛扫向站在锅炉后的卞大伟。"
  5351. ];
  5352. // 构建消息
  5353. $messages = [
  5354. $system_message,
  5355. [
  5356. 'role' => 'user',
  5357. 'content' => "以下是文档内容:
  5358. {$content}
  5359. 用户问题:
  5360. {$question}"
  5361. ]
  5362. ];
  5363. }else {
  5364. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5365. // 构建消息
  5366. $messages = [
  5367. $system_message,
  5368. [
  5369. 'role' => 'user',
  5370. 'content' => "以下是文档内容:
  5371. {$content}
  5372. 用户问题:
  5373. {$question}"
  5374. ]
  5375. ];
  5376. }else {
  5377. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5378. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5379. return (array)$value;
  5380. })->toArray();
  5381. array_unshift($messages, $system_message);
  5382. $messages[] = [
  5383. 'role' => 'user',
  5384. 'content' => $prompt
  5385. ];
  5386. }
  5387. }
  5388. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5389. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5390. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5391. if ($model === 'deepseek-chat') {
  5392. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5393. $model = 'deepseek-v4-flash';
  5394. $thinkingMode = 'disabled';
  5395. } elseif ($model === 'deepseek-reasoner') {
  5396. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5397. $model = 'deepseek-v4-flash';
  5398. $thinkingMode = 'enabled';
  5399. }
  5400. $post_data = [
  5401. 'model' => $model,
  5402. 'messages' => $messages,
  5403. // 'max_tokens' => 8192,
  5404. 'temperature' => 0.7,
  5405. 'frequency_penalty' => 0,
  5406. 'presence_penalty' => 0,
  5407. 'response_format' => ['type' => 'text'],
  5408. 'thinking' => ['type' => $thinkingMode],
  5409. 'stream' => true // 启用流式输出
  5410. ];
  5411. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5412. // 根据模型类型选择调用方法
  5413. $fullContent = '';
  5414. $fullReasoningContent = '';
  5415. $usage = [];
  5416. // dd($post_data);
  5417. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5418. try {
  5419. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5420. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5421. } else if (in_array($model, $this->gpt_text_models)) {
  5422. // GPT-5.4 模型使用 TokenRouter API
  5423. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5424. } else if (in_array($model, $this->gemini_text_models)) {
  5425. // Gemini 模型使用 Gemini API
  5426. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5427. } else {
  5428. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5429. }
  5430. // 验证返回值类型
  5431. if (!is_iterable($streamGenerator)) {
  5432. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5433. dLog('deepseek')->error('方法名流式生成器无效', [
  5434. 'generator_type' => $errorType,
  5435. 'model' => $model,
  5436. // 添加其他上下文信息
  5437. ]);
  5438. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5439. 'type' => $errorType,
  5440. 'model' => $model
  5441. ]);
  5442. yield [
  5443. 'type' => 'error',
  5444. // 根据方法返回相应的空数据结构
  5445. 'answer' => '',
  5446. 'reasoning' => '',
  5447. 'usage' => [],
  5448. 'error' => '接口返回数据异常,请重新请求'
  5449. ];
  5450. return;
  5451. }
  5452. // 处理流式输出
  5453. foreach ($streamGenerator as $chunk) {
  5454. if (isset($chunk['type'])) {
  5455. if ($chunk['type'] === 'done') {
  5456. $fullContent = $chunk['full_content'];
  5457. $fullReasoningContent = $chunk['full_reasoning'];
  5458. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5459. } else {
  5460. yield $chunk;
  5461. }
  5462. }
  5463. }
  5464. } catch (\Exception $e) {
  5465. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5466. 'model' => $model,
  5467. 'trace' => $e->getTraceAsString()
  5468. ]);
  5469. logDB('deepseek', 'error', '方法名流式处理失败', [
  5470. 'error' => $e->getMessage(),
  5471. 'model' => $model
  5472. ]);
  5473. yield [
  5474. 'type' => 'error',
  5475. // 根据方法返回相应的空数据结构
  5476. 'answer' => '',
  5477. 'reasoning' => '',
  5478. 'usage' => [],
  5479. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5480. ];
  5481. return;
  5482. }
  5483. dLog('deepseek')->info('完整内容: '.$fullContent);
  5484. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5485. // 处理完整内容并返回最终结果
  5486. $script_arr = [];
  5487. if ($fullContent) {
  5488. $script_arr = handleScriptContent($fullContent);
  5489. dLog('deepseek')->info('解析内容', $script_arr);
  5490. logDB('deepseek', 'info', '解析内容', $script_arr);
  5491. }
  5492. if (empty($script_arr['roles'])) {
  5493. // 未生成剧本相关内容,保存对话记录并返回提示
  5494. dLog('deepseek')->info('未生成剧本相关的内容');
  5495. try {
  5496. $now = date('Y-m-d H:i:s');
  5497. // 保存对话记录
  5498. $records = [
  5499. [
  5500. 'uid' => $uid,
  5501. 'anime_id' => $anime_id,
  5502. 'sequence' => 0,
  5503. 'role' => 'user',
  5504. 'content' => $prompt,
  5505. 'created_at' => $now,
  5506. 'updated_at' => $now
  5507. ],
  5508. [
  5509. 'uid' => $uid,
  5510. 'anime_id' => $anime_id,
  5511. 'sequence' => 0,
  5512. 'role' => 'assistant',
  5513. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5514. 'created_at' => $now,
  5515. 'updated_at' => $now
  5516. ]
  5517. ];
  5518. DB::table('mp_anime_records')->insert($records);
  5519. } catch (\Exception $e) {
  5520. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5521. }
  5522. yield [
  5523. 'type' => 'done',
  5524. 'script' => [],
  5525. 'episode' => [],
  5526. 'answer' => $fullContent,
  5527. 'reasoning' => $fullReasoningContent,
  5528. 'usage' => $usage,
  5529. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5530. ];
  5531. return;
  5532. }
  5533. // 替换美术风格
  5534. if ($mappedArtStyle !== '') {
  5535. $script_arr['art_style'] = $mappedArtStyle;
  5536. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5537. }
  5538. if ($user_anime_name != '新剧本策划') {
  5539. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5540. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5541. // 确认对话名称唯一性
  5542. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5543. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5544. }
  5545. }else {
  5546. $anime_name = $user_anime_name;
  5547. }
  5548. $table_data = [
  5549. 'user_id' => $uid,
  5550. 'model' => $model,
  5551. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5552. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5553. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5554. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5555. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5556. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5557. 'art_style_type' => $input_art_style,
  5558. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5559. 'status' => '解析完成',
  5560. 'generate_status' => '待执行',
  5561. 'updated_at' => date('Y-m-d H:i:s')
  5562. ];
  5563. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5564. // 如果是修改集数,则将content内容更新(会改变原文)
  5565. if (isset($episode_count) && $episode_count > 0) {
  5566. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5567. $table_data['start_episode_sequence'] = 1;
  5568. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5569. }else {
  5570. // 如果需要生成原文内容,从script_arr中提取
  5571. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5572. $table_data['content'] = $script_arr['content'];
  5573. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5574. if (!$table_data['content']) {
  5575. yield [
  5576. 'type' => 'done',
  5577. 'script' => [],
  5578. 'episode' => [],
  5579. 'answer' => $fullContent,
  5580. 'reasoning' => $fullReasoningContent,
  5581. 'usage' => $usage,
  5582. 'error' => '未生成剧本内容,请调整提示词再试'
  5583. ];
  5584. return;
  5585. }
  5586. }
  5587. if (isset($table_data['content']) && $table_data['content']) {
  5588. $chapters = splitContent($table_data['content']);
  5589. $chapter_count = count($chapters);
  5590. if ($chapter_count > 0) {
  5591. $table_data['start_episode_sequence'] = 1;
  5592. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5593. }
  5594. }
  5595. }
  5596. $single_episode = [];
  5597. try {
  5598. DB::beginTransaction();
  5599. $now = date('Y-m-d H:i:s');
  5600. // 更新动漫大纲
  5601. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5602. if (!$boolen) {
  5603. dLog('deepseek')->info('对话修改失败', $table_data);
  5604. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5605. Utils::throwError('20003:对话修改失败');
  5606. }
  5607. // 保存对话记录
  5608. $records = [
  5609. [
  5610. 'uid' => $uid,
  5611. 'anime_id' => $anime_id,
  5612. 'sequence' => 0,
  5613. 'role' => 'user',
  5614. 'content' => $prompt,
  5615. 'created_at' => $now,
  5616. 'updated_at' => $now
  5617. ],
  5618. [
  5619. 'uid' => $uid,
  5620. 'anime_id' => $anime_id,
  5621. 'sequence' => 0,
  5622. 'role' => 'assistant',
  5623. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5624. 'content' => $fullContent,
  5625. 'created_at' => $now,
  5626. 'updated_at' => $now
  5627. ]
  5628. ];
  5629. // 保存对话记录
  5630. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5631. if (!$boolen3) {
  5632. Utils::throwError('20003:对话记录保存失败');
  5633. }
  5634. // 单剧集模式:生成并保存剧集信息
  5635. if ($is_single) {
  5636. $anime_name = getProp($anime, 'anime_name', '未命名');
  5637. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5638. if (empty($episode_arr['acts'])) {
  5639. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5640. }
  5641. $saveResult = $this->saveEpisodeVersionData(
  5642. $anime_id,
  5643. 1,
  5644. $episode_arr,
  5645. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5646. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5647. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5648. null,
  5649. null,
  5650. false,
  5651. $content,
  5652. $now
  5653. );
  5654. $single_episode = $saveResult['episode'];
  5655. $episode_id = $saveResult['episode_id'];
  5656. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5657. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5658. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5659. 'props' => json_encode($saveResult['merged_props'], 256),
  5660. 'updated_at' => $now
  5661. ]);
  5662. if ($boolen5 === false) {
  5663. Utils::throwError('20003:单剧集主表资源同步失败');
  5664. }
  5665. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5666. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5667. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5668. $episode_record_content = '确认分镜大纲';
  5669. if ($content !== '') {
  5670. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5671. }
  5672. $episode_records = [
  5673. [
  5674. 'uid' => $uid,
  5675. 'anime_id' => $anime_id,
  5676. 'role' => 'user',
  5677. 'content' => $episode_record_content,
  5678. 'sequence' => 1,
  5679. 'episode_id' => $episode_id,
  5680. 'created_at' => $now,
  5681. 'updated_at' => $now
  5682. ],
  5683. [
  5684. 'uid' => $uid,
  5685. 'anime_id' => $anime_id,
  5686. 'role' => 'assistant',
  5687. 'content' => $fullContent,
  5688. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5689. 'sequence' => 1,
  5690. 'episode_id' => $episode_id,
  5691. 'created_at' => $now,
  5692. 'updated_at' => $now
  5693. ]
  5694. ];
  5695. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5696. if (!$boolen4) {
  5697. Utils::throwError('20003:单剧集分镜记录保存失败');
  5698. }
  5699. }
  5700. }catch (\Exception $e) {
  5701. DB::rollBack();
  5702. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5703. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5704. yield [
  5705. 'type' => 'done',
  5706. 'answer' => $fullContent,
  5707. 'reasoning' => $fullReasoningContent,
  5708. 'usage' => $usage,
  5709. 'error' => $e->getMessage(),
  5710. ];
  5711. return;
  5712. }
  5713. DB::commit();
  5714. dLog('deepseek')->info('保存完毕');
  5715. if ($is_single && !empty($single_episode)) {
  5716. // $this->batchSetGlobalRoleImg([
  5717. // 'anime_id' => $anime_id,
  5718. // ]);
  5719. // $this->batchSetGlobalSceneImg([
  5720. // 'anime_id' => $anime_id,
  5721. // ]);
  5722. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5723. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5724. }
  5725. $table_data['anime_id'] = $anime_id;
  5726. $table_data['roles'] = json_decode($table_data['roles'], true);
  5727. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5728. unset($table_data['updated_at']);
  5729. unset($table_data['status']);
  5730. yield [
  5731. 'type' => 'done',
  5732. 'script' => $table_data,
  5733. 'episode' => $single_episode,
  5734. 'answer' => $fullContent,
  5735. 'reasoning' => $fullReasoningContent,
  5736. 'usage' => $usage
  5737. ];
  5738. }
  5739. public function chat($data) {
  5740. $uid = Site::getUid();
  5741. $anime_id = getProp($data, 'anime_id');
  5742. $file = getProp($data, 'file');
  5743. $content = getProp($data, 'content', '');
  5744. $bid = getProp($data, 'bid', 0);
  5745. $script_id = getProp($data, 'script_id', 0);
  5746. $episode_number = getProp($data, 'episode_number', 1);
  5747. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5748. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5749. if (!$anime) Utils::throwError('20003:该对话不存在!');
  5750. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  5751. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  5752. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  5753. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  5754. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  5755. $roles = is_array($roles) ? $roles : [];
  5756. $scenes = is_array($scenes) ? $scenes : [];
  5757. // 获取最后一集序号
  5758. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  5759. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  5760. // 转换主体列表和场景列表的格式
  5761. // 获取参考主体或场景
  5762. if ((int)$episode_number === 1) {
  5763. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  5764. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  5765. }else {
  5766. $prev_episode_number = $episode_number - 1;
  5767. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  5768. }
  5769. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  5770. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  5771. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  5772. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  5773. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5774. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5775. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5776. 中年女:邻居阿姨
  5777. 老年男:幽默大爷
  5778. 老年女:婆婆
  5779. 萌娃:奶气萌娃";
  5780. if ($roles_content) {
  5781. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  5782. 主体范围:\n {$roles_content}\n
  5783. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  5784. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5785. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5786. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5787. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5788. }else {
  5789. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5790. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5791. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5792. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5793. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5794. }
  5795. if ($scenes_content) {
  5796. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  5797. 场景范围:\n {$scenes_content}\n
  5798. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  5799. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5800. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5801. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5802. }else {
  5803. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5804. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5805. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5806. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5807. }
  5808. // 提取文件内容
  5809. if ($file) {
  5810. $uploaded_content = $this->extractFileContent($file);
  5811. if (!$uploaded_content) {
  5812. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5813. }
  5814. } elseif ($script_id) {
  5815. $uploaded_content = $this->getContentByScriptId($script_id);
  5816. if (!$uploaded_content) {
  5817. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5818. }
  5819. } elseif ($bid) {
  5820. $uploaded_content = $this->getContentByBid($bid);
  5821. if (!$uploaded_content) {
  5822. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5823. }
  5824. } elseif ($content) {
  5825. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  5826. }
  5827. // elseif ($prompt) {
  5828. // $uploaded_content = filterContent($prompt);
  5829. // }
  5830. else {
  5831. $uploaded_content = '';
  5832. }
  5833. $input_art_style = getProp($anime, 'art_style');
  5834. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5835. // 美术风格
  5836. if (!$mappedArtStyle) {
  5837. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5838. }else {
  5839. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5840. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5841. }else {
  5842. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5843. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5844. }
  5845. }
  5846. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5847. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5848. // 强制要求:
  5849. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5850. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5851. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5852. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  5853. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  5854. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  5855. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  5856. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  5857. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  5858. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  5859. // - 分镜要和场景列表、人物主体保持一致\n
  5860. // 普通要求:
  5861. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5862. // {$role_demo}
  5863. // {$scene_demo}
  5864. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5865. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5866. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5867. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5868. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5869. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5870. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5871. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5872. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5873. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5874. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5875. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5876. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5877. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5878. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5879. // 5.$mappedArtStyle_prompt\n\n
  5880. // 示例格式:\n
  5881. // 第1集:隐形的守护者
  5882. // ###故事梗概
  5883. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5884. // ###美术风格
  5885. // 基础画风风格词:韩漫二次元
  5886. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5887. // ###主体列表
  5888. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5889. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5890. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5891. // ###场景列表
  5892. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5893. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5894. // 无人物。}
  5895. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5896. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5897. // 无人物。}
  5898. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5899. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5900. // 无人物。}
  5901. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5902. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5903. // 无人物。}
  5904. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5905. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5906. // 无人物。}
  5907. // ###分镜剧本
  5908. // ##第1幕:徐家老旧厨房 白天 室内
  5909. // 分镜1
  5910. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5911. // 场景:徐家老旧厨房
  5912. // 构图设计:全景,低角度仰视
  5913. // 运镜调度:手持拍摄
  5914. // 配音角色:旁白
  5915. // 出镜角色:许芸-校服装、徐母
  5916. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5917. // 画面类型:普通画面
  5918. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5919. // 分镜2
  5920. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5921. // 场景:徐家老旧厨房
  5922. // 构图设计:近景,徐母面部特写
  5923. // 运镜调度:固定镜头
  5924. // 配音角色:徐母
  5925. // 出镜角色:徐母
  5926. // 台词内容:问我夜不归宿死哪儿去了。
  5927. // 画面类型:对口型
  5928. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5929. // ##第2幕:徐家简陋客厅 黄昏 室内
  5930. // 分镜3
  5931. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5932. // 场景:徐家简陋客厅
  5933. // 构图设计:全景,景深虚化
  5934. // 运镜调度:固定镜头
  5935. // 配音角色:旁白
  5936. // 出镜角色:无
  5937. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5938. // 画面类型:普通画面
  5939. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5940. // 分镜4
  5941. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5942. // 场景:徐家简陋客厅
  5943. // 构图设计:特写,火车票
  5944. // 运镜调度:固定镜头
  5945. // 配音角色:旁白
  5946. // 出镜角色:无
  5947. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5948. // 画面类型:普通画面
  5949. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5950. // \n\n";
  5951. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  5952. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  5953. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  5954. 普通要求:
  5955. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5956. {$role_demo}
  5957. {$scene_demo}
  5958. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5959. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5960. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5961. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5962. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5963. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5964. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5965. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5966. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5967. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5968. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5969. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5970. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5971. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5972. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5973. 5.$mappedArtStyle_prompt
  5974. 6.《情绪-视听语言映射表》:
  5975. 6.1 场景空间与时间心理学 (Scene & Temporality)
  5976. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5977. -----|---------|------------|----------------
  5978. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  5979. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  5980. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  5981. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  5982. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  5983. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5984. -----|---------|------------|----------------
  5985. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  5986. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  5987. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  5988. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  5989. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  5990. --------|---------|--------------|-------------
  5991. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  5992. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  5993. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  5994. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  5995. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5996. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5997. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5998. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5999. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6000. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6001. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6002. -----|---------|------------|------------
  6003. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6004. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6005. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6006. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6007. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6008. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6009. --------|---------|--------------|----------
  6010. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6011. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6012. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6013. 6.6 声音设计与潜意识影响 (Soundscape)
  6014. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6015. -----|---------|------------|------------------
  6016. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6017. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6018. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6019. 理论基石:
  6020. - The Five C's of Cinematography by Joseph V. Mascelli
  6021. - Film Art: An Introduction by David Bordwell
  6022. - Sight, Sound, Motion by Herbert Zettl
  6023. - Notes on the Cinematograph by Robert Bresson
  6024. \n\n
  6025. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6026. 示例格式:\n
  6027. 第1集:隐形的守护者
  6028. ###故事梗概
  6029. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6030. ###美术风格
  6031. 基础画风风格词:韩漫二次元
  6032. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6033. ###主体列表
  6034. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6035. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6036. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6037. ###场景列表
  6038. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6039. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6040. 无人物。}
  6041. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6042. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6043. 无人物。}
  6044. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6045. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6046. 无人物。}
  6047. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6048. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6049. 无人物。}
  6050. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6051. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6052. 无人物。}
  6053. ###分镜剧本
  6054. ##第1幕:徐家老旧厨房 白天 室内
  6055. 分镜1
  6056. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6057. 场景:徐家老旧厨房
  6058. 构图设计:全景,低角度仰视
  6059. 运镜调度:手持拍摄
  6060. 配音角色:旁白
  6061. 出镜角色:许芸-校服装、徐母
  6062. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6063. 画面类型:普通画面
  6064. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6065. 分镜2
  6066. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6067. 场景:徐家老旧厨房
  6068. 构图设计:近景,徐母面部特写
  6069. 运镜调度:固定镜头
  6070. 配音角色:徐母
  6071. 出镜角色:徐母
  6072. 台词内容:问我夜不归宿死哪儿去了。
  6073. 画面类型:对口型
  6074. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6075. ##第2幕:徐家简陋客厅 黄昏 室内
  6076. 分镜3
  6077. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6078. 场景:徐家简陋客厅
  6079. 构图设计:全景,景深虚化
  6080. 运镜调度:固定镜头
  6081. 配音角色:旁白
  6082. 出镜角色:无
  6083. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6084. 画面类型:普通画面
  6085. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6086. 分镜4
  6087. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6088. 场景:徐家简陋客厅
  6089. 构图设计:特写,火车票
  6090. 运镜调度:固定镜头
  6091. 配音角色:旁白
  6092. 出镜角色:无
  6093. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6094. 画面类型:普通画面
  6095. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6096. \n\n";
  6097. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6098. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6099. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6100. $prompt = $origin_prompt;
  6101. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6102. // 获取章节内容
  6103. $full_content = getProp($anime, 'content');
  6104. if ($uploaded_content) {
  6105. $full_content = $uploaded_content;
  6106. }
  6107. // 根据章节内容拆分章节
  6108. $chapters = splitContent($full_content);
  6109. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6110. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6111. $messages = [];
  6112. if ($prompt == '确认分镜大纲') {
  6113. // 暂时保留
  6114. $content = $chapter_content;
  6115. if ($is_single) $content = $full_content; // 单剧集使用全文
  6116. if (!$content) {
  6117. Utils::throwError('20003:章节内容无法获取,请确认');
  6118. }
  6119. $question = $is_single
  6120. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6121. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6122. // 构建消息
  6123. $messages[] =
  6124. [
  6125. 'role' => 'user',
  6126. 'content' => $question
  6127. ];
  6128. }else if ($prompt == '继续策划下一集') {
  6129. if ($is_single) {
  6130. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6131. }
  6132. $content = $chapter_content;
  6133. if (!$content) {
  6134. Utils::throwError('20003:章节内容无法获取,请确认');
  6135. }
  6136. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6137. // 获取上一集最后记录
  6138. $prev_sequence = $episode_number - 1;
  6139. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6140. // 构建消息
  6141. $messages[] =
  6142. [
  6143. 'role' => 'user',
  6144. 'content' => $question
  6145. ];
  6146. }else {
  6147. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6148. if (!$content) {
  6149. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6150. }
  6151. if (!$content) {
  6152. Utils::throwError('20003:章节内容无法获取,请确认');
  6153. }
  6154. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6155. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6156. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6157. if ($origin_prompt) {
  6158. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6159. }
  6160. $messages[] =
  6161. [
  6162. 'role' => 'user',
  6163. 'content' => $question
  6164. ];
  6165. }
  6166. // 处理文本模型
  6167. $model = getProp($data, 'model');
  6168. if (!$model) {
  6169. // 用户没有输入,从anime表获取
  6170. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6171. $model = getProp($anime, 'model');
  6172. if (!$model) {
  6173. // anime表也没有,使用默认值
  6174. $model = 'doubao-seed-2-0-mini-260215';
  6175. }
  6176. }
  6177. // 验证模型是否在可用模型表中
  6178. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6179. $model = 'doubao-seed-2-0-mini-260215';
  6180. }
  6181. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6182. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6183. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6184. if ($model === 'deepseek-chat') {
  6185. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6186. $model = 'deepseek-v4-flash';
  6187. $thinkingMode = 'disabled';
  6188. } elseif ($model === 'deepseek-reasoner') {
  6189. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6190. $model = 'deepseek-v4-flash';
  6191. $thinkingMode = 'enabled';
  6192. }
  6193. $post_data = [
  6194. 'model' => $model,
  6195. 'messages' => $messages,
  6196. // 'max_tokens' => 8192,
  6197. 'temperature' => 0.2,
  6198. 'frequency_penalty' => 0,
  6199. 'presence_penalty' => 0,
  6200. 'response_format' => ['type' => 'text'],
  6201. 'thinking' => ['type' => $thinkingMode],
  6202. 'stream' => true // 启用流式输出
  6203. ];
  6204. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6205. // 根据模型类型选择调用方法
  6206. $fullContent = '';
  6207. $fullReasoningContent = '';
  6208. $usage = [];
  6209. try {
  6210. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6211. // DeepSeek 官方模型使用 DeepSeek API
  6212. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6213. } else if (in_array($model, $this->gpt_text_models)) {
  6214. // GPT-5.4 模型使用 TokenRouter API
  6215. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6216. } else if (in_array($model, $this->gemini_text_models)) {
  6217. // Gemini 模型使用 Gemini API
  6218. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6219. } else {
  6220. // 其他模型使用火山引擎API
  6221. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6222. }
  6223. // 验证返回值类型
  6224. if (!is_iterable($streamGenerator)) {
  6225. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6226. dLog('deepseek')->error('chat流式生成器无效', [
  6227. 'generator_type' => $errorType,
  6228. 'model' => $model,
  6229. 'anime_id' => $anime_id,
  6230. 'episode_number' => $episode_number
  6231. ]);
  6232. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6233. 'type' => $errorType,
  6234. 'model' => $model
  6235. ]);
  6236. yield [
  6237. 'type' => 'error',
  6238. 'episode' => [],
  6239. 'answer' => '',
  6240. 'reasoning' => '',
  6241. 'usage' => [],
  6242. 'error' => '接口返回数据异常,请重新请求'
  6243. ];
  6244. return;
  6245. }
  6246. // 处理流式输出
  6247. foreach ($streamGenerator as $chunk) {
  6248. if (isset($chunk['type'])) {
  6249. if ($chunk['type'] === 'done') {
  6250. // 最终结果
  6251. $fullContent = $chunk['full_content'];
  6252. $fullReasoningContent = $chunk['full_reasoning'];
  6253. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6254. } else {
  6255. // 逐块yield数据
  6256. yield $chunk;
  6257. }
  6258. }
  6259. }
  6260. } catch (\Exception $e) {
  6261. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6262. 'model' => $model,
  6263. 'anime_id' => $anime_id,
  6264. 'episode_number' => $episode_number,
  6265. 'trace' => $e->getTraceAsString()
  6266. ]);
  6267. logDB('deepseek', 'error', 'chat流式处理失败', [
  6268. 'error' => $e->getMessage(),
  6269. 'model' => $model
  6270. ]);
  6271. yield [
  6272. 'type' => 'error',
  6273. 'episode' => [],
  6274. 'answer' => '',
  6275. 'reasoning' => '',
  6276. 'usage' => [],
  6277. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6278. ];
  6279. return;
  6280. }
  6281. dLog('deepseek')->info('完整内容: '.$fullContent);
  6282. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6283. // 处理完整内容并返回最终结果
  6284. $episode_arr = handleEpisodeContent($fullContent);
  6285. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6286. if (empty($episode_arr['acts'])) {
  6287. // 未生成剧本相关内容,保存对话记录并返回提示
  6288. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6289. try {
  6290. $now = date('Y-m-d H:i:s');
  6291. // 保存对话记录
  6292. $records = [
  6293. [
  6294. 'uid' => $uid,
  6295. 'anime_id' => $anime_id,
  6296. 'sequence' => $episode_number,
  6297. 'role' => 'user',
  6298. 'content' => $prompt,
  6299. 'created_at' => $now,
  6300. 'updated_at' => $now
  6301. ],
  6302. [
  6303. 'uid' => $uid,
  6304. 'anime_id' => $anime_id,
  6305. 'sequence' => $episode_number,
  6306. 'role' => 'assistant',
  6307. 'content' => $fullContent,
  6308. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6309. 'created_at' => $now,
  6310. 'updated_at' => $now
  6311. ]
  6312. ];
  6313. DB::table('mp_anime_records')->insert($records);
  6314. } catch (\Exception $e) {
  6315. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6316. }
  6317. yield [
  6318. 'type' => 'done',
  6319. 'episode' => [],
  6320. 'answer' => $fullContent,
  6321. 'reasoning' => $fullReasoningContent,
  6322. 'usage' => $usage,
  6323. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6324. ];
  6325. return;
  6326. }
  6327. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6328. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6329. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6330. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6331. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6332. $existing_props = is_array($existing_props) ? $existing_props : [];
  6333. $now = date('Y-m-d H:i:s');
  6334. try {
  6335. DB::beginTransaction();
  6336. $saveResult = $this->saveEpisodeVersionData(
  6337. $anime_id,
  6338. $episode_number,
  6339. $episode_arr,
  6340. $existing_roles,
  6341. $existing_scenes,
  6342. $existing_props,
  6343. $current_episode,
  6344. $base_episode,
  6345. $is_regenerate_version,
  6346. $content,
  6347. $now
  6348. );
  6349. $episode = $saveResult['episode'];
  6350. $episode_id = $saveResult['episode_id'];
  6351. $merged_roles = $saveResult['merged_roles'];
  6352. $merged_scenes = $saveResult['merged_scenes'];
  6353. $merged_props = $saveResult['merged_props'];
  6354. $record_content = $origin_prompt;
  6355. if ($uploaded_content !== '') {
  6356. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6357. }
  6358. $records = [
  6359. [
  6360. 'uid' => $uid,
  6361. 'anime_id' => $anime_id,
  6362. 'role' => 'user',
  6363. 'content' => $record_content,
  6364. 'sequence' => $episode_number,
  6365. 'episode_id' => $episode_id,
  6366. 'created_at' => $now,
  6367. 'updated_at' => $now
  6368. ],
  6369. [
  6370. 'uid' => $uid,
  6371. 'anime_id' => $anime_id,
  6372. 'role' => 'assistant',
  6373. 'content' => $fullContent,
  6374. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6375. 'sequence' => $episode_number,
  6376. 'episode_id' => $episode_id,
  6377. 'created_at' => $now,
  6378. 'updated_at' => $now
  6379. ]
  6380. ];
  6381. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6382. if (!$boolen4) {
  6383. Utils::throwError('20003:对话记录保存失败');
  6384. }
  6385. // 保存模型和内容到anime表
  6386. $update_anime_data = [
  6387. 'model' => $model,
  6388. 'updated_at' => $now
  6389. ];
  6390. if ($uploaded_content) {
  6391. $update_anime_data['content'] = $uploaded_content;
  6392. }
  6393. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6394. }catch (\Exception $e) {
  6395. DB::rollBack();
  6396. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6397. yield [
  6398. 'type' => 'done',
  6399. 'answer' => $fullContent,
  6400. 'reasoning' => $fullReasoningContent,
  6401. 'usage' => $usage,
  6402. 'error' => $e->getMessage(),
  6403. ];
  6404. return;
  6405. }
  6406. DB::commit();
  6407. if ($is_global_generate_pics) {
  6408. // // 批量生成全局角色图片
  6409. // $this->batchSetGlobalRoleImg([
  6410. // 'anime_id' => $anime_id,
  6411. // ], true);
  6412. // // 批量生成全局场景图片
  6413. // $this->batchSetGlobalSceneImg([
  6414. // 'anime_id' => $anime_id,
  6415. // ], true);
  6416. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6417. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6418. }
  6419. $episode['episode_id'] = $episode_id;
  6420. $episode['roles'] = $merged_roles;
  6421. $episode['scenes'] = $merged_scenes;
  6422. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6423. yield [
  6424. 'type' => 'done',
  6425. 'episode' => $episode,
  6426. 'answer' => $fullContent,
  6427. 'reasoning' => $fullReasoningContent,
  6428. 'usage' => $usage
  6429. ];
  6430. }
  6431. public function addChatForAce($data) {
  6432. $uid = Site::getUid();
  6433. $anime_id = getProp($data, 'anime_id');
  6434. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6435. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6436. if (!$anime) Utils::throwError('20003:对话不存在');
  6437. $file = getProp($data, 'file');
  6438. $content = getProp($data, 'content', '');
  6439. $bid = getProp($data, 'bid', 0);
  6440. $script_id = getProp($data, 'script_id', 0);
  6441. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6442. $prompt = getProp($data, 'prompt');
  6443. $is_multi = getProp($anime, 'is_multi');
  6444. $is_single = (int)$is_multi !== 1;
  6445. $extra_products = getProp($data, 'products', []);
  6446. if (!$extra_products) {
  6447. $extra_products = getProp($anime, 'extra_products');
  6448. if ($extra_products) {
  6449. $extra_products = json_decode($extra_products, true);
  6450. }else {
  6451. $extra_products = [];
  6452. }
  6453. }else {
  6454. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6455. }
  6456. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6457. $anime_script_id = getProp($anime, 'script_id');
  6458. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6459. $cpid = Site::getCpid();
  6460. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6461. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6462. ->where('mapping.script_id', $anime_script_id)
  6463. ->where('product.cpid', $cpid)
  6464. ->where('product.is_deleted', 0);
  6465. $mappings = $script_products_mappings->select(
  6466. 'mapping.product_id',
  6467. 'mapping.episode_number',
  6468. 'product.product_name',
  6469. 'product.type',
  6470. 'product.product',
  6471. 'product.pic_prompt',
  6472. 'product.url',
  6473. 'product.pic_task_id',
  6474. 'product.pic_task_status',
  6475. 'product.three_view_image_url'
  6476. )
  6477. ->get();
  6478. // 按 product_id 分组,合并 episode_number
  6479. $productMap = [];
  6480. foreach ($mappings as $item) {
  6481. $product_id = $item->product_id;
  6482. $product_name = $item->product_name;
  6483. // 处理product_name两边的符号
  6484. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6485. if (!isset($productMap[$product_id])) {
  6486. $productMap[$product_id] = [
  6487. 'product_id' => $product_id,
  6488. 'product_name' => $product_name,
  6489. 'type' => (int)$item->type,
  6490. 'product' => (int)$item->product,
  6491. 'pic_prompt' => $item->pic_prompt,
  6492. 'url' => $item->url,
  6493. 'pic_task_id' => $item->pic_task_id,
  6494. 'pic_task_status' => $item->pic_task_status,
  6495. 'episode_numbers' => [],
  6496. ];
  6497. }
  6498. // 添加 episode_number(去重)
  6499. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6500. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6501. }
  6502. }
  6503. // 将查询到的剧本资产合并到extra_products中
  6504. // 先构建extra_products的索引(以product_id为key,用于去重)
  6505. $extraProductsMap = [];
  6506. foreach ($extra_products as $item) {
  6507. $key = getProp($item, 'product_id');
  6508. if ($key) {
  6509. $extraProductsMap[$key] = $item;
  6510. }
  6511. }
  6512. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6513. foreach ($productMap as $product) {
  6514. $product_id = $product['product_id'];
  6515. // 如果不存在则添加(不带episode_number信息)
  6516. if (!isset($extraProductsMap[$product_id])) {
  6517. $extraProductsMap[$product_id] = [
  6518. 'product_id' => $product['product_id'],
  6519. 'product_name' => $product['product_name'],
  6520. 'type' => $product['type'],
  6521. 'product' => $product['product'],
  6522. 'pic_prompt' => $product['pic_prompt'],
  6523. 'url' => $product['url'],
  6524. 'pic_task_id' => $product['pic_task_id'],
  6525. 'pic_task_status' => $product['pic_task_status'],
  6526. ];
  6527. }
  6528. }
  6529. // 重新赋值给extra_products
  6530. $extra_products = array_values($extraProductsMap);
  6531. }
  6532. $user_anime_name = getProp($anime, 'anime_name');
  6533. // 处理提示词
  6534. if ($prompt && $extra_products) {
  6535. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6536. foreach($extra_products as $item) {
  6537. $product_name = getProp($item, 'product_name');
  6538. if ($product_name) {
  6539. // 替换 {product_name} 为 product_name
  6540. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6541. }
  6542. }
  6543. }
  6544. // 处理文本模型
  6545. $model = getProp($data, 'model');
  6546. if (!$model) {
  6547. // 用户没有输入,从anime表获取
  6548. $model = getProp($anime, 'model');
  6549. if (!$model) {
  6550. // anime表也没有,使用默认值
  6551. $model = 'deepseek-v4-pro';
  6552. }
  6553. }
  6554. // 验证模型是否在可用模型表中
  6555. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6556. $model = 'deepseek-v4-pro';
  6557. }
  6558. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6559. if ($prompt) {
  6560. $question .= "本次修改要求如下:\n{$prompt}";
  6561. }
  6562. // if (!$file && !$content && !$bid) {
  6563. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6564. // }
  6565. // 提取文件内容
  6566. if ($file) {
  6567. $content = $this->extractFileContent($file);
  6568. if (!$content) {
  6569. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6570. }
  6571. } elseif ($script_id) {
  6572. $content = $this->getContentByScriptId($script_id);
  6573. if (!$content) {
  6574. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6575. }
  6576. } elseif ($bid) {
  6577. $content = $this->getContentByBid($bid);
  6578. if (!$content) {
  6579. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6580. }
  6581. } elseif ($content) {
  6582. $content = filterContent($content);
  6583. } else {
  6584. $content = getProp($anime, 'content');
  6585. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6586. $need_generate_content = true;
  6587. }
  6588. }
  6589. // 美术风格
  6590. $input_art_style = getProp($data, 'art_style');
  6591. if (!$input_art_style) {
  6592. $mappedArtStyle = getProp($anime, 'art_style');
  6593. }else {
  6594. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6595. }
  6596. // 判断是否需要生成原文内容
  6597. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6598. // 如果需要生成原文内容,添加额外的要求
  6599. $content_generation_requirement = $need_generate_content
  6600. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6601. : "";
  6602. // 美术风格
  6603. if (!$mappedArtStyle) {
  6604. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6605. }else {
  6606. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6607. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6608. }else {
  6609. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6610. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6611. }
  6612. }
  6613. // 构建主体、场景和道具提示词
  6614. $extra_role_prompt = "\n";
  6615. $extra_scene_prompt = "\n";
  6616. $extra_prop_prompt = "\n";
  6617. $ref_products = []; // 参考资产
  6618. if ($extra_products) {
  6619. foreach($extra_products as $item) {
  6620. $product = getProp($item, 'product');
  6621. $product_name = getProp($item, 'product_name');
  6622. if ($product_name == '旁白') continue;
  6623. $ref_products[$product_name] = $item;
  6624. $pic_prompt = getProp($item, 'pic_prompt');
  6625. if ((int)$product === 1) {
  6626. // 拼接角色信息
  6627. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6628. } elseif ((int)$product === 2) {
  6629. // 拼接场景信息
  6630. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6631. } elseif ((int)$product === 3) {
  6632. // 拼接道具信息
  6633. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6634. }
  6635. }
  6636. // 优化提示词,融入剧本
  6637. if (!empty(trim($extra_role_prompt))) {
  6638. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6639. }
  6640. if (!empty(trim($extra_scene_prompt))) {
  6641. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6642. }
  6643. if (!empty(trim($extra_prop_prompt))) {
  6644. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6645. }
  6646. }
  6647. if ($anime_script_id && $is_single) {
  6648. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6649. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6650. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6651. }else {
  6652. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6653. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6654. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6655. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6656. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6657. {$extra_role_prompt}";
  6658. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6659. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6660. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6661. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6662. {$extra_scene_prompt}";
  6663. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6664. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6665. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6666. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6667. {$extra_prop_prompt}";
  6668. }
  6669. $systemPrompt = $is_single
  6670. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6671. 强制要求:
  6672. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6673. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6674. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6675. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6676. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6677. 普通要求:
  6678. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6679. $role_demo
  6680. $scene_demo
  6681. $prop_demo
  6682. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6683. 5.1片段分割逻辑(优先级从高到低):
  6684. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6685. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6686. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6687. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6688. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6689. - 片段数量格式为: 片段数量:8
  6690. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6691. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6692. 5.3分镜结构:每个分镜包含以下字段:
  6693. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6694. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6695. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6696. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6697. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6698. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6699. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6700. - 运镜:场景+画面描述+运镜
  6701. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6702. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6703. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6704. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6705. 6.{$mappedArtStyle_prompt}\n\n
  6706. 示例如下:\n
  6707. ###剧本名:西昆仑
  6708. ###故事梗概
  6709. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6710. ###剧本亮点
  6711. 亮点1:绝境奇药,生死一线
  6712. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6713. 亮点2:结拜兄妹,化解尴尬
  6714. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6715. 亮点3:纤发夺命,情愫暗涌
  6716. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6717. ###人物关系
  6718. 阿雪与梁萧之间存在兄妹之情。
  6719. ###核心矛盾
  6720. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6721. ###主体列表
  6722. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6723. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6724. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6725. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6726. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6727. 全景,正面拍摄,青年女性,亚洲人。
  6728. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6729. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6730. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6731. ###美术风格
  6732. 基础画风风格词:厚涂古风
  6733. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6734. ###场景列表
  6735. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6736. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6737. 无人物。}
  6738. ###分段剧本
  6739. 片段数量:8
  6740. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6741. ##片段1
  6742. 时长:12s
  6743. 分镜1
  6744. 出场角色:刀疤脸
  6745. 场景:边境小镇街道
  6746. 出场道具:酒杯-高脚杯
  6747. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6748. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6749. 配音台词:
  6750. 背景音效:
  6751. 分镜2
  6752. 出场角色:刀疤脸
  6753. 场景:悦来酒馆
  6754. 出场道具:酒杯-高脚杯
  6755. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6756. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6757. 配音台词:
  6758. 背景音效:
  6759. 分镜3
  6760. 出场角色:刀疤脸
  6761. 场景:悦来酒馆
  6762. 出场道具:酒杯-高脚杯
  6763. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6764. 运镜:从中景推向令牌特写。
  6765. 配音台词:
  6766. 背景音效:
  6767. 分镜4
  6768. 出场角色:刀疤脸
  6769. 场景:悦来酒馆
  6770. 出场道具:酒杯-高脚杯
  6771. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6772. 运镜:极速推向酒水溅起的瞬间。
  6773. 配音台词:
  6774. 背景音效:
  6775. 分镜5
  6776. 出场角色:刀疤脸
  6777. 场景:悦来酒馆
  6778. 出场道具:酒杯-高脚杯
  6779. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6780. 运镜:固定机位,利用倾斜构图制造压迫感。
  6781. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6782. 背景音效:
  6783. \n\n"
  6784. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6785. 强制要求:\n
  6786. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6787. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6788. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6789. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6790. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6791. 普通要求:\n
  6792. 1.剧本名(必须生成)必须与文档内容高度相关
  6793. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6794. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6795. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6796. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6797. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6798. {$extra_role_prompt}
  6799. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6800. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6801. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6802. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6803. {$extra_scene_prompt}
  6804. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6805. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6806. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6807. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6808. {$extra_prop_prompt}
  6809. 5.{$mappedArtStyle_prompt}\n\n
  6810. 示例如下:\n
  6811. ###剧本名:西昆仑
  6812. ###故事梗概
  6813. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6814. ###剧本亮点
  6815. 亮点1:绝境奇药,生死一线
  6816. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6817. 亮点2:结拜兄妹,化解尴尬
  6818. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6819. 亮点3:纤发夺命,情愫暗涌
  6820. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6821. ###人物关系
  6822. 阿雪与梁萧之间存在兄妹之情。
  6823. ###核心矛盾
  6824. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6825. ###主体列表
  6826. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6827. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6828. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6829. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6830. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6831. 全景,正面拍摄,青年女性,亚洲人。
  6832. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6833. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6834. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6835. ###美术风格
  6836. 基础画风风格词:厚涂古风
  6837. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6838. ###场景列表
  6839. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6840. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6841. 无人物。}
  6842. ###道具列表
  6843. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  6844. // 构建消息
  6845. $messages = [
  6846. [
  6847. 'role' => 'system',
  6848. 'content' => $systemPrompt
  6849. ],
  6850. [
  6851. 'role' => 'user',
  6852. 'content' => "以下是文档内容:
  6853. {$content}
  6854. 用户问题:
  6855. {$question}"
  6856. ]
  6857. ];
  6858. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6859. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6860. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6861. if ($model === 'deepseek-chat') {
  6862. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6863. $model = 'deepseek-v4-flash';
  6864. $thinkingMode = 'disabled';
  6865. } elseif ($model === 'deepseek-reasoner') {
  6866. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6867. $model = 'deepseek-v4-flash';
  6868. $thinkingMode = 'enabled';
  6869. }
  6870. $post_data = [
  6871. 'model' => $model,
  6872. 'messages' => $messages,
  6873. // 'max_tokens' => 8192,
  6874. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6875. 'frequency_penalty' => 0,
  6876. 'presence_penalty' => 0,
  6877. 'response_format' => ['type' => 'text'],
  6878. 'thinking' => ['type'=>$thinkingMode],
  6879. 'stream' => true // 启用流式输出
  6880. ];
  6881. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6882. // 根据模型类型选择调用方法
  6883. $fullContent = '';
  6884. $fullReasoningContent = '';
  6885. $usage = [];
  6886. try {
  6887. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6888. // DeepSeek 官方模型使用 DeepSeek API
  6889. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6890. } else if (in_array($model, $this->gpt_text_models)) {
  6891. // GPT-5.4 模型使用 TokenRouter API
  6892. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6893. } else if (in_array($model, $this->gemini_text_models)) {
  6894. // Gemini 模型使用 Gemini API
  6895. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6896. } else {
  6897. // 其他模型使用火山引擎API
  6898. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6899. }
  6900. // 验证返回值类型
  6901. if (!is_iterable($streamGenerator)) {
  6902. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6903. dLog('deepseek')->error('addChat流式生成器无效', [
  6904. 'generator_type' => $errorType,
  6905. 'model' => $model,
  6906. 'anime_id' => $anime_id
  6907. ]);
  6908. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6909. 'type' => $errorType,
  6910. 'model' => $model
  6911. ]);
  6912. yield [
  6913. 'type' => 'error',
  6914. 'script' => [],
  6915. 'episode' => [],
  6916. 'answer' => '',
  6917. 'reasoning' => '',
  6918. 'usage' => [],
  6919. 'error' => '接口返回数据异常,请重新请求'
  6920. ];
  6921. return;
  6922. }
  6923. // 处理流式输出
  6924. foreach ($streamGenerator as $chunk) {
  6925. if (isset($chunk['type'])) {
  6926. if ($chunk['type'] === 'done') {
  6927. // 最终结果
  6928. $fullContent = $chunk['full_content'];
  6929. $fullReasoningContent = $chunk['full_reasoning'];
  6930. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6931. } else {
  6932. // 逐块yield数据
  6933. yield $chunk;
  6934. }
  6935. }
  6936. }
  6937. } catch (\Exception $e) {
  6938. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6939. 'model' => $model,
  6940. 'anime_id' => $anime_id,
  6941. 'trace' => $e->getTraceAsString()
  6942. ]);
  6943. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6944. 'error' => $e->getMessage(),
  6945. 'model' => $model
  6946. ]);
  6947. yield [
  6948. 'type' => 'error',
  6949. 'script' => [],
  6950. 'episode' => [],
  6951. 'answer' => '',
  6952. 'reasoning' => '',
  6953. 'usage' => [],
  6954. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6955. ];
  6956. return;
  6957. }
  6958. dLog('deepseek')->info('完整内容: '.$fullContent);
  6959. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6960. // 处理完整内容并返回最终结果
  6961. $script_arr = [];
  6962. if ($fullContent) {
  6963. $script_arr = handleScriptContentForAce($fullContent);
  6964. dLog('deepseek')->info('解析内容', $script_arr);
  6965. logDB('deepseek', 'info', '解析内容', $script_arr);
  6966. }
  6967. if (empty($script_arr['roles'])) {
  6968. // 未生成剧本相关内容,保存对话记录并返回提示
  6969. dLog('deepseek')->info('未生成剧本相关的内容');
  6970. try {
  6971. DB::beginTransaction();
  6972. $now = date('Y-m-d H:i:s');
  6973. // 保存对话记录
  6974. $records = [
  6975. [
  6976. 'uid' => $uid,
  6977. 'anime_id' => $anime_id,
  6978. 'sequence' => 0,
  6979. 'role' => 'user',
  6980. 'content' => $prompt,
  6981. 'created_at' => $now,
  6982. 'updated_at' => $now
  6983. ],
  6984. [
  6985. 'uid' => $uid,
  6986. 'anime_id' => $anime_id,
  6987. 'sequence' => 0,
  6988. 'role' => 'assistant',
  6989. // 'content' => $fullContent,
  6990. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6991. 'created_at' => $now,
  6992. 'updated_at' => $now
  6993. ]
  6994. ];
  6995. DB::table('mp_anime_records')->insert($records);
  6996. DB::commit();
  6997. } catch (\Exception $e) {
  6998. DB::rollBack();
  6999. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7000. }
  7001. yield [
  7002. 'type' => 'done',
  7003. 'script' => [],
  7004. 'episode' => [],
  7005. 'answer' => $fullContent,
  7006. 'reasoning' => $fullReasoningContent,
  7007. 'usage' => $usage,
  7008. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7009. ];
  7010. return;
  7011. }
  7012. // 如果需要生成原文内容,从script_arr中提取
  7013. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7014. $content = $script_arr['content'];
  7015. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7016. if (!$content) {
  7017. yield [
  7018. 'type' => 'done',
  7019. 'script' => [],
  7020. 'episode' => [],
  7021. 'answer' => $fullContent,
  7022. 'reasoning' => $fullReasoningContent,
  7023. 'usage' => $usage,
  7024. 'error' => '未生成剧本内容,请调整提示词再试'
  7025. ];
  7026. return;
  7027. }
  7028. }
  7029. // 替换美术风格
  7030. if ($mappedArtStyle !== '') {
  7031. $script_arr['art_style'] = $mappedArtStyle;
  7032. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7033. }
  7034. // 新建动漫
  7035. if ($user_anime_name == '新剧本策划') {
  7036. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7037. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7038. // if (!$anime_name) {
  7039. // // 未识别到剧本名,保存对话记录并返回提示
  7040. // dLog('deepseek')->info('未能识别到剧本名称');
  7041. // try {
  7042. // DB::beginTransaction();
  7043. // $now = date('Y-m-d H:i:s');
  7044. // // 保存对话记录
  7045. // $records = [
  7046. // [
  7047. // 'uid' => $uid,
  7048. // 'anime_id' => $anime_id,
  7049. // 'sequence' => 0,
  7050. // 'role' => 'user',
  7051. // 'content' => $prompt,
  7052. // 'created_at' => $now,
  7053. // 'updated_at' => $now
  7054. // ],
  7055. // [
  7056. // 'uid' => $uid,
  7057. // 'anime_id' => $anime_id,
  7058. // 'sequence' => 0,
  7059. // 'role' => 'assistant',
  7060. // 'content' => '未能生成剧本名称,请重试',
  7061. // 'created_at' => $now,
  7062. // 'updated_at' => $now
  7063. // ]
  7064. // ];
  7065. // DB::table('mp_anime_records')->insert($records);
  7066. // DB::commit();
  7067. // } catch (\Exception $e) {
  7068. // DB::rollBack();
  7069. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7070. // }
  7071. // yield [
  7072. // 'type' => 'done',
  7073. // 'script' => [],
  7074. // 'episode' => [],
  7075. // 'answer' => $fullContent,
  7076. // 'reasoning' => $fullReasoningContent,
  7077. // 'usage' => $usage,
  7078. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7079. // ];
  7080. // return;
  7081. // }
  7082. // 确认对话名称唯一性
  7083. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7084. $anime_name = $anime_name . '_' . date('YmdHis');
  7085. }
  7086. }else {
  7087. $anime_name = $user_anime_name;
  7088. }
  7089. $table_data = [
  7090. 'user_id' => $uid,
  7091. 'anime_name' => $anime_name,
  7092. 'model' => $model,
  7093. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7094. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7095. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7096. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7097. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7098. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7099. 'art_style_type' => $input_art_style,
  7100. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7101. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7102. 'status' => '解析完成',
  7103. 'content' => $content,
  7104. 'is_multi' => $is_multi,
  7105. 'ace_mode' => $ace_mode,
  7106. 'generate_status' => '待执行',
  7107. 'updated_at' => date('Y-m-d H:i:s')
  7108. ];
  7109. if ($table_data['content']) {
  7110. $chapters = splitContent($table_data['content']);
  7111. $chapter_count = count($chapters);
  7112. if ($chapter_count > 0) {
  7113. $table_data['start_episode_sequence'] = 1;
  7114. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7115. }
  7116. }
  7117. if ($extra_products) {
  7118. $table_data['extra_products'] = json_encode($extra_products, 256);
  7119. }
  7120. // 如果有剧本ID则进行绑定
  7121. if ($script_id) {
  7122. $table_data['script_id'] = $script_id;
  7123. }
  7124. $single_episode = [];
  7125. try {
  7126. DB::beginTransaction();
  7127. $now = date('Y-m-d H:i:s');
  7128. // 更新动漫大纲
  7129. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7130. if (!$boolen) {
  7131. dLog('deepseek')->info('动漫保存失败', $table_data);
  7132. Utils::throwError('20003:动漫保存失败');
  7133. }
  7134. // 保存对话记录
  7135. $records = [
  7136. [
  7137. 'uid' => $uid,
  7138. 'anime_id' => $anime_id,
  7139. 'sequence' => 0,
  7140. 'role' => 'user',
  7141. 'content' => $prompt,
  7142. 'created_at' => date('Y-m-d H:i:s'),
  7143. 'updated_at' => date('Y-m-d H:i:s')
  7144. ],
  7145. [
  7146. 'uid' => $uid,
  7147. 'anime_id' => $anime_id,
  7148. 'sequence' => 0,
  7149. 'role' => 'assistant',
  7150. 'content' => $fullContent,
  7151. 'created_at' => date('Y-m-d H:i:s'),
  7152. 'updated_at' => date('Y-m-d H:i:s')
  7153. ]
  7154. ];
  7155. // 保存对话记录
  7156. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7157. if (!$boolen3) {
  7158. Utils::throwError('20003:对话记录保存失败');
  7159. }
  7160. if ($is_single) {
  7161. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7162. if (empty($episode_arr['acts'])) {
  7163. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7164. }
  7165. $saveResult = $this->saveEpisodeVersionData(
  7166. $anime_id,
  7167. 1,
  7168. $episode_arr,
  7169. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7170. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7171. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7172. null,
  7173. null,
  7174. false,
  7175. $content,
  7176. $now,
  7177. $ref_products
  7178. );
  7179. $single_episode = $saveResult['episode'];
  7180. $episode_id = $saveResult['episode_id'];
  7181. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7182. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7183. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7184. 'props' => json_encode($saveResult['merged_props'], 256),
  7185. 'updated_at' => $now
  7186. ]);
  7187. if ($boolen5 === false) {
  7188. Utils::throwError('20003:单剧集主表资源同步失败');
  7189. }
  7190. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7191. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7192. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7193. $episode_record_content = '确认分镜大纲';
  7194. if ($content !== '') {
  7195. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7196. }
  7197. $episode_records = [
  7198. [
  7199. 'uid' => $uid,
  7200. 'anime_id' => $anime_id,
  7201. 'role' => 'user',
  7202. 'content' => $episode_record_content,
  7203. 'sequence' => 1,
  7204. 'episode_id' => $episode_id,
  7205. 'created_at' => $now,
  7206. 'updated_at' => $now
  7207. ],
  7208. [
  7209. 'uid' => $uid,
  7210. 'anime_id' => $anime_id,
  7211. 'role' => 'assistant',
  7212. 'content' => $fullContent,
  7213. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7214. 'sequence' => 1,
  7215. 'episode_id' => $episode_id,
  7216. 'created_at' => $now,
  7217. 'updated_at' => $now
  7218. ]
  7219. ];
  7220. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7221. if (!$boolen4) {
  7222. Utils::throwError('20003:单剧集分镜记录保存失败');
  7223. }
  7224. }
  7225. }catch (\Exception $e) {
  7226. DB::rollBack();
  7227. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7228. yield [
  7229. 'type' => 'done',
  7230. 'answer' => $fullContent,
  7231. 'reasoning' => $fullReasoningContent,
  7232. 'usage' => $usage,
  7233. 'error' => $e->getMessage(),
  7234. ];
  7235. return;
  7236. }
  7237. DB::commit();
  7238. dLog('deepseek')->info('保存完毕');
  7239. if ($is_single && !empty($single_episode)) {
  7240. // $this->batchSetGlobalRoleImg([
  7241. // 'anime_id' => $anime_id,
  7242. // ]);
  7243. // $this->batchSetGlobalSceneImg([
  7244. // 'anime_id' => $anime_id,
  7245. // ]);
  7246. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7247. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7248. }
  7249. $table_data['anime_id'] = $anime_id;
  7250. $table_data['roles'] = json_decode($table_data['roles'], true);
  7251. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7252. // $table_data['episodes'] = $script_arr['episodes'];
  7253. unset($table_data['created_at']);
  7254. unset($table_data['updated_at']);
  7255. unset($table_data['status']);
  7256. dLog('deepseek')->info('开始返回');
  7257. yield [
  7258. 'type' => 'done',
  7259. 'script' => $table_data,
  7260. 'episode' => $single_episode,
  7261. 'answer' => $fullContent,
  7262. 'reasoning' => $fullReasoningContent,
  7263. 'usage' => $usage
  7264. ];
  7265. }
  7266. public function reGenerateAnimeForAce($data) {
  7267. $uid = Site::getUid();
  7268. $file = getProp($data, 'file');
  7269. $content = getProp($data, 'content', '');
  7270. $bid = getProp($data, 'bid', 0);
  7271. $script_id = getProp($data, 'script_id', 0);
  7272. $anime_id = getProp($data, 'anime_id');
  7273. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7274. if (!$anime) {
  7275. Utils::throwError('20003:该对话不存在');
  7276. }
  7277. $is_multi = getProp($anime, 'is_multi', 1);
  7278. $is_single = (int)$is_multi !== 1;
  7279. $extra_products = getProp($data, 'products', []);
  7280. if (!$extra_products) {
  7281. $extra_products = getProp($anime, 'extra_products');
  7282. if ($extra_products) {
  7283. $extra_products = json_decode($extra_products, true);
  7284. }else {
  7285. $extra_products = [];
  7286. }
  7287. }else {
  7288. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7289. }
  7290. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7291. $anime_script_id = getProp($anime, 'script_id');
  7292. if ($anime_script_id && $is_single) {
  7293. $cpid = Site::getCpid();
  7294. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7295. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7296. ->where('mapping.script_id', $anime_script_id)
  7297. ->where('product.cpid', $cpid)
  7298. ->where('product.is_deleted', 0);
  7299. $mappings = $script_products_mappings->select(
  7300. 'mapping.product_id',
  7301. 'mapping.episode_number',
  7302. 'product.product_name',
  7303. 'product.type',
  7304. 'product.product',
  7305. 'product.pic_prompt',
  7306. 'product.url',
  7307. 'product.pic_task_id',
  7308. 'product.pic_task_status',
  7309. 'product.three_view_image_url'
  7310. )
  7311. ->get();
  7312. // 按 product_id 分组,合并 episode_number
  7313. $productMap = [];
  7314. foreach ($mappings as $item) {
  7315. $product_id = $item->product_id;
  7316. $product_name = $item->product_name;
  7317. // 处理product_name两边的符号
  7318. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7319. if (!isset($productMap[$product_id])) {
  7320. $productMap[$product_id] = [
  7321. 'product_id' => $product_id,
  7322. 'product_name' => $product_name,
  7323. 'type' => (int)$item->type,
  7324. 'product' => (int)$item->product,
  7325. 'pic_prompt' => $item->pic_prompt,
  7326. 'url' => $item->url,
  7327. 'pic_task_id' => $item->pic_task_id,
  7328. 'pic_task_status' => $item->pic_task_status,
  7329. 'episode_numbers' => [],
  7330. ];
  7331. }
  7332. // 添加 episode_number(去重)
  7333. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7334. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7335. }
  7336. }
  7337. // 将查询到的剧本资产合并到extra_products中
  7338. // 先构建extra_products的索引(以product_id为key,用于去重)
  7339. $extraProductsMap = [];
  7340. foreach ($extra_products as $item) {
  7341. $key = getProp($item, 'product_id');
  7342. if ($key) {
  7343. $extraProductsMap[$key] = $item;
  7344. }
  7345. }
  7346. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7347. foreach ($productMap as $product) {
  7348. $product_id = $product['product_id'];
  7349. // 如果不存在则添加(不带episode_number信息)
  7350. if (!isset($extraProductsMap[$product_id])) {
  7351. $extraProductsMap[$product_id] = [
  7352. 'product_id' => $product['product_id'],
  7353. 'product_name' => $product['product_name'],
  7354. 'type' => $product['type'],
  7355. 'product' => $product['product'],
  7356. 'pic_prompt' => $product['pic_prompt'],
  7357. 'url' => $product['url'],
  7358. 'pic_task_id' => $product['pic_task_id'],
  7359. 'pic_task_status' => $product['pic_task_status'],
  7360. ];
  7361. }
  7362. }
  7363. // 重新赋值给extra_products
  7364. $extra_products = array_values($extraProductsMap);
  7365. }
  7366. $user_anime_name = getProp($anime, 'anime_name');
  7367. $prompt = getProp($data, 'prompt');
  7368. // 处理提示词
  7369. if ($prompt && $extra_products) {
  7370. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7371. foreach($extra_products as $item) {
  7372. $product_name = getProp($item, 'product_name');
  7373. if ($product_name) {
  7374. // 替换 {product_name} 为 product_name
  7375. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7376. }
  7377. }
  7378. }
  7379. // 处理文本模型
  7380. $model = getProp($data, 'model');
  7381. if (!$model) {
  7382. // 用户没有输入,从anime表获取
  7383. $model = getProp($anime, 'model');
  7384. if (!$model) {
  7385. // anime表也没有,使用默认值
  7386. $model = 'deepseek-v4-pro';
  7387. }
  7388. }
  7389. // 验证模型是否在可用模型表中
  7390. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7391. $model = 'deepseek-v4-pro';
  7392. }
  7393. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7394. if ($is_single) {
  7395. $episode_exists = DB::table('mp_anime_episodes')
  7396. ->where('anime_id', $anime_id)
  7397. ->where('sequence', 1)
  7398. ->exists();
  7399. if ($episode_exists) {
  7400. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7401. }
  7402. }
  7403. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7404. if ($prompt) {
  7405. $question .= "本次修改要求如下:\n{$prompt}";
  7406. }
  7407. // 提取文件内容
  7408. if ($file) {
  7409. $content = $this->extractFileContent($file);
  7410. if (!$content) {
  7411. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7412. }
  7413. } elseif ($script_id) {
  7414. $content = $this->getContentByScriptId($script_id);
  7415. if (!$content) {
  7416. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7417. }
  7418. } elseif ($bid) {
  7419. $content = $this->getContentByBid($bid);
  7420. if (!$content) {
  7421. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7422. }
  7423. } elseif ($content) {
  7424. $content = filterContent($content);
  7425. }else {
  7426. $content = filterContent(getProp($anime, 'content'));
  7427. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7428. $need_generate_content = true;
  7429. }
  7430. }
  7431. // 判断是否需要生成原文内容
  7432. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7433. // 如果需要生成原文内容,添加额外的要求
  7434. $content_generation_requirement = $need_generate_content
  7435. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7436. : "";
  7437. // 美术风格
  7438. $input_art_style = getProp($data, 'art_style');
  7439. if (!$input_art_style) {
  7440. $mappedArtStyle = getProp($anime, 'art_style');
  7441. }else {
  7442. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7443. }
  7444. if (!$mappedArtStyle) {
  7445. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7446. }else {
  7447. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7448. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7449. }else {
  7450. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7451. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7452. }
  7453. }
  7454. // 构建主体、场景和道具提示词
  7455. $extra_role_prompt = "\n";
  7456. $extra_scene_prompt = "\n";
  7457. $extra_prop_prompt = "\n";
  7458. $ref_products = []; // 参考资产
  7459. if ($extra_products) {
  7460. foreach($extra_products as $item) {
  7461. $product = getProp($item, 'product');
  7462. $product_name = getProp($item, 'product_name');
  7463. if ($product_name == '旁白') continue;
  7464. $ref_products[$product_name] = $item;
  7465. $pic_prompt = getProp($item, 'pic_prompt');
  7466. if ((int)$product === 1) {
  7467. // 拼接角色信息
  7468. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7469. } elseif ((int)$product === 2) {
  7470. // 拼接场景信息
  7471. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7472. } elseif ((int)$product === 3) {
  7473. // 拼接道具信息
  7474. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7475. }
  7476. }
  7477. // 优化提示词,融入剧本
  7478. if (!empty(trim($extra_role_prompt))) {
  7479. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7480. }
  7481. if (!empty(trim($extra_scene_prompt))) {
  7482. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7483. }
  7484. if (!empty(trim($extra_prop_prompt))) {
  7485. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7486. }
  7487. }
  7488. if ($anime_script_id && $is_single) {
  7489. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7490. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7491. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7492. }else {
  7493. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7494. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7495. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7496. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7497. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7498. {$extra_role_prompt}";
  7499. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7500. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7501. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7502. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7503. {$extra_scene_prompt}";
  7504. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7505. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7506. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7507. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7508. {$extra_prop_prompt}";
  7509. }
  7510. $system_message = ['role'=>'system', 'content'=>$is_single
  7511. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7512. 强制要求:
  7513. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7514. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7515. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7516. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7517. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7518. 普通要求:
  7519. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7520. $role_demo
  7521. $scene_demo
  7522. $prop_demo
  7523. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7524. 5.1片段分割逻辑(优先级从高到低):
  7525. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7526. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7527. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7528. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7529. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7530. - 片段数量格式为: 片段数量:8
  7531. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7532. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7533. 5.3分镜结构:每个分镜包含以下字段:
  7534. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7535. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7536. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7537. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7538. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7539. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7540. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7541. - 运镜:场景+画面描述+运镜
  7542. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7543. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7544. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7545. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7546. 6.{$mappedArtStyle_prompt}\n\n
  7547. 示例如下:\n
  7548. ###剧本名:西昆仑
  7549. ###故事梗概
  7550. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7551. ###剧本亮点
  7552. 亮点1:绝境奇药,生死一线
  7553. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7554. 亮点2:结拜兄妹,化解尴尬
  7555. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7556. 亮点3:纤发夺命,情愫暗涌
  7557. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7558. ###人物关系
  7559. 阿雪与梁萧之间存在兄妹之情。
  7560. ###核心矛盾
  7561. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7562. ###主体列表
  7563. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7564. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7565. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7566. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7567. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7568. 全景,正面拍摄,青年女性,亚洲人。
  7569. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7570. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7571. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7572. ###美术风格
  7573. 基础画风风格词:厚涂古风
  7574. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7575. ###场景列表
  7576. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7577. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7578. 无人物。}
  7579. ###分段剧本
  7580. 片段数量:8
  7581. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7582. ##片段1
  7583. 时长:12s
  7584. 分镜1
  7585. 出场角色:刀疤脸
  7586. 场景:边境小镇街道
  7587. 出场道具:酒杯-高脚杯
  7588. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7589. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7590. 配音台词:
  7591. 背景音效:
  7592. 分镜2
  7593. 出场角色:刀疤脸
  7594. 场景:悦来酒馆
  7595. 出场道具:酒杯-高脚杯
  7596. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7597. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7598. 配音台词:
  7599. 背景音效:
  7600. 分镜3
  7601. 出场角色:刀疤脸
  7602. 场景:悦来酒馆
  7603. 出场道具:酒杯-高脚杯
  7604. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7605. 运镜:从中景推向令牌特写。
  7606. 配音台词:
  7607. 背景音效:
  7608. 分镜4
  7609. 出场角色:刀疤脸
  7610. 场景:悦来酒馆
  7611. 出场道具:酒杯-高脚杯
  7612. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7613. 运镜:极速推向酒水溅起的瞬间。
  7614. 配音台词:
  7615. 背景音效:
  7616. 分镜5
  7617. 出场角色:刀疤脸
  7618. 场景:悦来酒馆
  7619. 出场道具:酒杯-高脚杯
  7620. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7621. 运镜:固定机位,利用倾斜构图制造压迫感。
  7622. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7623. 背景音效:
  7624. \n\n"
  7625. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7626. 强制要求:\n
  7627. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7628. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7629. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7630. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7631. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7632. 普通要求:\n
  7633. 1.剧本名(必须生成)必须与文档内容高度相关
  7634. $role_demo
  7635. $scene_demo
  7636. $prop_demo
  7637. 5.{$mappedArtStyle_prompt}\n\n
  7638. 示例如下:\n
  7639. ###剧本名:西昆仑
  7640. ###故事梗概
  7641. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7642. ###剧本亮点
  7643. 亮点1:绝境奇药,生死一线
  7644. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7645. 亮点2:结拜兄妹,化解尴尬
  7646. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7647. 亮点3:纤发夺命,情愫暗涌
  7648. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7649. ###人物关系
  7650. 阿雪与梁萧之间存在兄妹之情。
  7651. ###核心矛盾
  7652. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7653. ###主体列表
  7654. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7655. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7656. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7657. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7658. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7659. 全景,正面拍摄,青年女性,亚洲人。
  7660. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7661. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7662. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7663. ###美术风格
  7664. 基础画风风格词:厚涂古风
  7665. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7666. ###场景列表
  7667. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7668. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7669. 无人物。}
  7670. ###道具列表
  7671. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7672. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7673. $episode_count = $this->extractEpisodeNumber($prompt);
  7674. if ((int)getProp($anime, 'is_multi') !== 1) {
  7675. yield [
  7676. 'type' => 'done',
  7677. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7678. 'reasoning' => '',
  7679. 'usage' => []
  7680. ];
  7681. return;
  7682. }
  7683. if ($episode_count) {
  7684. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7685. $system_message = [
  7686. 'role' => 'system',
  7687. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7688. 强制要求:\n
  7689. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7690. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7691. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7692. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7693. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7694. 普通要求:\n
  7695. 1.<故事梗概>控制在200-300字左右
  7696. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7697. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7698. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7699. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7700. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7701. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7702. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7703. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7704. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7705. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  7706. 示例如下:\n
  7707. ###剧本名:西昆仑
  7708. ###故事梗概
  7709. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7710. ###剧本亮点
  7711. 亮点1:绝境奇药,生死一线
  7712. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7713. 亮点2:结拜兄妹,化解尴尬
  7714. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7715. 亮点3:纤发夺命,情愫暗涌
  7716. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7717. ###人物关系
  7718. 阿雪与梁萧之间存在兄妹之情。
  7719. ###核心矛盾
  7720. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7721. ###主体列表
  7722. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7723. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7724. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7725. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7726. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7727. 全景,正面拍摄,青年女性,亚洲人。
  7728. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7729. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7730. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7731. ###美术风格
  7732. 基础画风风格词:厚涂古风
  7733. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7734. ###场景列表
  7735. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7736. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7737. 无人物。}
  7738. ###分集详细内容
  7739. ##第1章 重生
  7740. 我重生了。
  7741. 源于一个男人偏执的暗恋。
  7742. ##第2章 相救
  7743. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  7744. 我眼睛扫向站在锅炉后的卞大伟。"
  7745. ];
  7746. // 构建消息
  7747. $messages = [
  7748. $system_message,
  7749. [
  7750. 'role' => 'user',
  7751. 'content' => "以下是文档内容:
  7752. {$content}
  7753. 用户问题:
  7754. {$question}"
  7755. ]
  7756. ];
  7757. }else {
  7758. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  7759. // 构建消息
  7760. $messages = [
  7761. $system_message,
  7762. [
  7763. 'role' => 'user',
  7764. 'content' => "以下是文档内容:
  7765. {$content}
  7766. 用户问题:
  7767. {$question}"
  7768. ]
  7769. ];
  7770. }else {
  7771. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  7772. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  7773. return (array)$value;
  7774. })->toArray();
  7775. array_unshift($messages, $system_message);
  7776. $messages[] = [
  7777. 'role' => 'user',
  7778. 'content' => $prompt
  7779. ];
  7780. }
  7781. }
  7782. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7783. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7784. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7785. if ($model === 'deepseek-chat') {
  7786. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7787. $model = 'deepseek-v4-flash';
  7788. $thinkingMode = 'disabled';
  7789. } elseif ($model === 'deepseek-reasoner') {
  7790. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7791. $model = 'deepseek-v4-flash';
  7792. $thinkingMode = 'enabled';
  7793. }
  7794. $post_data = [
  7795. 'model' => $model,
  7796. 'messages' => $messages,
  7797. // 'max_tokens' => 8192,
  7798. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7799. 'frequency_penalty' => 0,
  7800. 'presence_penalty' => 0,
  7801. 'response_format' => ['type' => 'text'],
  7802. 'thinking' => ['type' => $thinkingMode],
  7803. 'stream' => true // 启用流式输出
  7804. ];
  7805. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7806. // 根据模型类型选择调用方法
  7807. $fullContent = '';
  7808. $fullReasoningContent = '';
  7809. $usage = [];
  7810. // dd($post_data);
  7811. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  7812. try {
  7813. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7814. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7815. } else if (in_array($model, $this->gpt_text_models)) {
  7816. // GPT-5.4 模型使用 TokenRouter API
  7817. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7818. } else if (in_array($model, $this->gemini_text_models)) {
  7819. // Gemini 模型使用 Gemini API
  7820. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7821. } else {
  7822. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7823. }
  7824. // 验证返回值类型
  7825. if (!is_iterable($streamGenerator)) {
  7826. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7827. dLog('deepseek')->error('方法名流式生成器无效', [
  7828. 'generator_type' => $errorType,
  7829. 'model' => $model,
  7830. // 添加其他上下文信息
  7831. ]);
  7832. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  7833. 'type' => $errorType,
  7834. 'model' => $model
  7835. ]);
  7836. yield [
  7837. 'type' => 'error',
  7838. // 根据方法返回相应的空数据结构
  7839. 'answer' => '',
  7840. 'reasoning' => '',
  7841. 'usage' => [],
  7842. 'error' => '接口返回数据异常,请重新请求'
  7843. ];
  7844. return;
  7845. }
  7846. // 处理流式输出
  7847. foreach ($streamGenerator as $chunk) {
  7848. if (isset($chunk['type'])) {
  7849. if ($chunk['type'] === 'done') {
  7850. $fullContent = $chunk['full_content'];
  7851. $fullReasoningContent = $chunk['full_reasoning'];
  7852. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7853. } else {
  7854. yield $chunk;
  7855. }
  7856. }
  7857. }
  7858. } catch (\Exception $e) {
  7859. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  7860. 'model' => $model,
  7861. 'trace' => $e->getTraceAsString()
  7862. ]);
  7863. logDB('deepseek', 'error', '方法名流式处理失败', [
  7864. 'error' => $e->getMessage(),
  7865. 'model' => $model
  7866. ]);
  7867. yield [
  7868. 'type' => 'error',
  7869. // 根据方法返回相应的空数据结构
  7870. 'answer' => '',
  7871. 'reasoning' => '',
  7872. 'usage' => [],
  7873. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7874. ];
  7875. return;
  7876. }
  7877. dLog('deepseek')->info('完整内容: '.$fullContent);
  7878. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7879. // 处理完整内容并返回最终结果
  7880. $script_arr = [];
  7881. if ($fullContent) {
  7882. $script_arr = handleScriptContentForAce($fullContent);
  7883. dLog('deepseek')->info('解析内容', $script_arr);
  7884. logDB('deepseek', 'info', '解析内容', $script_arr);
  7885. }
  7886. if (empty($script_arr['roles'])) {
  7887. // 未生成剧本相关内容,保存对话记录并返回提示
  7888. dLog('deepseek')->info('未生成剧本相关的内容');
  7889. try {
  7890. $now = date('Y-m-d H:i:s');
  7891. // 保存对话记录
  7892. $records = [
  7893. [
  7894. 'uid' => $uid,
  7895. 'anime_id' => $anime_id,
  7896. 'sequence' => 0,
  7897. 'role' => 'user',
  7898. 'content' => $prompt,
  7899. 'created_at' => $now,
  7900. 'updated_at' => $now
  7901. ],
  7902. [
  7903. 'uid' => $uid,
  7904. 'anime_id' => $anime_id,
  7905. 'sequence' => 0,
  7906. 'role' => 'assistant',
  7907. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  7908. 'created_at' => $now,
  7909. 'updated_at' => $now
  7910. ]
  7911. ];
  7912. DB::table('mp_anime_records')->insert($records);
  7913. } catch (\Exception $e) {
  7914. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7915. }
  7916. yield [
  7917. 'type' => 'done',
  7918. 'script' => [],
  7919. 'episode' => [],
  7920. 'answer' => $fullContent,
  7921. 'reasoning' => $fullReasoningContent,
  7922. 'usage' => $usage,
  7923. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7924. ];
  7925. return;
  7926. }
  7927. // 替换美术风格
  7928. if ($mappedArtStyle !== '') {
  7929. $script_arr['art_style'] = $mappedArtStyle;
  7930. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7931. }
  7932. if ($user_anime_name != '新剧本策划') {
  7933. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7934. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7935. // 确认对话名称唯一性
  7936. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7937. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  7938. }
  7939. }else {
  7940. $anime_name = $user_anime_name;
  7941. }
  7942. $table_data = [
  7943. 'user_id' => $uid,
  7944. 'model' => $model,
  7945. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7946. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7947. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7948. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7949. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7950. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7951. 'art_style_type' => $input_art_style,
  7952. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7953. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7954. 'status' => '解析完成',
  7955. 'generate_status' => '待执行',
  7956. 'updated_at' => date('Y-m-d H:i:s')
  7957. ];
  7958. if ($anime_name) $table_data['anime_name'] = $anime_name;
  7959. // 如果是修改集数,则将content内容更新(会改变原文)
  7960. if (isset($episode_count) && $episode_count > 0) {
  7961. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  7962. $table_data['start_episode_sequence'] = 1;
  7963. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  7964. }else {
  7965. // 如果需要生成原文内容,从script_arr中提取
  7966. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7967. $table_data['content'] = $script_arr['content'];
  7968. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  7969. if (!$table_data['content']) {
  7970. yield [
  7971. 'type' => 'done',
  7972. 'script' => [],
  7973. 'episode' => [],
  7974. 'answer' => $fullContent,
  7975. 'reasoning' => $fullReasoningContent,
  7976. 'usage' => $usage,
  7977. 'error' => '未生成剧本内容,请调整提示词再试'
  7978. ];
  7979. return;
  7980. }
  7981. }
  7982. if (isset($table_data['content']) && $table_data['content']) {
  7983. $chapters = splitContent($table_data['content']);
  7984. $chapter_count = count($chapters);
  7985. if ($chapter_count > 0) {
  7986. $table_data['start_episode_sequence'] = 1;
  7987. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7988. }
  7989. }
  7990. }
  7991. if ($extra_products) {
  7992. $table_data['extra_products'] = json_encode($extra_products, 256);
  7993. }
  7994. $single_episode = [];
  7995. try {
  7996. DB::beginTransaction();
  7997. $now = date('Y-m-d H:i:s');
  7998. // 更新动漫大纲
  7999. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8000. if (!$boolen) {
  8001. dLog('deepseek')->info('对话修改失败', $table_data);
  8002. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8003. Utils::throwError('20003:对话修改失败');
  8004. }
  8005. // 保存对话记录
  8006. $records = [
  8007. [
  8008. 'uid' => $uid,
  8009. 'anime_id' => $anime_id,
  8010. 'sequence' => 0,
  8011. 'role' => 'user',
  8012. 'content' => $prompt,
  8013. 'created_at' => $now,
  8014. 'updated_at' => $now
  8015. ],
  8016. [
  8017. 'uid' => $uid,
  8018. 'anime_id' => $anime_id,
  8019. 'sequence' => 0,
  8020. 'role' => 'assistant',
  8021. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8022. 'content' => $fullContent,
  8023. 'created_at' => $now,
  8024. 'updated_at' => $now
  8025. ]
  8026. ];
  8027. // 保存对话记录
  8028. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8029. if (!$boolen3) {
  8030. Utils::throwError('20003:对话记录保存失败');
  8031. }
  8032. // 单剧集模式:生成并保存剧集信息
  8033. if ($is_single) {
  8034. $anime_name = getProp($anime, 'anime_name', '未命名');
  8035. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8036. if (empty($episode_arr['acts'])) {
  8037. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8038. }
  8039. $saveResult = $this->saveEpisodeVersionData(
  8040. $anime_id,
  8041. 1,
  8042. $episode_arr,
  8043. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8044. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8045. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8046. null,
  8047. null,
  8048. false,
  8049. $content,
  8050. $now,
  8051. $ref_products
  8052. );
  8053. $single_episode = $saveResult['episode'];
  8054. $episode_id = $saveResult['episode_id'];
  8055. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8056. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8057. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8058. 'props' => json_encode($saveResult['merged_props'], 256),
  8059. 'updated_at' => $now
  8060. ]);
  8061. if ($boolen5 === false) {
  8062. Utils::throwError('20003:单剧集主表资源同步失败');
  8063. }
  8064. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8065. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8066. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8067. $episode_record_content = '确认分镜大纲';
  8068. if ($content !== '') {
  8069. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8070. }
  8071. $episode_records = [
  8072. [
  8073. 'uid' => $uid,
  8074. 'anime_id' => $anime_id,
  8075. 'role' => 'user',
  8076. 'content' => $episode_record_content,
  8077. 'sequence' => 1,
  8078. 'episode_id' => $episode_id,
  8079. 'created_at' => $now,
  8080. 'updated_at' => $now
  8081. ],
  8082. [
  8083. 'uid' => $uid,
  8084. 'anime_id' => $anime_id,
  8085. 'role' => 'assistant',
  8086. 'content' => $fullContent,
  8087. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8088. 'sequence' => 1,
  8089. 'episode_id' => $episode_id,
  8090. 'created_at' => $now,
  8091. 'updated_at' => $now
  8092. ]
  8093. ];
  8094. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8095. if (!$boolen4) {
  8096. Utils::throwError('20003:单剧集分镜记录保存失败');
  8097. }
  8098. }
  8099. }catch (\Exception $e) {
  8100. DB::rollBack();
  8101. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8102. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8103. yield [
  8104. 'type' => 'done',
  8105. 'answer' => $fullContent,
  8106. 'reasoning' => $fullReasoningContent,
  8107. 'usage' => $usage,
  8108. 'error' => $e->getMessage(),
  8109. ];
  8110. return;
  8111. }
  8112. DB::commit();
  8113. dLog('deepseek')->info('保存完毕');
  8114. if ($is_single && !empty($single_episode)) {
  8115. // $this->batchSetGlobalRoleImg([
  8116. // 'anime_id' => $anime_id,
  8117. // ]);
  8118. // $this->batchSetGlobalSceneImg([
  8119. // 'anime_id' => $anime_id,
  8120. // ]);
  8121. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8122. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8123. }
  8124. $table_data['anime_id'] = $anime_id;
  8125. $table_data['roles'] = json_decode($table_data['roles'], true);
  8126. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8127. $table_data['props'] = json_decode($table_data['props'], true);
  8128. unset($table_data['updated_at']);
  8129. unset($table_data['status']);
  8130. yield [
  8131. 'type' => 'done',
  8132. 'script' => $table_data,
  8133. 'episode' => $single_episode,
  8134. 'answer' => $fullContent,
  8135. 'reasoning' => $fullReasoningContent,
  8136. 'usage' => $usage
  8137. ];
  8138. }
  8139. public function chatForAce($data) {
  8140. $uid = Site::getUid();
  8141. $anime_id = getProp($data, 'anime_id');
  8142. $file = getProp($data, 'file');
  8143. $content = getProp($data, 'content', '');
  8144. $bid = getProp($data, 'bid', 0);
  8145. $script_id = getProp($data, 'script_id', 0);
  8146. $episode_number = getProp($data, 'episode_number', 1);
  8147. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8148. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8149. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8150. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8151. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8152. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8153. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8154. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8155. $roles = is_array($roles) ? $roles : [];
  8156. $scenes = is_array($scenes) ? $scenes : [];
  8157. $extra_products = getProp($data, 'products', []);
  8158. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8159. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8160. $anime_script_id = getProp($anime, 'script_id');
  8161. if ($anime_script_id) {
  8162. $cpid = Site::getCpid();
  8163. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8164. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8165. ->where('mapping.script_id', $anime_script_id)
  8166. ->where('product.cpid', $cpid)
  8167. ->where('product.is_deleted', 0);
  8168. // 如果提供了 episode_number,则过滤指定集数
  8169. if ($episode_number !== null && $episode_number !== '') {
  8170. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8171. }
  8172. $mappings = $script_products_mappings->select(
  8173. 'mapping.product_id',
  8174. 'mapping.episode_number',
  8175. 'product.product_name',
  8176. 'product.type',
  8177. 'product.product',
  8178. 'product.pic_prompt',
  8179. 'product.url',
  8180. 'product.pic_task_id',
  8181. 'product.pic_task_status',
  8182. 'product.three_view_image_url'
  8183. )
  8184. ->get();
  8185. // 按 product_id 分组,合并 episode_number
  8186. $productMap = [];
  8187. foreach ($mappings as $item) {
  8188. $product_id = $item->product_id;
  8189. $product_name = $item->product_name;
  8190. // 处理product_name两边的符号
  8191. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8192. if (!isset($productMap[$product_id])) {
  8193. $productMap[$product_id] = [
  8194. 'product_id' => $product_id,
  8195. 'product_name' => $product_name,
  8196. 'type' => (int)$item->type,
  8197. 'product' => (int)$item->product,
  8198. 'pic_prompt' => $item->pic_prompt,
  8199. 'url' => $item->url,
  8200. 'pic_task_id' => $item->pic_task_id,
  8201. 'pic_task_status' => $item->pic_task_status,
  8202. 'episode_numbers' => [],
  8203. ];
  8204. }
  8205. // 添加 episode_number(去重)
  8206. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8207. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8208. }
  8209. }
  8210. // 将查询到的剧本资产合并到extra_products中
  8211. // 先构建extra_products的索引(以product_id+episode_number为key)
  8212. $extraProductsMap = [];
  8213. foreach ($extra_products as $item) {
  8214. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8215. $extraProductsMap[$key] = $item;
  8216. }
  8217. // 合并剧本资产(去重:product_id+episode_number)
  8218. foreach ($productMap as $product) {
  8219. foreach ($product['episode_numbers'] as $ep_num) {
  8220. $key = $product['product_id'] . '_' . $ep_num;
  8221. // 如果不存在则添加
  8222. if (!isset($extraProductsMap[$key])) {
  8223. $extraProductsMap[$key] = [
  8224. 'product_id' => $product['product_id'],
  8225. 'product_name' => $product['product_name'],
  8226. 'type' => $product['type'],
  8227. 'product' => $product['product'],
  8228. 'pic_prompt' => $product['pic_prompt'],
  8229. 'url' => $product['url'],
  8230. 'pic_task_id' => $product['pic_task_id'],
  8231. 'pic_task_status' => $product['pic_task_status'],
  8232. 'episode_number' => $ep_num,
  8233. ];
  8234. }
  8235. }
  8236. }
  8237. // 重新赋值给extra_products
  8238. $extra_products = array_values($extraProductsMap);
  8239. }
  8240. // 处理提示词
  8241. if ($prompt && $extra_products) {
  8242. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8243. foreach($extra_products as $item) {
  8244. $product_name = getProp($item, 'product_name');
  8245. if ($product_name) {
  8246. // 替换 {product_name} 为 product_name
  8247. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8248. }
  8249. }
  8250. }
  8251. // 获取最后一集序号
  8252. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8253. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8254. // 转换主体列表和场景列表的格式
  8255. // 获取参考主体或场景
  8256. if ((int)$episode_number === 1) {
  8257. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8258. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8259. }else {
  8260. $prev_episode_number = $episode_number - 1;
  8261. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8262. }
  8263. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8264. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8265. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8266. // 合并anime_products和extra_products(extra_products优先,去重)
  8267. $anime_products = getProp($anime, 'extra_products');
  8268. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8269. $ref_products = [];
  8270. foreach($anime_products as $item) {
  8271. $product_name = getProp($item, 'product_name');
  8272. $ref_products[$product_name] = $item;
  8273. }
  8274. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8275. $extra_roles = []; // 从extra_products中提取的角色
  8276. $extra_scenes = []; // 从extra_products中提取的场景
  8277. $extra_props = []; // 从extra_products中提取的道具
  8278. if ($extra_products && is_array($extra_products)) {
  8279. foreach($extra_products as $item) {
  8280. $product = (int)getProp($item, 'product');
  8281. $product_name = getProp($item, 'product_name');
  8282. if ($product_name == '旁白') continue;
  8283. $pic_prompt = getProp($item, 'pic_prompt');
  8284. $ref_products[$product_name] = $item;
  8285. if ($product === 1) {
  8286. // 角色
  8287. $extra_roles[$product_name] = [
  8288. 'role' => $product_name,
  8289. 'pic_prompt' => $pic_prompt,
  8290. 'url' => getProp($item, 'url', ''),
  8291. ];
  8292. } elseif ($product === 2) {
  8293. // 场景
  8294. $extra_scenes[$product_name] = [
  8295. 'scene' => $product_name,
  8296. 'pic_prompt' => $pic_prompt,
  8297. 'url' => getProp($item, 'url', ''),
  8298. ];
  8299. } elseif ($product === 3) {
  8300. // 道具
  8301. $extra_props[$product_name] = [
  8302. 'prop' => $product_name,
  8303. 'pic_prompt' => $pic_prompt,
  8304. 'url' => getProp($item, 'url', ''),
  8305. ];
  8306. }
  8307. }
  8308. }
  8309. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8310. $merged_roles = [];
  8311. foreach($ref_roles as $role) {
  8312. $role_name = getProp($role, 'role');
  8313. if (!isset($extra_roles[$role_name])) {
  8314. $merged_roles[$role_name] = $role;
  8315. }
  8316. }
  8317. // 添加extra_roles
  8318. foreach($extra_roles as $role_name => $role) {
  8319. $merged_roles[$role_name] = $role;
  8320. }
  8321. $ref_roles = array_values($merged_roles);
  8322. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8323. $merged_scenes = [];
  8324. foreach($ref_scenes as $scene) {
  8325. $scene_name = getProp($scene, 'scene');
  8326. if (!isset($extra_scenes[$scene_name])) {
  8327. $merged_scenes[$scene_name] = $scene;
  8328. }
  8329. }
  8330. // 添加extra_scenes
  8331. foreach($extra_scenes as $scene_name => $scene) {
  8332. $merged_scenes[$scene_name] = $scene;
  8333. }
  8334. $ref_scenes = array_values($merged_scenes);
  8335. // 合并ref_props和extra_props(extra_props优先,去重)
  8336. $merged_props = [];
  8337. foreach($ref_props as $prop) {
  8338. $prop_name = getProp($prop, 'prop');
  8339. if (!isset($extra_props[$prop_name])) {
  8340. $merged_props[$prop_name] = $prop;
  8341. }
  8342. }
  8343. // 添加extra_props
  8344. foreach($extra_props as $prop_name => $prop) {
  8345. $merged_props[$prop_name] = $prop;
  8346. }
  8347. $ref_props = array_values($merged_props);
  8348. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8349. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8350. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8351. // 构建强制主体、场景和道具提示词
  8352. $forced_roles_prompt = "";
  8353. $forced_scenes_prompt = "";
  8354. $forced_props_prompt = "";
  8355. if (!empty($extra_roles)) {
  8356. $forced_roles_list = "";
  8357. foreach($extra_roles as $role_name => $role) {
  8358. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8359. }
  8360. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8361. }
  8362. if (!empty($extra_scenes)) {
  8363. $forced_scenes_list = "";
  8364. foreach($extra_scenes as $scene_name => $scene) {
  8365. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8366. }
  8367. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8368. }
  8369. if (!empty($extra_props)) {
  8370. $forced_props_list = "";
  8371. foreach($extra_props as $prop_name => $prop) {
  8372. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8373. }
  8374. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8375. }
  8376. if ($anime_script_id) {
  8377. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8378. }else if ($roles_content) {
  8379. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8380. 主体范围:\n {$roles_content}\n
  8381. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8382. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8383. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8384. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8385. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8386. }else {
  8387. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8388. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8389. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8390. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8391. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8392. }
  8393. if ($anime_script_id) {
  8394. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8395. }else if ($scenes_content) {
  8396. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8397. 场景范围:\n {$scenes_content}\n
  8398. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8399. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8400. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8401. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8402. }else {
  8403. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8404. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8405. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8406. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8407. }
  8408. if ($anime_script_id) {
  8409. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8410. }else if ($props_content) {
  8411. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8412. 道具范围:\n {$props_content}\n
  8413. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8414. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8415. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8416. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8417. }else {
  8418. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8419. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8420. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8421. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8422. }
  8423. // 提取文件内容
  8424. if ($file) {
  8425. $uploaded_content = $this->extractFileContent($file);
  8426. if (!$uploaded_content) {
  8427. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8428. }
  8429. } elseif ($script_id) {
  8430. $uploaded_content = $this->getContentByScriptId($script_id);
  8431. if (!$uploaded_content) {
  8432. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8433. }
  8434. } elseif ($bid) {
  8435. $uploaded_content = $this->getContentByBid($bid);
  8436. if (!$uploaded_content) {
  8437. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8438. }
  8439. } elseif ($content) {
  8440. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8441. }
  8442. // elseif ($prompt) {
  8443. // $uploaded_content = filterContent($prompt);
  8444. // }
  8445. else {
  8446. $uploaded_content = '';
  8447. }
  8448. // 美术风格
  8449. $input_art_style = getProp($data, 'art_style');
  8450. if (!$input_art_style) {
  8451. $mappedArtStyle = getProp($anime, 'art_style');
  8452. }else {
  8453. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8454. }
  8455. if (!$mappedArtStyle) {
  8456. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8457. }else {
  8458. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8459. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8460. }else {
  8461. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8462. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8463. }
  8464. }
  8465. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8466. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8467. // 强制要求:
  8468. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8469. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8470. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8471. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8472. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8473. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8474. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8475. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8476. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8477. // 10.分镜要和场景列表、人物主体保持一致\n
  8478. // 普通要求:
  8479. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8480. // {$role_demo}
  8481. // {$scene_demo}
  8482. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8483. // 4.1片段分割逻辑(优先级从高到低):
  8484. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8485. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8486. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8487. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8488. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8489. // - 片段数量格式为: 片段数量:8
  8490. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8491. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8492. // 4.3分镜结构:每个分镜包含以下字段:
  8493. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8494. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8495. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8496. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8497. // - 运镜:场景+画面描述+运镜
  8498. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8499. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8500. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8501. // 5.$mappedArtStyle_prompt\n\n
  8502. // 示例格式:\n
  8503. // 第1集:隐形的守护者
  8504. // ###故事梗概
  8505. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8506. // ###美术风格
  8507. // 基础画风风格词:胡金铨武侠
  8508. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8509. // ###主体列表
  8510. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8511. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8512. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8513. // ###场景列表
  8514. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8515. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8516. // ###分段剧本
  8517. // 片段数量:8
  8518. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8519. // ##片段1
  8520. // 时长:12s
  8521. // 分镜1
  8522. // 场景:边境小镇街道
  8523. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8524. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8525. // 配音台词:
  8526. // 背景音效:
  8527. // 分镜2
  8528. // 场景:悦来酒馆
  8529. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8530. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8531. // 配音台词:
  8532. // 背景音效:
  8533. // 分镜3
  8534. // 场景:悦来酒馆
  8535. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8536. // 运镜:从中景推向令牌特写。
  8537. // 配音台词:
  8538. // 背景音效:
  8539. // 分镜4
  8540. // 场景:悦来酒馆
  8541. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8542. // 运镜:极速推向酒水溅起的瞬间。
  8543. // 配音台词:
  8544. // 背景音效:
  8545. // 分镜5
  8546. // 镜头描述
  8547. // 场景:悦来酒馆
  8548. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8549. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8550. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8551. // 背景音效:
  8552. // \n\n";
  8553. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8554. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8555. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8556. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8557. 强制要求:
  8558. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  8559. 普通要求:
  8560. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8561. {$role_demo}
  8562. {$scene_demo}
  8563. {$prop_demo}
  8564. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8565. 5.1片段分割逻辑(优先级从高到低):
  8566. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8567. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8568. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8569. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8570. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8571. - 片段数量格式为: 片段数量:8
  8572. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8573. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8574. 5.3分镜结构:每个分镜包含以下字段:
  8575. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8576. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8577. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8578. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8579. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8580. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8581. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8582. - 运镜:场景+画面描述+运镜
  8583. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8584. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8585. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8586. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8587. 6.《情绪-视听语言映射表》:
  8588. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8589. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8590. -----|---------|------------|----------------
  8591. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8592. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8593. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8594. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8595. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8596. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8597. -----|---------|------------|----------------
  8598. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8599. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8600. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8601. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8602. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8603. --------|---------|--------------|-------------
  8604. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8605. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8606. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8607. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8608. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8609. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8610. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8611. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8612. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8613. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8614. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8615. -----|---------|------------|------------
  8616. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8617. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8618. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8619. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8620. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8621. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8622. --------|---------|--------------|----------
  8623. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8624. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8625. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8626. 6.6 声音设计与潜意识影响 (Soundscape)
  8627. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8628. -----|---------|------------|------------------
  8629. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8630. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8631. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8632. 理论基石:
  8633. - The Five C's of Cinematography by Joseph V. Mascelli
  8634. - Film Art: An Introduction by David Bordwell
  8635. - Sight, Sound, Motion by Herbert Zettl
  8636. - Notes on the Cinematograph by Robert Bresson
  8637. \n\n
  8638. 7.{$mappedArtStyle_prompt}
  8639. 示例格式:\n
  8640. 第1集:隐形的守护者
  8641. ###故事梗概
  8642. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8643. ###美术风格
  8644. 基础画风风格词:胡金铨武侠
  8645. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8646. ###主体列表
  8647. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8648. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8649. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8650. ###场景列表
  8651. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8652. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8653. ###道具列表
  8654. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8655. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8656. ###分段剧本
  8657. 片段数量:8
  8658. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8659. ##片段1
  8660. 时长:12s
  8661. 分镜1
  8662. 出场角色:刀疤脸
  8663. 场景:边境小镇街道
  8664. 出场道具:酒杯-高脚杯
  8665. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8666. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8667. 配音台词:
  8668. 背景音效:
  8669. 分镜2
  8670. 出场角色:刀疤脸
  8671. 场景:悦来酒馆
  8672. 出场道具:酒杯-高脚杯
  8673. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8674. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8675. 配音台词:
  8676. 背景音效:
  8677. 分镜3
  8678. 出场角色:刀疤脸
  8679. 场景:悦来酒馆
  8680. 出场道具:酒杯-高脚杯
  8681. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8682. 运镜:从中景推向令牌特写。
  8683. 配音台词:
  8684. 背景音效:
  8685. 分镜4
  8686. 出场角色:刀疤脸
  8687. 场景:悦来酒馆
  8688. 出场道具:酒杯-高脚杯
  8689. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8690. 运镜:极速推向酒水溅起的瞬间。
  8691. 配音台词:
  8692. 背景音效:
  8693. 分镜5
  8694. 出场角色:刀疤脸
  8695. 场景:悦来酒馆
  8696. 出场道具:酒杯-高脚杯
  8697. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8698. 运镜:固定机位,利用倾斜构图制造压迫感。
  8699. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8700. 背景音效:
  8701. \n\n";
  8702. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8703. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  8704. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  8705. $prompt = $origin_prompt;
  8706. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  8707. // 获取章节内容
  8708. $full_content = getProp($anime, 'content');
  8709. if ($uploaded_content) {
  8710. $full_content = $uploaded_content;
  8711. }
  8712. // 根据章节内容拆分章节
  8713. $chapters = splitContent($full_content);
  8714. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  8715. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  8716. $messages = [];
  8717. if ($prompt == '确认分镜大纲') {
  8718. // 暂时保留
  8719. $content = $chapter_content;
  8720. if ($is_single) $content = $full_content; // 单剧集使用全文
  8721. if (!$content) {
  8722. Utils::throwError('20003:章节内容无法获取,请确认');
  8723. }
  8724. $question = $is_single
  8725. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  8726. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  8727. // 构建消息
  8728. $messages[] =
  8729. [
  8730. 'role' => 'user',
  8731. 'content' => $question
  8732. ];
  8733. }else if ($prompt == '继续策划下一集') {
  8734. if ($is_single) {
  8735. Utils::throwError('20003:单剧集不支持继续策划下一集');
  8736. }
  8737. $content = $chapter_content;
  8738. if (!$content) {
  8739. Utils::throwError('20003:章节内容无法获取,请确认');
  8740. }
  8741. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  8742. // 获取上一集最后记录
  8743. $prev_sequence = $episode_number - 1;
  8744. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  8745. // 构建消息
  8746. $messages[] =
  8747. [
  8748. 'role' => 'user',
  8749. 'content' => $question
  8750. ];
  8751. // dd($messages);
  8752. }else {
  8753. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  8754. if (!$content) {
  8755. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  8756. }
  8757. if (!$content) {
  8758. Utils::throwError('20003:章节内容无法获取,请确认');
  8759. }
  8760. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  8761. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  8762. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  8763. if ($origin_prompt) {
  8764. $question .= "本次修改要求如下:\n{$origin_prompt}";
  8765. }
  8766. $messages[] =
  8767. [
  8768. 'role' => 'user',
  8769. 'content' => $question
  8770. ];
  8771. }
  8772. // 处理文本模型
  8773. $model = getProp($data, 'model');
  8774. if (!$model) {
  8775. // 用户没有输入,从anime表获取
  8776. $model = getProp($anime, 'model');
  8777. if (!$model) {
  8778. // anime表也没有,使用默认值
  8779. $model = 'deepseek-v4-pro';
  8780. }
  8781. }
  8782. // 验证模型是否在可用模型表中
  8783. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8784. $model = 'deepseek-v4-pro';
  8785. }
  8786. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8787. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8788. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8789. if ($model === 'deepseek-chat') {
  8790. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8791. $model = 'deepseek-v4-flash';
  8792. $thinkingMode = 'disabled';
  8793. } elseif ($model === 'deepseek-reasoner') {
  8794. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8795. $model = 'deepseek-v4-flash';
  8796. $thinkingMode = 'enabled';
  8797. }
  8798. $post_data = [
  8799. 'model' => $model,
  8800. 'messages' => $messages,
  8801. // 'max_tokens' => 8192,
  8802. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8803. 'frequency_penalty' => 0,
  8804. 'presence_penalty' => 0,
  8805. 'response_format' => ['type' => 'text'],
  8806. 'thinking' => ['type' => $thinkingMode],
  8807. 'stream' => true // 启用流式输出
  8808. ];
  8809. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8810. // 根据模型类型选择调用方法
  8811. $fullContent = '';
  8812. $fullReasoningContent = '';
  8813. $usage = [];
  8814. try {
  8815. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8816. // DeepSeek 官方模型使用 DeepSeek API
  8817. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8818. } else if (in_array($model, $this->gpt_text_models)) {
  8819. // GPT-5.4 模型使用 TokenRouter API
  8820. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8821. } else if (in_array($model, $this->gemini_text_models)) {
  8822. // Gemini 模型使用 Gemini API
  8823. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8824. } else {
  8825. // 其他模型使用火山引擎API
  8826. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8827. }
  8828. // 验证返回值类型
  8829. if (!is_iterable($streamGenerator)) {
  8830. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8831. dLog('deepseek')->error('chat流式生成器无效', [
  8832. 'generator_type' => $errorType,
  8833. 'model' => $model,
  8834. 'anime_id' => $anime_id,
  8835. 'episode_number' => $episode_number
  8836. ]);
  8837. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  8838. 'type' => $errorType,
  8839. 'model' => $model
  8840. ]);
  8841. yield [
  8842. 'type' => 'error',
  8843. 'episode' => [],
  8844. 'answer' => '',
  8845. 'reasoning' => '',
  8846. 'usage' => [],
  8847. 'error' => '接口返回数据异常,请重新请求'
  8848. ];
  8849. return;
  8850. }
  8851. // 处理流式输出
  8852. foreach ($streamGenerator as $chunk) {
  8853. if (isset($chunk['type'])) {
  8854. if ($chunk['type'] === 'done') {
  8855. // 最终结果
  8856. $fullContent = $chunk['full_content'];
  8857. $fullReasoningContent = $chunk['full_reasoning'];
  8858. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8859. } else {
  8860. // 逐块yield数据
  8861. yield $chunk;
  8862. }
  8863. }
  8864. }
  8865. } catch (\Exception $e) {
  8866. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  8867. 'model' => $model,
  8868. 'anime_id' => $anime_id,
  8869. 'episode_number' => $episode_number,
  8870. 'trace' => $e->getTraceAsString()
  8871. ]);
  8872. logDB('deepseek', 'error', 'chat流式处理失败', [
  8873. 'error' => $e->getMessage(),
  8874. 'model' => $model
  8875. ]);
  8876. yield [
  8877. 'type' => 'error',
  8878. 'episode' => [],
  8879. 'answer' => '',
  8880. 'reasoning' => '',
  8881. 'usage' => [],
  8882. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8883. ];
  8884. return;
  8885. }
  8886. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  8887. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8888. dLog('deepseek')->info('完整内容: '.$fullContent);
  8889. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8890. // 处理完整内容并返回最终结果
  8891. $episode_arr = handleEpisodeContentForAce($fullContent);
  8892. dLog('deepseek')->info('解析内容: ', $episode_arr);
  8893. logDB('deepseek', 'info', '解析内容', $episode_arr);
  8894. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  8895. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8896. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8897. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  8898. // }
  8899. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  8900. $max_retries = 3;
  8901. $retry_count = 0;
  8902. $validation_failed = false;
  8903. $validation_error_msg = '';
  8904. // 验证生成的内容
  8905. if ($anime_script_id) {
  8906. // 检查是否有acts数据
  8907. if (empty($episode_arr['acts'])) {
  8908. $validation_failed = true;
  8909. $validation_error_msg = '未生成分镜剧本相关的内容';
  8910. } else {
  8911. // 仅当存在强制主体设定时校验主体列表
  8912. if (!empty($extra_roles)) {
  8913. $generated_roles = array_column($episode_arr['roles'], 'role');
  8914. // 过滤掉"旁白"角色
  8915. $generated_roles = array_filter($generated_roles, function($role) {
  8916. return $role !== '旁白';
  8917. });
  8918. $expected_roles = array_keys($extra_roles);
  8919. // 找出生成的主体中不在预期列表中的主体
  8920. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8921. if (!empty($invalid_roles)) {
  8922. $validation_failed = true;
  8923. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8924. }
  8925. }
  8926. // 仅当存在强制场景设定时校验场景列表
  8927. if (!$validation_failed && !empty($extra_scenes)) {
  8928. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8929. $expected_scenes = array_keys($extra_scenes);
  8930. // 找出生成的场景中不在预期列表中的场景
  8931. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8932. if (!empty($invalid_scenes)) {
  8933. $validation_failed = true;
  8934. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8935. }
  8936. }
  8937. // 仅当存在强制道具设定时校验道具列表
  8938. if (!$validation_failed && !empty($extra_props)) {
  8939. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8940. $expected_props = array_keys($extra_props);
  8941. // 找出生成的道具中不在预期列表中的道具
  8942. $invalid_props = array_diff($generated_props, $expected_props);
  8943. if (!empty($invalid_props)) {
  8944. $validation_failed = true;
  8945. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8946. }
  8947. }
  8948. }
  8949. } else {
  8950. // 如果没有anime_script_id,只检查是否有acts数据
  8951. if (empty($episode_arr['acts'])) {
  8952. $validation_failed = true;
  8953. $validation_error_msg = '未生成分镜剧本相关的内容';
  8954. }
  8955. }
  8956. // 重试逻辑
  8957. while ($validation_failed && $retry_count < $max_retries) {
  8958. $retry_count++;
  8959. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8960. 'reason' => $validation_error_msg,
  8961. 'anime_id' => $anime_id,
  8962. 'episode_number' => $episode_number
  8963. ]);
  8964. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8965. 'reason' => $validation_error_msg,
  8966. 'anime_id' => $anime_id
  8967. ]);
  8968. // 发送流式重试提示
  8969. yield [
  8970. 'type' => 'retry',
  8971. 'retry_count' => $retry_count,
  8972. 'reason' => $validation_error_msg
  8973. ];
  8974. // 构建重试提示词
  8975. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8976. if ($anime_script_id) {
  8977. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8978. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8979. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  8980. } else {
  8981. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  8982. }
  8983. // 添加重试消息到messages
  8984. $messages[] = [
  8985. 'role' => 'assistant',
  8986. 'content' => $fullContent
  8987. ];
  8988. $messages[] = [
  8989. 'role' => 'user',
  8990. 'content' => $retry_prompt
  8991. ];
  8992. // 更新post_data的messages
  8993. $post_data['messages'] = $messages;
  8994. // 重新调用API
  8995. try {
  8996. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8997. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8998. } else if (in_array($model, $this->gpt_text_models)) {
  8999. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9000. } else if (in_array($model, $this->gemini_text_models)) {
  9001. // Gemini 模型使用 Gemini API
  9002. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9003. } else {
  9004. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9005. }
  9006. // 处理流式输出
  9007. $fullContent = '';
  9008. $fullReasoningContent = '';
  9009. foreach ($streamGenerator as $chunk) {
  9010. if (isset($chunk['type'])) {
  9011. if ($chunk['type'] === 'done') {
  9012. $fullContent = $chunk['full_content'];
  9013. $fullReasoningContent = $chunk['full_reasoning'];
  9014. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9015. } else {
  9016. yield $chunk;
  9017. }
  9018. }
  9019. }
  9020. // 重新解析内容
  9021. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9022. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9023. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9024. $episode_arr = handleEpisodeContentForAce($fullContent);
  9025. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9026. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9027. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9028. // }
  9029. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9030. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9031. // 重新验证
  9032. $validation_failed = false;
  9033. $validation_error_msg = '';
  9034. if ($anime_script_id) {
  9035. if (empty($episode_arr['acts'])) {
  9036. $validation_failed = true;
  9037. $validation_error_msg = '未生成分镜剧本相关的内容';
  9038. } else {
  9039. // 仅当存在强制主体设定时校验主体列表
  9040. if (!empty($extra_roles)) {
  9041. $generated_roles = array_column($episode_arr['roles'], 'role');
  9042. // 过滤掉"旁白"角色
  9043. $generated_roles = array_filter($generated_roles, function($role) {
  9044. return $role !== '旁白';
  9045. });
  9046. $expected_roles = array_keys($extra_roles);
  9047. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9048. if (!empty($invalid_roles)) {
  9049. $validation_failed = true;
  9050. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9051. }
  9052. }
  9053. // 仅当存在强制场景设定时校验场景列表
  9054. if (!$validation_failed && !empty($extra_scenes)) {
  9055. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9056. $expected_scenes = array_keys($extra_scenes);
  9057. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9058. if (!empty($invalid_scenes)) {
  9059. $validation_failed = true;
  9060. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9061. }
  9062. }
  9063. // 仅当存在强制道具设定时校验道具列表
  9064. if (!$validation_failed && !empty($extra_props)) {
  9065. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9066. $expected_props = array_keys($extra_props);
  9067. $invalid_props = array_diff($generated_props, $expected_props);
  9068. if (!empty($invalid_props)) {
  9069. $validation_failed = true;
  9070. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9071. }
  9072. }
  9073. }
  9074. } else {
  9075. if (empty($episode_arr['acts'])) {
  9076. $validation_failed = true;
  9077. $validation_error_msg = '未生成分镜剧本相关的内容';
  9078. }
  9079. }
  9080. } catch (\Exception $e) {
  9081. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9082. 'trace' => $e->getTraceAsString()
  9083. ]);
  9084. break;
  9085. }
  9086. }
  9087. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  9088. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  9089. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  9090. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  9091. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  9092. if ($validation_failed && $retry_count >= $max_retries) {
  9093. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9094. 'retry_count' => $retry_count,
  9095. 'last_error' => $validation_error_msg
  9096. ]);
  9097. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9098. 'error' => $validation_error_msg,
  9099. 'anime_id' => $anime_id
  9100. ]);
  9101. $validation_failed = false;
  9102. $validation_error_msg = '';
  9103. }
  9104. // 如果重试后仍然失败
  9105. if ($validation_failed) {
  9106. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9107. 'retry_count' => $retry_count,
  9108. 'last_error' => $validation_error_msg
  9109. ]);
  9110. try {
  9111. $now = date('Y-m-d H:i:s');
  9112. $records = [
  9113. [
  9114. 'uid' => $uid,
  9115. 'anime_id' => $anime_id,
  9116. 'sequence' => $episode_number,
  9117. 'role' => 'user',
  9118. 'content' => $prompt,
  9119. 'created_at' => $now,
  9120. 'updated_at' => $now
  9121. ],
  9122. [
  9123. 'uid' => $uid,
  9124. 'anime_id' => $anime_id,
  9125. 'sequence' => $episode_number,
  9126. 'role' => 'assistant',
  9127. 'content' => $fullContent,
  9128. 'created_at' => $now,
  9129. 'updated_at' => $now
  9130. ]
  9131. ];
  9132. DB::table('mp_anime_records')->insert($records);
  9133. } catch (\Exception $e) {
  9134. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9135. }
  9136. yield [
  9137. 'type' => 'done',
  9138. 'episode' => [],
  9139. 'answer' => $fullContent,
  9140. 'reasoning' => $fullReasoningContent,
  9141. 'usage' => $usage,
  9142. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9143. ];
  9144. return;
  9145. }
  9146. // 验证成功,记录日志
  9147. if ($retry_count > 0) {
  9148. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9149. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9150. }
  9151. // 老逻辑
  9152. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  9153. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  9154. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  9155. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  9156. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  9157. $existing_props = is_array($existing_props) ? $existing_props : [];
  9158. $now = date('Y-m-d H:i:s');
  9159. try {
  9160. DB::beginTransaction();
  9161. $saveResult = $this->saveEpisodeVersionData(
  9162. $anime_id,
  9163. $episode_number,
  9164. $episode_arr,
  9165. $existing_roles,
  9166. $existing_scenes,
  9167. $existing_props,
  9168. $current_episode,
  9169. $base_episode,
  9170. $is_regenerate_version,
  9171. $content,
  9172. $now,
  9173. $ref_products
  9174. );
  9175. $episode = $saveResult['episode'];
  9176. $episode_id = $saveResult['episode_id'];
  9177. $merged_roles = $saveResult['merged_roles'];
  9178. $merged_scenes = $saveResult['merged_scenes'];
  9179. $merged_props = $saveResult['merged_props'];
  9180. $record_content = $origin_prompt;
  9181. if ($uploaded_content !== '') {
  9182. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9183. }
  9184. $records = [
  9185. [
  9186. 'uid' => $uid,
  9187. 'anime_id' => $anime_id,
  9188. 'role' => 'user',
  9189. 'content' => $record_content,
  9190. 'sequence' => $episode_number,
  9191. 'episode_id' => $episode_id,
  9192. 'created_at' => $now,
  9193. 'updated_at' => $now
  9194. ],
  9195. [
  9196. 'uid' => $uid,
  9197. 'anime_id' => $anime_id,
  9198. 'role' => 'assistant',
  9199. 'content' => $fullContent,
  9200. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9201. 'sequence' => $episode_number,
  9202. 'episode_id' => $episode_id,
  9203. 'created_at' => $now,
  9204. 'updated_at' => $now
  9205. ]
  9206. ];
  9207. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9208. if (!$boolen4) {
  9209. Utils::throwError('20003:对话记录保存失败');
  9210. }
  9211. // 保存模型到anime表
  9212. $update_anime_data = [
  9213. 'model' => $model,
  9214. 'updated_at' => $now
  9215. ];
  9216. if ($uploaded_content) {
  9217. $update_anime_data['content'] = $uploaded_content;
  9218. }
  9219. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9220. }catch (\Exception $e) {
  9221. DB::rollBack();
  9222. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9223. yield [
  9224. 'type' => 'done',
  9225. 'answer' => $fullContent,
  9226. 'reasoning' => $fullReasoningContent,
  9227. 'usage' => $usage,
  9228. 'error' => $e->getMessage(),
  9229. ];
  9230. return;
  9231. }
  9232. DB::commit();
  9233. if ($is_global_generate_pics) {
  9234. // // 批量生成全局角色图片
  9235. // $this->batchSetGlobalRoleImg([
  9236. // 'anime_id' => $anime_id,
  9237. // ], true);
  9238. // // 批量生成全局场景图片
  9239. // $this->batchSetGlobalSceneImg([
  9240. // 'anime_id' => $anime_id,
  9241. // ], true);
  9242. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9243. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9244. }
  9245. $episode['episode_id'] = $episode_id;
  9246. $episode['roles'] = $merged_roles;
  9247. $episode['scenes'] = $merged_scenes;
  9248. $episode['props'] = $merged_props;
  9249. $episode['end_episode_sequence'] = $end_episode_sequence;
  9250. // 获取mp_animes表中的视频参数
  9251. $episode['video_params'] = [
  9252. 'video_model' => getProp($anime, 'video_model'),
  9253. 'video_resolution' => getProp($anime, 'video_resolution'),
  9254. 'ratio' => getProp($anime, 'video_ratio'),
  9255. ];
  9256. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9257. yield [
  9258. 'type' => 'done',
  9259. 'episode' => $episode,
  9260. 'answer' => $fullContent,
  9261. 'reasoning' => $fullReasoningContent,
  9262. 'usage' => $usage
  9263. ];
  9264. }
  9265. /**
  9266. * chatForAce的非流式版本 - 用于定时任务
  9267. * 只获取最终 type=done 的数据,并验证必要字段
  9268. *
  9269. * @param array $data 请求数据
  9270. * @return array 生成结果
  9271. */
  9272. public function chatForAceNonStream($data) {
  9273. $finalResult = null;
  9274. // 调用流式方法,只保存 type=done 的数据
  9275. foreach ($this->chatForAce($data) as $chunk) {
  9276. // 只关注最终结果
  9277. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9278. $finalResult = $chunk;
  9279. break; // 找到 done 就退出循环
  9280. }
  9281. }
  9282. // 验证最终结果
  9283. if (!$finalResult) {
  9284. return ['error' => '生成失败:未获取到最终结果'];
  9285. }
  9286. // 检查是否有错误
  9287. if (isset($finalResult['error']) && $finalResult['error']) {
  9288. return $finalResult;
  9289. }
  9290. // 验证必要字段
  9291. $episode = $finalResult['episode'] ?? [];
  9292. // 验证 roles
  9293. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9294. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9295. }
  9296. // 验证 scenes
  9297. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9298. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9299. }
  9300. // 验证 props(道具可以为空,但必须存在且为数组)
  9301. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9302. $episode['props'] = [];
  9303. }
  9304. // 验证 acts(分镜剧本)
  9305. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9306. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9307. }
  9308. // 更新验证后的 episode 数据
  9309. $finalResult['episode'] = $episode;
  9310. // 记录验证成功日志
  9311. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9312. 'roles_count' => count($episode['roles']),
  9313. 'scenes_count' => count($episode['scenes']),
  9314. 'props_count' => count($episode['props']),
  9315. 'acts_count' => count($episode['acts'])
  9316. ]);
  9317. return $finalResult;
  9318. }
  9319. /**
  9320. * 批量生成多个分集
  9321. *
  9322. * @param array $data 请求数据
  9323. * @return array 任务信息
  9324. */
  9325. public function batchGenerateEpisodes($data) {
  9326. $uid = Site::getUid();
  9327. $cpid = Site::getCpid();
  9328. $anime_id = getProp($data, 'anime_id');
  9329. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9330. if (!$anime_id) {
  9331. Utils::throwError('20003:anime_id参数缺失');
  9332. }
  9333. if ($generate_episode_number < 1) {
  9334. Utils::throwError('20003:生成集数必须大于0');
  9335. }
  9336. // 获取动漫信息
  9337. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9338. if (!$anime) {
  9339. Utils::throwError('20003:该剧集不存在');
  9340. }
  9341. // 检查是否是全能模式
  9342. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9343. Utils::throwError('20003:只有全能模式才支持批量生成');
  9344. }
  9345. // 检查是否是多剧集模式
  9346. if ((int)getProp($anime, 'is_multi') !== 1) {
  9347. Utils::throwError('20003:单剧集不支持批量生成');
  9348. }
  9349. // 获取当前已生成的最大集数
  9350. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9351. ->where('anime_id', $anime_id)
  9352. ->where('is_default', 1)
  9353. ->max('episode_number');
  9354. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9355. // 确定起始集数
  9356. $startEpisodeNumber = $currentMaxEpisode + 1;
  9357. // 计算结束集数
  9358. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9359. // 检查是否超过总集数限制
  9360. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9361. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9362. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9363. }
  9364. $now = date('Y-m-d H:i:s');
  9365. $createdTasks = [];
  9366. $skippedTasks = [];
  9367. // 为每一集创建详情记录
  9368. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9369. // 检查是否已有该集的任务记录
  9370. $existingTask = DB::table('mp_batch_episode_generation_details')
  9371. ->where('anime_id', $anime_id)
  9372. ->where('episode_number', $episodeNumber)
  9373. ->first();
  9374. if ($existingTask) {
  9375. // 如果已存在且未完成,跳过
  9376. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9377. $skippedTasks[] = $episodeNumber;
  9378. continue;
  9379. }
  9380. // 如果是失败状态,可以重新创建(删除旧记录)
  9381. if ($existingTask->status === 'failed') {
  9382. DB::table('mp_batch_episode_generation_details')
  9383. ->where('id', $existingTask->id)
  9384. ->delete();
  9385. }
  9386. // 如果是已完成状态,也跳过
  9387. if ($existingTask->status === 'completed') {
  9388. $skippedTasks[] = $episodeNumber;
  9389. continue;
  9390. }
  9391. }
  9392. // 准备任务数据
  9393. $taskData = [
  9394. 'anime_id' => $anime_id,
  9395. 'uid' => $uid,
  9396. 'cpid' => $cpid,
  9397. 'episode_number' => $episodeNumber,
  9398. 'status' => 'pending',
  9399. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9400. 'retry_count' => 0,
  9401. 'created_at' => $now,
  9402. 'updated_at' => $now
  9403. ];
  9404. // 创建任务记录
  9405. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9406. if ($taskId) {
  9407. $createdTasks[] = $episodeNumber;
  9408. }
  9409. }
  9410. if (empty($createdTasks)) {
  9411. if (!empty($skippedTasks)) {
  9412. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9413. } else {
  9414. Utils::throwError('20003:创建批量生成任务失败');
  9415. }
  9416. }
  9417. return [
  9418. 'anime_id' => $anime_id,
  9419. 'start_episode' => $startEpisodeNumber,
  9420. 'end_episode' => $endEpisodeNumber,
  9421. 'total_episodes' => $generate_episode_number,
  9422. 'created_episodes' => $createdTasks,
  9423. 'skipped_episodes' => $skippedTasks,
  9424. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9425. "已创建: " . implode(',', $createdTasks) .
  9426. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9427. ];
  9428. }
  9429. /**
  9430. * 获取批量生成任务状态
  9431. *
  9432. * @param array $data 请求数据
  9433. * @return array 任务状态信息
  9434. */
  9435. public function getBatchGenerationTaskStatus($data) {
  9436. $anime_id = getProp($data, 'anime_id');
  9437. if (!$anime_id) {
  9438. Utils::throwError('20003:anime_id参数缺失');
  9439. }
  9440. // 获取该anime的所有任务
  9441. $tasks = DB::table('mp_batch_episode_generation_details')
  9442. ->where('anime_id', $anime_id)
  9443. ->orderBy('episode_number')
  9444. ->get()
  9445. ->map(function($item) {
  9446. return [
  9447. 'id' => $item->id,
  9448. 'episode_number' => $item->episode_number,
  9449. 'status' => $item->status,
  9450. 'error_message' => $item->error_message,
  9451. 'retry_count' => $item->retry_count,
  9452. 'created_at' => $item->created_at,
  9453. 'updated_at' => $item->updated_at,
  9454. 'completed_at' => $item->completed_at
  9455. ];
  9456. })
  9457. ->toArray();
  9458. if (empty($tasks)) {
  9459. Utils::throwError('20003:该剧集没有批量生成任务');
  9460. }
  9461. // 统计各状态数量
  9462. $totalCount = count($tasks);
  9463. $pendingCount = 0;
  9464. $processingCount = 0;
  9465. $completedCount = 0;
  9466. $failedCount = 0;
  9467. foreach ($tasks as $task) {
  9468. switch ($task['status']) {
  9469. case 'pending':
  9470. $pendingCount++;
  9471. break;
  9472. case 'processing':
  9473. $processingCount++;
  9474. break;
  9475. case 'completed':
  9476. $completedCount++;
  9477. break;
  9478. case 'failed':
  9479. $failedCount++;
  9480. break;
  9481. }
  9482. }
  9483. // 计算进度百分比
  9484. $progress = 0;
  9485. if ($totalCount > 0) {
  9486. $progress = round(($completedCount / $totalCount) * 100, 2);
  9487. }
  9488. // 判断整体状态
  9489. $overallStatus = 'processing';
  9490. if ($completedCount === $totalCount) {
  9491. $overallStatus = 'completed';
  9492. } elseif ($pendingCount === $totalCount) {
  9493. $overallStatus = 'pending';
  9494. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  9495. $overallStatus = 'failed';
  9496. }
  9497. return [
  9498. 'anime_id' => $anime_id,
  9499. 'total_episodes' => $totalCount,
  9500. 'pending_count' => $pendingCount,
  9501. 'processing_count' => $processingCount,
  9502. 'completed_count' => $completedCount,
  9503. 'failed_count' => $failedCount,
  9504. 'progress' => $progress,
  9505. 'overall_status' => $overallStatus,
  9506. 'tasks' => $tasks
  9507. ];
  9508. }
  9509. /**
  9510. * 将生成内容中不在强制列表中的资源合并进强制列表
  9511. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  9512. *
  9513. * @param array $generated 生成内容中的资源列表
  9514. * @param array $forced 强制资源列表(key为资源名称)
  9515. * @param string $type 资源类型:role、scene、prop
  9516. * @return array
  9517. */
  9518. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  9519. {
  9520. foreach ($generated as $item) {
  9521. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  9522. if ($name === null || $name === '') {
  9523. continue;
  9524. }
  9525. if ($name === '旁白') {
  9526. continue;
  9527. }
  9528. if (!isset($forced[$name])) {
  9529. $forced[$name] = $item;
  9530. }
  9531. }
  9532. return $forced;
  9533. }
  9534. /**
  9535. * 智能匹配并替换主体和场景名称
  9536. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  9537. *
  9538. * @param array $episode_arr 解析后的剧集数据
  9539. * @param array $extra_roles 强制主体设定(key为主体名称)
  9540. * @param array $extra_scenes 强制场景设定(key为场景名称)
  9541. * @return array 替换后的剧集数据
  9542. */
  9543. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  9544. $replaced_count = 0;
  9545. // 1. 处理主体列表
  9546. if (!empty($episode_arr['roles'])) {
  9547. foreach ($episode_arr['roles'] as &$role) {
  9548. $generated_role_name = $role['role'] ?? '';
  9549. // 跳过旁白
  9550. if ($generated_role_name === '旁白') {
  9551. continue;
  9552. }
  9553. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  9554. if (!isset($extra_roles[$generated_role_name])) {
  9555. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  9556. if ($matched_role) {
  9557. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  9558. $role['role'] = $matched_role;
  9559. $replaced_count++;
  9560. }
  9561. }
  9562. }
  9563. }
  9564. // 2. 处理场景列表
  9565. if (!empty($episode_arr['scenes'])) {
  9566. foreach ($episode_arr['scenes'] as &$scene) {
  9567. $generated_scene_name = $scene['scene'] ?? '';
  9568. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  9569. if (!isset($extra_scenes[$generated_scene_name])) {
  9570. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  9571. if ($matched_scene) {
  9572. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  9573. $scene['scene'] = $matched_scene;
  9574. $replaced_count++;
  9575. }
  9576. }
  9577. }
  9578. }
  9579. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  9580. if (!empty($episode_arr['acts'])) {
  9581. foreach ($episode_arr['acts'] as &$act) {
  9582. if (!empty($act['segments'])) {
  9583. foreach ($act['segments'] as &$segment) {
  9584. if (!empty($segment['segment_content'])) {
  9585. $original_content = $segment['segment_content'];
  9586. $replaced_content = $original_content;
  9587. // 替换场景名 - 在文本中查找并替换
  9588. foreach (array_keys($extra_scenes) as $full_scene_name) {
  9589. // 尝试找到可能的短名称
  9590. $potential_short_names = [];
  9591. // 提取场景名的主要部分(冒号之前)
  9592. if (mb_strpos($full_scene_name, ':') !== false) {
  9593. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9594. $potential_short_names[] = $short_name;
  9595. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  9596. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9597. $potential_short_names[] = $short_name;
  9598. }
  9599. // 替换场景字段中的短名称
  9600. foreach ($potential_short_names as $short_name) {
  9601. if ($short_name !== $full_scene_name) {
  9602. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  9603. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  9604. if ($new_content !== $replaced_content) {
  9605. $replaced_content = $new_content;
  9606. $replaced_count++;
  9607. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  9608. }
  9609. }
  9610. }
  9611. }
  9612. // 替换配音角色名(跳过旁白)
  9613. foreach (array_keys($extra_roles) as $full_role_name) {
  9614. if ($full_role_name === '旁白') {
  9615. continue;
  9616. }
  9617. // 尝试找到可能的短名称
  9618. $potential_short_names = [];
  9619. // 提取角色名的主要部分(短横线之前)
  9620. if (mb_strpos($full_role_name, '-') !== false) {
  9621. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  9622. $potential_short_names[] = $short_name;
  9623. }
  9624. // 替换配音台词中的短名称
  9625. foreach ($potential_short_names as $short_name) {
  9626. if ($short_name !== $full_role_name) {
  9627. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  9628. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  9629. if ($new_content !== $replaced_content) {
  9630. $replaced_content = $new_content;
  9631. $replaced_count++;
  9632. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  9633. }
  9634. }
  9635. }
  9636. }
  9637. // 如果有替换,更新segment_content
  9638. if ($replaced_content !== $original_content) {
  9639. $segment['segment_content'] = $replaced_content;
  9640. }
  9641. }
  9642. }
  9643. }
  9644. }
  9645. }
  9646. if ($replaced_count > 0) {
  9647. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  9648. 'replaced_count' => $replaced_count
  9649. ]);
  9650. }
  9651. return $episode_arr;
  9652. }
  9653. /**
  9654. * 查找匹配的名称
  9655. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  9656. *
  9657. * @param string $generated_name 生成的名称
  9658. * @param array $expected_names 预期的名称列表
  9659. * @return string|null 匹配到的名称,如果没有匹配则返回null
  9660. */
  9661. private function findMatchingName($generated_name, $expected_names) {
  9662. if (empty($generated_name)) {
  9663. return null;
  9664. }
  9665. // 尝试精确匹配
  9666. if (in_array($generated_name, $expected_names)) {
  9667. return $generated_name;
  9668. }
  9669. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  9670. foreach ($expected_names as $expected_name) {
  9671. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  9672. if (mb_strpos($expected_name, $generated_name) === 0) {
  9673. return $expected_name;
  9674. }
  9675. }
  9676. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  9677. // 这样可以处理一些变体,但优先级较低
  9678. foreach ($expected_names as $expected_name) {
  9679. if (mb_strpos($expected_name, $generated_name) !== false) {
  9680. return $expected_name;
  9681. }
  9682. }
  9683. return null;
  9684. }
  9685. /**
  9686. * 重新生成分段剧本
  9687. * @param array $data 包含以下字段:
  9688. * - prompt: string|null 用户修改要求(可选)
  9689. * - template_id: int|null 提示词模板ID(可选)
  9690. * - act_id: int|null 单个片段ID(与episode_id二选一)
  9691. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  9692. * @return array 返回生成结果
  9693. */
  9694. public function regenerateSegmentScript($data) {
  9695. $uid = Site::getUid();
  9696. $prompt = trim((string)getProp($data, 'prompt', ''));
  9697. $template_id = getProp($data, 'template_id', 0);
  9698. $act_id = getProp($data, 'act_id', 0);
  9699. $episode_id = getProp($data, 'episode_id', 0);
  9700. // 验证:prompt和template_id至少提供一个
  9701. if (empty($prompt) && empty($template_id)) {
  9702. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  9703. }
  9704. // 验证:act_id和episode_id二选一
  9705. if (empty($act_id) && empty($episode_id)) {
  9706. Utils::throwError('20003:请提供片段ID或剧集ID');
  9707. }
  9708. if (!empty($act_id) && !empty($episode_id)) {
  9709. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  9710. }
  9711. // 如果提供了template_id,获取模板提示词
  9712. $template_prompt = '';
  9713. if ($template_id > 0) {
  9714. $template = DB::table('mp_prompt_templates')
  9715. ->where('id', $template_id)
  9716. ->where('is_deleted', 0)
  9717. ->first();
  9718. if (!$template) {
  9719. Utils::throwError('20003:提示词模板不存在或已删除');
  9720. }
  9721. $template_prompt = $template->template_prompt ?? '';
  9722. }
  9723. // 合并用户提示词和模板提示词
  9724. $final_prompt = '';
  9725. if (!empty($template_prompt)) {
  9726. $final_prompt = $template_prompt;
  9727. if (!empty($prompt)) {
  9728. $final_prompt .= "\n\n补充要求:" . $prompt;
  9729. }
  9730. } else {
  9731. $final_prompt = $prompt;
  9732. }
  9733. // 获取需要重新生成的内容参考
  9734. $reference_content = '';
  9735. $target_episode_id = 0;
  9736. $target_anime_id = 0;
  9737. $target_episode_number = 0;
  9738. if ($act_id > 0) {
  9739. // 单个片段模式:获取该片段的内容
  9740. $segment = DB::table('mp_episode_segments')
  9741. ->where('id', $act_id)
  9742. ->first();
  9743. if (!$segment) {
  9744. Utils::throwError('20003:片段不存在');
  9745. }
  9746. $target_episode_id = $segment->episode_id;
  9747. $target_anime_id = $segment->anime_id;
  9748. $target_episode_number = $segment->episode_number;
  9749. $reference_content = $segment->act_content ?? '';
  9750. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9751. } else {
  9752. // 整个剧集模式:获取所有片段的内容
  9753. $segments = DB::table('mp_episode_segments')
  9754. ->where('episode_id', $episode_id)
  9755. ->orderBy('act_number')
  9756. ->get();
  9757. if ($segments->isEmpty()) {
  9758. Utils::throwError('20003:该剧集没有片段数据');
  9759. }
  9760. $target_episode_id = $episode_id;
  9761. $target_anime_id = $segments[0]->anime_id;
  9762. $target_episode_number = $segments[0]->episode_number;
  9763. // 拼接所有片段内容,保留格式用于AI理解
  9764. $act_contents = [];
  9765. foreach ($segments as $seg) {
  9766. $act_number = $seg->act_number;
  9767. $act_content = $seg->act_content ?? '';
  9768. if (!empty($act_content)) {
  9769. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  9770. }
  9771. }
  9772. $reference_content = implode("\n\n", $act_contents);
  9773. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  9774. if ($episode_content) {
  9775. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  9776. }else {
  9777. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9778. }
  9779. }
  9780. if (empty($reference_content)) {
  9781. Utils::throwError('20003:没有可参考的片段内容');
  9782. }
  9783. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  9784. $episode = DB::table('mp_anime_episodes')
  9785. ->where('id', $target_episode_id)
  9786. ->first();
  9787. if (!$episode) {
  9788. Utils::throwError('20003:剧集不存在');
  9789. }
  9790. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  9791. $anime_script_id = getProp($anime, 'script_id');
  9792. $intro = $episode->intro ?? '';
  9793. $art_style = $episode->art_style ?? '';
  9794. $roles = json_decode($episode->roles ?? '[]', true);
  9795. $scenes = json_decode($episode->scenes ?? '[]', true);
  9796. $props = json_decode($episode->props ?? '[]', true);
  9797. // 构建提示词中的主体列表和场景列表参考
  9798. $roles_ref = '';
  9799. if (!empty($roles) && is_array($roles)) {
  9800. $roles_list = [];
  9801. foreach ($roles as $role) {
  9802. $role_name = getProp($role, 'role', '');
  9803. $role_desc = getProp($role, 'description', '');
  9804. $pic_prompt = getProp($role, 'pic_prompt', '');
  9805. $voice_prompt = getProp($role, 'voice_prompt', '');
  9806. if (!empty($role_name)) {
  9807. $role_line = $role_name;
  9808. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  9809. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  9810. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  9811. $roles_list[] = $role_line;
  9812. }
  9813. }
  9814. if (!empty($roles_list)) {
  9815. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  9816. }
  9817. }
  9818. $scenes_ref = '';
  9819. if (!empty($scenes) && is_array($scenes)) {
  9820. $scenes_list = [];
  9821. foreach ($scenes as $scene) {
  9822. $scene_name = getProp($scene, 'scene', '');
  9823. $scene_desc = getProp($scene, 'description', '');
  9824. $pic_prompt = getProp($scene, 'pic_prompt', '');
  9825. if (!empty($scene_name)) {
  9826. $scene_line = $scene_name;
  9827. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  9828. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  9829. $scenes_list[] = $scene_line;
  9830. }
  9831. }
  9832. if (!empty($scenes_list)) {
  9833. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  9834. }
  9835. }
  9836. $props_ref = '';
  9837. if (!empty($props) && is_array($props)) {
  9838. $props_list = [];
  9839. foreach ($props as $prop) {
  9840. $prop_name = getProp($prop, 'prop', '');
  9841. $prop_desc = getProp($prop, 'description', '');
  9842. $pic_prompt = getProp($prop, 'pic_prompt', '');
  9843. if (!empty($prop_name)) {
  9844. $prop_line = $prop_name;
  9845. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  9846. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  9847. $props_list[] = $prop_line;
  9848. }
  9849. }
  9850. if (!empty($props_list)) {
  9851. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  9852. }
  9853. }
  9854. // 构建美术风格参考
  9855. $art_style_ref = '';
  9856. if (!empty($art_style)) {
  9857. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  9858. }
  9859. // 构建内容简介参考
  9860. $intro_ref = '';
  9861. if (!empty($intro)) {
  9862. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  9863. }
  9864. // 构建完整的AI提示词
  9865. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  9866. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  9867. $user_prompt .= $intro_ref;
  9868. $user_prompt .= $art_style_ref;
  9869. $user_prompt .= $reference_content;
  9870. // $user_prompt .= $roles_ref;
  9871. // $user_prompt .= $scenes_ref;
  9872. $system_prompt = "\n\n【强制要求】\n";
  9873. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  9874. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  9875. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  9876. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  9877. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  9878. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  9879. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  9880. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  9881. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  9882. ###分段剧本
  9883. 片段数量:8
  9884. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9885. ##片段1
  9886. 时长:12s
  9887. 分镜1
  9888. 出场角色:刀疤脸
  9889. 场景:边境小镇街道
  9890. 出场道具:酒杯-高脚杯
  9891. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9892. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9893. 配音台词:
  9894. 背景音效:
  9895. 分镜2
  9896. 出场角色:刀疤脸
  9897. 场景:悦来酒馆
  9898. 出场道具:酒杯-高脚杯
  9899. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9900. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9901. 配音台词:
  9902. 背景音效:
  9903. 分镜3
  9904. 出场角色:刀疤脸
  9905. 场景:悦来酒馆
  9906. 出场道具:酒杯-高脚杯
  9907. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9908. 运镜:从中景推向令牌特写。
  9909. 配音台词:
  9910. 背景音效:
  9911. 分镜4
  9912. 出场角色:刀疤脸
  9913. 场景:悦来酒馆
  9914. 出场道具:酒杯-高脚杯
  9915. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9916. 运镜:极速推向酒水溅起的瞬间。
  9917. 配音台词:
  9918. 背景音效:
  9919. 分镜5
  9920. 出场角色:刀疤脸
  9921. 场景:悦来酒馆
  9922. 出场道具:酒杯-高脚杯
  9923. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9924. 运镜:固定机位,利用倾斜构图制造压迫感。
  9925. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9926. 背景音效:";
  9927. // 获取模型配置
  9928. $model = getProp($data, 'model');
  9929. if (!$model) {
  9930. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  9931. }
  9932. // 验证模型是否在可用模型表中
  9933. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9934. $model = 'deepseek-v4-pro';
  9935. }
  9936. // 模型兼容性处理
  9937. $thinkingMode = 'disabled';
  9938. $reasoningEffort = 'high';
  9939. if ($model === 'deepseek-chat') {
  9940. $model = 'deepseek-v4-flash';
  9941. $thinkingMode = 'disabled';
  9942. } elseif ($model === 'deepseek-reasoner') {
  9943. $model = 'deepseek-v4-flash';
  9944. $thinkingMode = 'enabled';
  9945. }
  9946. // 构建消息
  9947. $messages = [
  9948. [
  9949. 'role' => 'system',
  9950. 'content' => $system_prompt
  9951. ],
  9952. [
  9953. 'role' => 'user',
  9954. 'content' => $user_prompt
  9955. ]
  9956. ];
  9957. // dd($messages);
  9958. // 构建请求参数
  9959. $post_data = [
  9960. 'model' => $model,
  9961. 'messages' => $messages,
  9962. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9963. 'frequency_penalty' => 0,
  9964. 'presence_penalty' => 0,
  9965. 'response_format' => ['type' => 'text'],
  9966. 'thinking' => ['type' => $thinkingMode],
  9967. 'stream' => false // 非流式输出
  9968. ];
  9969. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9970. // 调用AI生成新的分段剧本
  9971. try {
  9972. $fullContent = '';
  9973. $usage = [];
  9974. // 根据模型类型选择调用方法
  9975. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9976. // DeepSeek 官方模型使用 DeepSeek API
  9977. $chatResult = $this->chatOnly($post_data);
  9978. } else if (in_array($model, $this->gpt_text_models)) {
  9979. // GPT 模型使用 TokenRouter API
  9980. $chatResult = $this->gpt54ChatOnly($post_data);
  9981. } else {
  9982. // 其他模型使用火山引擎API
  9983. $chatResult = $this->volcEngineChatCompletion($post_data);
  9984. }
  9985. if (is_array($chatResult)) {
  9986. $fullContent = $chatResult['fullContent'] ?? '';
  9987. $usage = $chatResult['usage'] ?? [];
  9988. }
  9989. $generated_content = $fullContent;
  9990. if (empty($generated_content)) {
  9991. Utils::throwError('20003:AI生成内容为空,请重试');
  9992. }
  9993. // 解析生成的内容 - 按片段分割
  9994. $parsed_segments = [];
  9995. // 先在开头添加换行符,确保第1片段也能被正确分割
  9996. $normalizedText = "\n" . $generated_content;
  9997. $parts = preg_split('/\n\s*##/', $normalizedText);
  9998. foreach ($parts as $part) {
  9999. $part = trim($part);
  10000. if (empty($part)) continue;
  10001. // 匹配"片段X"格式
  10002. if (!preg_match('/^片段\d+/', $part)) {
  10003. continue;
  10004. }
  10005. // 分离标题和内容
  10006. $lines = explode("\n", $part, 2);
  10007. $actTitle = trim($lines[0]);
  10008. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  10009. // 解析标题,提取序号
  10010. $actNumber = 0;
  10011. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  10012. $actNumber = intval($segmentTitleMatch[1]);
  10013. } else {
  10014. $actNumber = count($parsed_segments) + 1;
  10015. }
  10016. // 提取时长(仅保留数字)
  10017. $actDuration = 0;
  10018. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  10019. $actDurationStr = trim($actDurationMatch[1]);
  10020. // 提取数字部分(支持整数和小数)
  10021. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  10022. $actDuration = (float)$numMatch[1];
  10023. }
  10024. }
  10025. // 清理act_content:去除时长、旁白音色等非分镜内容行
  10026. // 只保留分镜内容,并确保分镜标记使用【】格式
  10027. $cleaned_content = '';
  10028. $content_lines = explode("\n", $actContent);
  10029. $is_capturing = false; // 标记是否开始捕获分镜内容
  10030. $count = 0;
  10031. foreach ($content_lines as $line) {
  10032. $trimmed_line = trim($line);
  10033. // 跳过时长和旁白音色行
  10034. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  10035. continue;
  10036. }
  10037. // 检测是否是分镜开始
  10038. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  10039. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  10040. $count++;
  10041. $is_capturing = true;
  10042. // 如果没有【】,则添加
  10043. if (!preg_match('/^【/u', $trimmed_line)) {
  10044. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  10045. }
  10046. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  10047. }
  10048. // 如果已经开始捕获,则添加该行
  10049. if ($is_capturing && !empty($trimmed_line)) {
  10050. $cleaned_content .= $trimmed_line."\n";
  10051. }
  10052. }
  10053. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  10054. $parsed_segments[] = [
  10055. 'act_number' => $actNumber,
  10056. 'act_title' => $actTitle,
  10057. 'act_duration' => $actDuration,
  10058. 'act_content' => $cleaned_content,
  10059. ];
  10060. }
  10061. if (empty($parsed_segments)) {
  10062. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  10063. }
  10064. // 收集所有资产名称(角色、场景、道具)
  10065. $product_names = [];
  10066. // 收集角色名称
  10067. if (!empty($roles) && is_array($roles)) {
  10068. foreach ($roles as $role) {
  10069. $role_name = getProp($role, 'role', '');
  10070. if (!empty($role_name)) {
  10071. $product_names[] = $role_name;
  10072. }
  10073. }
  10074. }
  10075. // 收集场景名称
  10076. if (!empty($scenes) && is_array($scenes)) {
  10077. foreach ($scenes as $scene) {
  10078. $scene_name = getProp($scene, 'scene', '');
  10079. if (!empty($scene_name)) {
  10080. $product_names[] = $scene_name;
  10081. }
  10082. }
  10083. }
  10084. // 收集道具名称
  10085. if (!empty($props) && is_array($props)) {
  10086. foreach ($props as $prop) {
  10087. $prop_name = getProp($prop, 'prop', '');
  10088. if (!empty($prop_name)) {
  10089. $product_names[] = $prop_name;
  10090. }
  10091. }
  10092. }
  10093. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10094. $product_names = array_unique($product_names);
  10095. usort($product_names, function($a, $b) {
  10096. return mb_strlen($b) - mb_strlen($a);
  10097. });
  10098. // 处理每个片段的 act_show_content
  10099. foreach ($parsed_segments as &$segment) {
  10100. $act_content = getProp($segment, 'act_content', '');
  10101. if (empty($act_content)) {
  10102. $segment['act_show_content'] = '';
  10103. continue;
  10104. }
  10105. $processed_content = $act_content;
  10106. // 统一替换所有资产名称为 {资产名} 格式
  10107. // 使用占位符避免嵌套替换问题
  10108. $placeholder_map = [];
  10109. $placeholder_index = 0;
  10110. foreach ($product_names as $product_name) {
  10111. // 转义特殊字符
  10112. $escaped_product = preg_quote($product_name, '/');
  10113. // 检查是否匹配且未被 {} 包裹
  10114. $processed_content = preg_replace_callback(
  10115. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10116. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10117. // 使用唯一占位符
  10118. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10119. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10120. $placeholder_index++;
  10121. return $placeholder;
  10122. },
  10123. $processed_content
  10124. );
  10125. }
  10126. // 将所有占位符替换回实际内容
  10127. foreach ($placeholder_map as $placeholder => $replacement) {
  10128. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10129. }
  10130. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10131. $shot_counter = 0;
  10132. $processed_content = preg_replace_callback(
  10133. '/【(?:镜头|分镜)(\d+)】/u',
  10134. function($matches) use (&$shot_counter) {
  10135. $shot_counter++;
  10136. return '【镜头' . $shot_counter . '】';
  10137. },
  10138. $processed_content
  10139. );
  10140. $segment['act_show_content'] = $processed_content;
  10141. }
  10142. unset($segment); // 解除引用
  10143. // 保存到数据库
  10144. $now = date('Y-m-d H:i:s');
  10145. $saved_acts = []; // 用于记录保存后的片段信息
  10146. if ($act_id > 0) {
  10147. // 单个片段模式:更新单条记录
  10148. if (count($parsed_segments) > 0) {
  10149. $new_segment = $parsed_segments[0];
  10150. $update_data = [
  10151. 'act_content' => getProp($new_segment, 'act_content', ''),
  10152. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  10153. 'act_title' => getProp($new_segment, 'act_title', ''),
  10154. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  10155. 'updated_at' => $now,
  10156. ];
  10157. DB::table('mp_episode_segments')
  10158. ->where('id', $act_id)
  10159. ->update($update_data);
  10160. // 获取更新后的记录
  10161. $updated_act = DB::table('mp_episode_segments')
  10162. ->where('id', $act_id)
  10163. ->first();
  10164. if ($updated_act) {
  10165. $saved_acts[] = [
  10166. 'act_id' => $updated_act->id,
  10167. 'act_number' => $updated_act->act_number,
  10168. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  10169. 'act_content' => $updated_act->act_content,
  10170. 'act_show_content' => $updated_act->act_show_content,
  10171. 'video_url' => $updated_act->video_url ?? '',
  10172. 'video_duration' => $updated_act->video_duration ?? 0,
  10173. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  10174. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  10175. ];
  10176. }
  10177. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  10178. }
  10179. } else {
  10180. // 整个剧集模式:删除原有记录并批量保存新记录
  10181. DB::beginTransaction();
  10182. try {
  10183. // 删除原有的所有片段记录
  10184. DB::table('mp_episode_segments')
  10185. ->where('episode_id', $target_episode_id)
  10186. ->delete();
  10187. // 批量插入新的片段记录
  10188. $segments_to_insert = [];
  10189. foreach ($parsed_segments as $index => $segment) {
  10190. $act_number = $index + 1;
  10191. $segments_to_insert[] = [
  10192. 'anime_id' => $target_anime_id,
  10193. 'episode_id' => $target_episode_id,
  10194. 'episode_number' => $target_episode_number,
  10195. 'act_number' => $act_number,
  10196. 'act_title' => getProp($segment, 'act_title', ''),
  10197. 'act_duration' => getProp($segment, 'act_duration', 0),
  10198. 'act_content' => getProp($segment, 'act_content', ''),
  10199. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  10200. 'created_at' => $now,
  10201. 'updated_at' => $now,
  10202. ];
  10203. }
  10204. if (!empty($segments_to_insert)) {
  10205. DB::table('mp_episode_segments')->insert($segments_to_insert);
  10206. }
  10207. DB::commit();
  10208. // 查询保存后的所有片段记录
  10209. $saved_segments = DB::table('mp_episode_segments')
  10210. ->where('episode_id', $target_episode_id)
  10211. ->orderBy('act_number')
  10212. ->get();
  10213. foreach ($saved_segments as $saved_segment) {
  10214. $saved_acts[] = [
  10215. 'act_id' => $saved_segment->id,
  10216. 'act_number' => $saved_segment->act_number,
  10217. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  10218. 'act_content' => $saved_segment->act_content,
  10219. 'act_show_content' => $saved_segment->act_show_content,
  10220. 'video_url' => $saved_segment->video_url ?? '',
  10221. 'video_duration' => $saved_segment->video_duration ?? 0,
  10222. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  10223. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  10224. ];
  10225. }
  10226. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  10227. 'episode_id' => $target_episode_id,
  10228. 'segments_count' => count($segments_to_insert)
  10229. ]);
  10230. } catch (\Exception $e) {
  10231. DB::rollBack();
  10232. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  10233. Utils::throwError('20003:保存失败,请重试');
  10234. }
  10235. }
  10236. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  10237. return [
  10238. 'anime_id' => $target_anime_id,
  10239. 'episode_id' => $target_episode_id,
  10240. 'title' => getProp($episode, 'title', ''),
  10241. 'episode_number' => $target_episode_number,
  10242. 'is_generated' => getProp($episode, 'is_generated', 0),
  10243. 'acts' => $saved_acts,
  10244. ];
  10245. } catch (\Exception $e) {
  10246. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  10247. throw $e;
  10248. }
  10249. }
  10250. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  10251. {
  10252. $episode_arr = [
  10253. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  10254. 'intro' => getProp($script_arr, 'intro'),
  10255. 'art_style' => getProp($script_arr, 'art_style'),
  10256. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10257. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10258. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10259. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  10260. ];
  10261. if (empty($episode_arr['acts'])) {
  10262. $fallback_episode_arr = handleEpisodeContent($fullContent);
  10263. if (!empty($fallback_episode_arr['acts'])) {
  10264. $episode_arr = array_merge($fallback_episode_arr, [
  10265. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  10266. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  10267. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  10268. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  10269. ]);
  10270. }
  10271. }
  10272. // if (!getProp($episode_arr, 'episode_title')) {
  10273. // $episode_title = '';
  10274. // $episodes = getProp($script_arr, 'episodes', []);
  10275. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  10276. // $episode_title = '第1集:' . $episodes[0]['title'];
  10277. // }
  10278. // if (!$episode_title) {
  10279. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  10280. // }
  10281. // $episode_arr['episode_title'] = $episode_title;
  10282. // }
  10283. return $episode_arr;
  10284. }
  10285. private function saveEpisodeVersionData(
  10286. int $anime_id,
  10287. int $episode_number,
  10288. array $episode_arr,
  10289. array $existing_roles,
  10290. array $existing_scenes,
  10291. array $existing_props,
  10292. $current_episode,
  10293. $base_episode,
  10294. bool $is_regenerate_version,
  10295. string $content,
  10296. string $now,
  10297. array $ref_products = []
  10298. ): array {
  10299. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10300. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10301. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10302. // 过滤掉关键字段为空的条目
  10303. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10304. return !empty($item['role'] ?? null);
  10305. }));
  10306. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10307. return !empty($item['scene'] ?? null);
  10308. }));
  10309. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10310. return !empty($item['prop'] ?? null);
  10311. }));
  10312. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10313. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10314. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10315. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10316. $ace_mode = getProp($anime, 'ace_mode');
  10317. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10318. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10319. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10320. $global_roles = is_array($global_roles) ? $global_roles : [];
  10321. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10322. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10323. $art_style_type = getProp($anime, 'art_style_type');
  10324. // 检查并创建 roles 的图片生成任务
  10325. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10326. // 检查并创建 scenes 的图片生成任务
  10327. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10328. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10329. if ($arr && is_array($arr)) {
  10330. $merged_roles = $arr['roles'];
  10331. $merged_scenes = $arr['scenes'];
  10332. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10333. }
  10334. // 确保数据是数组类型
  10335. if (!is_array($merged_roles)) {
  10336. dLog('deepseek')->error('merged_roles不是数组类型', [
  10337. 'type' => gettype($merged_roles),
  10338. 'value' => $merged_roles
  10339. ]);
  10340. $merged_roles = [];
  10341. }
  10342. if (!is_array($merged_scenes)) {
  10343. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10344. 'type' => gettype($merged_scenes),
  10345. 'value' => $merged_scenes
  10346. ]);
  10347. $merged_scenes = [];
  10348. }
  10349. if (!is_array($merged_props)) {
  10350. dLog('deepseek')->error('merged_props不是数组类型', [
  10351. 'type' => gettype($merged_props),
  10352. 'value' => $merged_props
  10353. ]);
  10354. $merged_props = [];
  10355. }
  10356. // 同步新出现的主体和场景到全局
  10357. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10358. $role_arr = [];
  10359. foreach ($merged_roles as $item) {
  10360. $role_arr[$item['role']] = $item;
  10361. }
  10362. $version_count = DB::table('mp_anime_episodes')
  10363. ->where('anime_id', $anime_id)
  10364. ->where('episode_number', $episode_number)
  10365. ->count('id');
  10366. $episode = [
  10367. 'anime_id' => $anime_id,
  10368. 'episode_number' => $episode_number,
  10369. 'title' => getProp($episode_arr, 'episode_title'),
  10370. 'content' => $content,
  10371. 'intro' => getProp($episode_arr, 'intro'),
  10372. 'art_style' => getProp($episode_arr, 'art_style'),
  10373. 'roles' => json_encode($merged_roles, 256),
  10374. 'scenes' => json_encode($merged_scenes, 256),
  10375. 'props' => json_encode($merged_props, 256),
  10376. 'generate_status' => '待执行',
  10377. 'generate_at' => $now,
  10378. 'is_default' => 1,
  10379. 'updated_at' => $now,
  10380. ];
  10381. $del_flag = false;
  10382. if ($is_regenerate_version) {
  10383. DB::table('mp_anime_episodes')
  10384. ->where('anime_id', $anime_id)
  10385. ->where('episode_number', $episode_number)
  10386. ->update(['is_default' => 0, 'updated_at' => $now]);
  10387. $episode['sequence'] = $version_count + 1;
  10388. $episode['created_at'] = $now;
  10389. $episode['cpid'] = Site::getCpid();
  10390. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10391. if (!$episode_id) {
  10392. Utils::throwError('20003:创建剧集版本失败');
  10393. }
  10394. } else {
  10395. $target_episode = $current_episode ?: $base_episode;
  10396. if ($target_episode) {
  10397. $episode_id = getProp($target_episode, 'id');
  10398. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10399. DB::table('mp_anime_episodes')
  10400. ->where('anime_id', $anime_id)
  10401. ->where('episode_number', $episode_number)
  10402. ->where('id', '<>', $episode_id)
  10403. ->update(['is_default' => 0, 'updated_at' => $now]);
  10404. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10405. if ($boolen === false) {
  10406. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10407. Utils::throwError('20003:分集内容保存失败');
  10408. }
  10409. $del_flag = true;
  10410. } else {
  10411. DB::table('mp_anime_episodes')
  10412. ->where('anime_id', $anime_id)
  10413. ->where('episode_number', $episode_number)
  10414. ->update(['is_default' => 0, 'updated_at' => $now]);
  10415. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  10416. $episode['created_at'] = $now;
  10417. $episode['cpid'] = Site::getCpid();
  10418. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10419. if (!$episode_id) {
  10420. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  10421. Utils::throwError('20003:分集内容保存失败');
  10422. }
  10423. }
  10424. }
  10425. $segments = [];
  10426. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10427. // 如果是第2集及以后,获取上一集的主体音色数据
  10428. $previous_roles_voice = [];
  10429. if ($episode_number >= 2) {
  10430. $previous_episode = DB::table('mp_anime_episodes')
  10431. ->where('anime_id', $anime_id)
  10432. ->where('episode_number', $episode_number - 1)
  10433. ->where('is_default', 1)
  10434. ->first();
  10435. if ($previous_episode) {
  10436. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  10437. if (is_array($previous_roles)) {
  10438. foreach ($previous_roles as $prev_role) {
  10439. $role_name = getProp($prev_role, 'role');
  10440. if ($role_name) {
  10441. $previous_roles_voice[$role_name] = [
  10442. 'voice_name' => getProp($prev_role, 'voice_name'),
  10443. 'voice_type' => getProp($prev_role, 'voice_type'),
  10444. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  10445. ];
  10446. $voice_prompt = getProp($prev_role, 'voice_prompt');
  10447. if ($voice_prompt) {
  10448. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  10449. }
  10450. }
  10451. }
  10452. }
  10453. }
  10454. }
  10455. // 将继承的音色数据同步到当前集的主体列表
  10456. if (!empty($previous_roles_voice)) {
  10457. foreach ($merged_roles as &$role) {
  10458. $role_name = getProp($role, 'role');
  10459. if ($role_name && isset($previous_roles_voice[$role_name])) {
  10460. // 强制继承上一集的音色数据
  10461. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  10462. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  10463. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  10464. // 如果上一集有 voice_prompt 则继承,否则跳过
  10465. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  10466. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  10467. }
  10468. }
  10469. }
  10470. unset($role); // 解除引用
  10471. // 更新 role_arr 以便后续使用
  10472. $role_arr = [];
  10473. foreach ($merged_roles as $item) {
  10474. $role_arr[$item['role']] = $item;
  10475. }
  10476. }
  10477. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  10478. $emotion_list = array_flip($emotion_list);
  10479. foreach ($acts as $act) {
  10480. $act_segments = getProp($act, 'segments', []);
  10481. if (!is_array($act_segments)) {
  10482. continue;
  10483. }
  10484. if ((int)$ace_mode === 1) {
  10485. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  10486. $merged_parts = [];
  10487. foreach ($act_segments as $seg) {
  10488. $seg_num = getProp($seg, 'segment_number');
  10489. $seg_content = getProp($seg, 'segment_content');
  10490. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  10491. }
  10492. $act_content = implode("\n", $merged_parts);
  10493. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10494. $segments[] = [
  10495. 'anime_id' => $anime_id,
  10496. 'episode_id' => $episode_id,
  10497. 'episode_number' => $episode_number,
  10498. 'act_number' => getProp($act, 'act_number'),
  10499. 'act_title' => getProp($act, 'act_title'),
  10500. 'act_duration' => getProp($act, 'act_duration'),
  10501. 'act_content' => $act_content,
  10502. 'created_at' => $now,
  10503. 'updated_at' => $now
  10504. ];
  10505. } else {
  10506. foreach ($act_segments as $segment) {
  10507. $voice_actor = getProp($segment, 'voice_actor');
  10508. // 优先从上一集继承音色数据
  10509. $timbre_info = [];
  10510. if (isset($previous_roles_voice[$voice_actor])) {
  10511. // 从上一集继承音色数据
  10512. $timbre_info = $previous_roles_voice[$voice_actor];
  10513. } elseif (isset($role_arr[$voice_actor])) {
  10514. // 使用当前集的主体音色数据
  10515. $timbre_info = $role_arr[$voice_actor];
  10516. }
  10517. $voice_type = getProp($timbre_info, 'voice_type');
  10518. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  10519. if ($timbre_emotion) {
  10520. $timbre_emotion = explode(',', $timbre_emotion);
  10521. } else {
  10522. $timbre_emotion = [];
  10523. }
  10524. $emotion = getProp($segment, 'emotion', '中性');
  10525. if (!in_array($emotion, $timbre_emotion)) {
  10526. $emotion = '中性';
  10527. }
  10528. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  10529. $segments[] = [
  10530. 'anime_id' => $anime_id,
  10531. 'episode_id' => $episode_id,
  10532. 'episode_number' => $episode_number,
  10533. 'act_number' => getProp($act, 'act_number'),
  10534. 'act_title' => getProp($act, 'act_title'),
  10535. 'act_duration' => getProp($act, 'act_duration'),
  10536. 'segment_id' => getProp($segment, 'segment_id'),
  10537. 'segment_number' => getProp($segment, 'segment_number'),
  10538. 'segment_content' => getProp($segment, 'segment_content'),
  10539. 'description' => getProp($segment, 'description'),
  10540. 'composition' => getProp($segment, 'composition'),
  10541. 'camera_movement' => getProp($segment, 'camera_movement'),
  10542. 'voice_actor' => $voice_actor,
  10543. 'dialogue' => getProp($segment, 'dialogue'),
  10544. 'frame_type' => getProp($segment, 'frame_type'),
  10545. 'scene' => getProp($segment, 'scene'),
  10546. 'characters' => getProp($segment, 'characters'),
  10547. 'tail_frame' => getProp($segment, 'tail_frame'),
  10548. 'voice_name' => getProp($timbre_info, 'voice_name'),
  10549. 'voice_type' => $voice_type,
  10550. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  10551. 'emotion' => $emotion,
  10552. 'emotion_type' => $emotion_type,
  10553. 'gender' => getProp($segment, 'gender', '0'),
  10554. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  10555. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  10556. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  10557. 'pitch' => getProp($segment, 'pitch', 0),
  10558. 'created_at' => $now,
  10559. 'updated_at' => $now
  10560. ];
  10561. }
  10562. }
  10563. }
  10564. if ($segments) {
  10565. if ($del_flag) {
  10566. DB::table('mp_episode_segments')
  10567. ->where('anime_id', $anime_id)
  10568. ->where('episode_id', $episode_id)
  10569. ->delete();
  10570. }
  10571. $boolen = DB::table('mp_episode_segments')->insert($segments);
  10572. if (!$boolen) {
  10573. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  10574. Utils::throwError('20003:分镜内容保存失败');
  10575. }
  10576. }
  10577. dLog('deepseek')->info('segments', $segments);
  10578. // ace_mode=1: acts 返回值按合并格式调整
  10579. if ((int)$ace_mode === 1) {
  10580. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  10581. $act_map = [];
  10582. foreach ($table_act_data as $item) {
  10583. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  10584. }
  10585. $restructured_acts = [];
  10586. foreach ($acts as $act) {
  10587. $act_segments = getProp($act, 'segments', []);
  10588. if (!is_array($act_segments)) {
  10589. continue;
  10590. }
  10591. $merged_parts = [];
  10592. foreach ($act_segments as $seg) {
  10593. $seg_num = getProp($seg, 'segment_number');
  10594. $seg_content = getProp($seg, 'segment_content');
  10595. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  10596. }
  10597. $act_content = implode("\n", $merged_parts);
  10598. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10599. $restructured_acts[] = [
  10600. 'anime_id' => $anime_id,
  10601. 'episode_id' => $episode_id,
  10602. 'episode_number' => $episode_number,
  10603. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  10604. 'act_number' => getProp($act, 'act_number'),
  10605. 'act_title' => getProp($act, 'act_title'),
  10606. 'act_duration' => getProp($act, 'act_duration'),
  10607. 'act_content' => $act_content,
  10608. 'created_at' => $now,
  10609. 'updated_at' => $now,
  10610. ];
  10611. }
  10612. $acts = $restructured_acts;
  10613. }
  10614. $episode['episode_id'] = $episode_id;
  10615. $episode['roles'] = $merged_roles;
  10616. $episode['scenes'] = $merged_scenes;
  10617. $episode['props'] = $merged_props;
  10618. $episode['acts'] = $acts;
  10619. return [
  10620. 'episode' => $episode,
  10621. 'episode_id' => $episode_id,
  10622. 'merged_roles' => $merged_roles,
  10623. 'merged_scenes' => $merged_scenes,
  10624. 'merged_props' => $merged_props,
  10625. ];
  10626. }
  10627. private function buildEpisodeItemContent(array $items, string $nameKey): string
  10628. {
  10629. $content = '';
  10630. foreach ($items as $item) {
  10631. $name = trim((string)getProp($item, $nameKey));
  10632. if ($name === '' || $name === '旁白') {
  10633. continue;
  10634. }
  10635. $description = trim((string)getProp($item, 'description'));
  10636. $content .= $name . ': ' . $description;
  10637. if ($nameKey == 'role') {
  10638. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10639. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10640. $voice_name = trim(getProp($item, 'voice_name'));
  10641. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10642. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  10643. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10644. }else {
  10645. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10646. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10647. }
  10648. $content .= "\n";
  10649. }
  10650. return trim($content);
  10651. }
  10652. private function getEpisodeChatContent($animeId, $sequence, $content) {
  10653. if ((int)$sequence <= 0) {
  10654. return [];
  10655. }
  10656. $origin_content = '';
  10657. if ($content) {
  10658. $origin_content = '本集剧情内容:'.$content;
  10659. }else {
  10660. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  10661. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  10662. }
  10663. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  10664. // 获取分集信息
  10665. $episode = DB::table('mp_anime_episodes')
  10666. ->where('anime_id', $animeId)
  10667. ->where('episode_number', $sequence)
  10668. ->where('is_default', 1)
  10669. ->first();
  10670. if (!$episode) {
  10671. return [];
  10672. }
  10673. $episode_id = getProp($episode, 'id');
  10674. $episode_number = getProp($episode, 'episode_number');
  10675. $title = getProp($episode, 'title');
  10676. $intro = getProp($episode, 'intro');
  10677. $art_style = getProp($episode, 'art_style');
  10678. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10679. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10680. // 组装纯文本内容
  10681. $content = '';
  10682. // 添加分集标题和梗概
  10683. $content .= "###第{$episode_number}集:{$title}\n\n";
  10684. $content .= "###故事梗概\n";
  10685. $content .= trim($intro) . "\n\n";
  10686. // 添加美术风格
  10687. $content .= "###美术风格\n";
  10688. $content .= trim($art_style) . "\n\n";
  10689. // 添加主体列表
  10690. $content .= "###主体列表\n";
  10691. $pangbai_voice_prompt = "";
  10692. foreach ($roles as $role) {
  10693. $name = getProp($role, 'role');
  10694. $description = getProp($role, 'description');
  10695. $pic_prompt = getProp($role, 'pic_prompt');
  10696. $voice_prompt = getProp($role, 'voice_prompt');
  10697. $voice_name = getProp($role, 'voice_name');
  10698. $content .= "{$name}: {$description}";
  10699. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10700. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10701. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10702. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  10703. $content .= "\n";
  10704. }
  10705. $content .= "\n";
  10706. // 添加场景列表
  10707. $content .= "###场景列表\n";
  10708. foreach ($scenes as $scene) {
  10709. $name = getProp($scene, 'scene');
  10710. $description = getProp($scene, 'description');
  10711. $pic_prompt = getProp($scene, 'pic_prompt');
  10712. $content .= "{$name}: {$description}";
  10713. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10714. $content .= "\n";
  10715. }
  10716. $content .= "\n";
  10717. // 获取分镜信息
  10718. $segments = DB::table('mp_episode_segments')
  10719. ->where('anime_id', $animeId)
  10720. ->where('episode_id', $episode_id)
  10721. ->orderBy('segment_number')
  10722. ->get();
  10723. if ($segments && count($segments) > 0) {
  10724. if ((int)$ace_mode === 1) {
  10725. $content .= "###分段剧本\n";
  10726. // 获取片段数量
  10727. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  10728. $content .= "片段数量:{$act_count}\n";
  10729. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  10730. $content .= "\n";
  10731. }else {
  10732. $content .= "###分镜剧本\n";
  10733. }
  10734. // 按幕分组
  10735. $currentAct = null;
  10736. foreach ($segments as $segment) {
  10737. $act_number = getProp($segment, 'act_number');
  10738. $act_title = getProp($segment, 'act_title');
  10739. $act_duration = getProp($segment, 'act_duration');
  10740. $segment_number = getProp($segment, 'segment_number');
  10741. $segment_content = getProp($segment, 'segment_content');
  10742. $scene_description = getProp($segment, 'scene_description');
  10743. $scene_name = getProp($segment, 'scene_name');
  10744. $composition = getProp($segment, 'composition');
  10745. $camera_movement = getProp($segment, 'camera_movement');
  10746. $voice_type = getProp($segment, 'voice_type');
  10747. $characters = getProp($segment, 'characters');
  10748. $dialogue = getProp($segment, 'dialogue');
  10749. $frame_type = getProp($segment, 'frame_type');
  10750. $tail_frame_description = getProp($segment, 'tail_frame_description');
  10751. // 判断是否是全能模式
  10752. if ((int)$ace_mode === 1) { // 全能模式
  10753. // 如果是新的分段,添加分段标题
  10754. if ($act_number !== $currentAct) {
  10755. $currentAct = $act_number;
  10756. $content .= "##{$act_title}\n";
  10757. $content .= "时长:{$act_duration}s\n";
  10758. }
  10759. }else {
  10760. // 如果是新的幕,添加幕标题
  10761. if ($act_number !== $currentAct) {
  10762. $currentAct = $act_number;
  10763. $content .= "##第{$act_number}幕:{$scene_name}\n";
  10764. }
  10765. }
  10766. // 添加分镜信息
  10767. $content .= "分镜{$segment_number}\n";
  10768. $content .= "分镜内容:\n{$segment_content}\n";
  10769. // $content .= "画面描述:{$scene_description}\n";
  10770. // $content .= "场景:{$scene_name}\n";
  10771. // $content .= "构图设计:{$composition}\n";
  10772. // $content .= "运镜调度:{$camera_movement}\n";
  10773. // if (!empty($voice_type)) {
  10774. // $content .= "配音角色:{$voice_type}\n";
  10775. // }
  10776. // if (!empty($characters)) {
  10777. // $content .= "出镜角色:{$characters}\n";
  10778. // }
  10779. // if (!empty($dialogue)) {
  10780. // $content .= "台词内容:\"{$dialogue}\"\n";
  10781. // }
  10782. // $content .= "画面类型:{$frame_type}\n";
  10783. // $content .= "尾帧描述:{$tail_frame_description}\n";
  10784. $content .= "\n";
  10785. }
  10786. }
  10787. $content = trim($content);
  10788. if($content) $content = "上集剧本内容:\n{$content}";
  10789. return [
  10790. [
  10791. 'role' => 'user',
  10792. 'content' => $origin_content
  10793. ],
  10794. [
  10795. 'role' => 'assistant',
  10796. 'content' => $content
  10797. ]
  10798. ];
  10799. }
  10800. private function getEpisodeChatMessages($animeId, $sequence): array
  10801. {
  10802. if ((int)$sequence <= 0) {
  10803. return [];
  10804. }
  10805. return DB::table('mp_anime_records')
  10806. ->where('anime_id', $animeId)
  10807. ->where('sequence', $sequence)
  10808. ->where('episode_id', '>', 0)
  10809. ->select('role', 'content')
  10810. ->orderBy('created_at')
  10811. ->orderBy('id')
  10812. ->get()
  10813. ->map(function ($value) {
  10814. return (array)$value;
  10815. })
  10816. ->toArray();
  10817. }
  10818. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  10819. {
  10820. $existingMap = [];
  10821. foreach ($existingItems as $item) {
  10822. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10823. if ($itemKey === '') {
  10824. continue;
  10825. }
  10826. $existingMap[$itemKey] = $item;
  10827. }
  10828. if (!$generatedItems) {
  10829. return array_values($existingItems);
  10830. }
  10831. $merged = [];
  10832. foreach ($generatedItems as $item) {
  10833. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10834. if ($itemKey === '') {
  10835. continue;
  10836. }
  10837. if (isset($existingMap[$itemKey])) {
  10838. if (trim((string)getProp($item, 'description')) === '') {
  10839. $merged[] = $existingMap[$itemKey];
  10840. continue;
  10841. }
  10842. // 检查内容是否发生变化
  10843. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  10844. if (!$isChanged) {
  10845. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  10846. $mergedItem = [
  10847. $nameKey => trim((string)getProp($item, $nameKey)),
  10848. 'description' => trim((string)getProp($item, 'description')),
  10849. ];
  10850. // 如果有 pic_prompt,添加到合并项中
  10851. $picPrompt = getProp($item, 'pic_prompt');
  10852. if (!empty($picPrompt)) {
  10853. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10854. }
  10855. // 继承现有项的 URL
  10856. $existingUrl = getProp($existingMap[$itemKey], 'url');
  10857. if (!empty($existingUrl)) {
  10858. $mergedItem['url'] = $existingUrl;
  10859. }
  10860. // 继承现有项的 task_id
  10861. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  10862. if (!empty($existingTaskId)) {
  10863. $mergedItem['task_id'] = $existingTaskId;
  10864. }
  10865. // 继承现有项的 task_status
  10866. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  10867. if (!empty($existingTaskStatus)) {
  10868. $mergedItem['task_status'] = $existingTaskStatus;
  10869. }
  10870. // 保留生成项的音色字段
  10871. $voiceName = getProp($item, 'voice_name');
  10872. if (!empty($voiceName)) {
  10873. $mergedItem['voice_name'] = $voiceName;
  10874. }
  10875. $voiceType = getProp($item, 'voice_type');
  10876. if (!empty($voiceType)) {
  10877. $mergedItem['voice_type'] = $voiceType;
  10878. }
  10879. $audioUrl = getProp($item, 'voice_audio_url');
  10880. if (!empty($audioUrl)) {
  10881. $mergedItem['voice_audio_url'] = $audioUrl;
  10882. }
  10883. $merged[] = $mergedItem;
  10884. } else {
  10885. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  10886. $mergedItem = [
  10887. $nameKey => trim((string)getProp($item, $nameKey)),
  10888. 'description' => trim((string)getProp($item, 'description')),
  10889. ];
  10890. // 如果有 pic_prompt,添加到合并项中
  10891. $picPrompt = getProp($item, 'pic_prompt');
  10892. if (!empty($picPrompt)) {
  10893. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10894. }
  10895. // 保留生成项的音色字段
  10896. $voiceName = getProp($item, 'voice_name');
  10897. if (!empty($voiceName)) {
  10898. $mergedItem['voice_name'] = $voiceName;
  10899. }
  10900. $voiceType = getProp($item, 'voice_type');
  10901. if (!empty($voiceType)) {
  10902. $mergedItem['voice_type'] = $voiceType;
  10903. }
  10904. $audioUrl = getProp($item, 'voice_audio_url');
  10905. if (!empty($audioUrl)) {
  10906. $mergedItem['voice_audio_url'] = $audioUrl;
  10907. }
  10908. // 不继承 URL、task_id 和 task_status(重置状态)
  10909. $merged[] = $mergedItem;
  10910. }
  10911. } else {
  10912. // 新增项,保留生成项的所有字段
  10913. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  10914. }
  10915. }
  10916. return $merged ?: array_values($existingItems);
  10917. }
  10918. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  10919. {
  10920. $resetItem = [
  10921. $nameKey => trim((string)getProp($item, $nameKey)),
  10922. 'description' => trim((string)getProp($item, 'description')),
  10923. ];
  10924. // 保留指定的字段
  10925. foreach ($preserveFields as $field) {
  10926. $value = getProp($item, $field);
  10927. if (!empty($value)) {
  10928. $resetItem[$field] = $value;
  10929. }
  10930. }
  10931. return $resetItem;
  10932. }
  10933. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  10934. {
  10935. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  10936. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  10937. if ($existingKey !== $generatedKey) {
  10938. return true;
  10939. }
  10940. // 比较 description 是否变化
  10941. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  10942. return true;
  10943. }
  10944. // 比较 pic_prompt 是否变化
  10945. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  10946. }
  10947. private function normalizeEpisodeResourceKey($value): string
  10948. {
  10949. $value = trim((string)$value);
  10950. if ($value === '') {
  10951. return '';
  10952. }
  10953. return strtolower((string)preg_replace('/\s+/u', '', $value));
  10954. }
  10955. // 生成全局角色图片
  10956. private function batchSetGlobalRoleImg($data, $is_force=false) {
  10957. $anime_id = getProp($data, 'anime_id');
  10958. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10959. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10960. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10961. $art_style = getProp($anime, 'art_style');
  10962. $update_flag = false;
  10963. foreach ($roles as &$role) {
  10964. $role_name = getProp($role, 'role');
  10965. if ($role_name == '旁白') continue;
  10966. // 优先使用 pic_prompt,如果没有则使用 description
  10967. $pic_prompt = getProp($role, 'pic_prompt');
  10968. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10969. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10970. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10971. // 参考图地址
  10972. $ref_img_url = getProp($role, 'url');
  10973. if (!$is_force && $ref_img_url) continue;
  10974. $update_flag = true;
  10975. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10976. try {
  10977. $params = [
  10978. 'prompt' => $description,
  10979. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  10980. 'ref_img_urls' => []
  10981. ];
  10982. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10983. $task_id = $task->id;
  10984. if (!$task_id) {
  10985. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  10986. }
  10987. $role['task_id'] = $task_id;
  10988. $role['task_status'] = 'processing';
  10989. } catch (\Exception $e) {
  10990. Utils::throwError("20003:" . $e->getMessage());
  10991. }
  10992. }
  10993. if (!$update_flag) return true;
  10994. // 保存角色信息
  10995. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10996. 'roles' => json_encode($roles, 256),
  10997. 'generate_status' => '执行中',
  10998. 'generate_at' => date('Y-m-d H:i:s'),
  10999. 'updated_at' => date('Y-m-d H:i:s')
  11000. ]);
  11001. if (!$boolen) {
  11002. Utils::throwError('20003:保存角色信息失败');
  11003. }
  11004. return $boolen;
  11005. }
  11006. // 生成全局场景图片
  11007. private function batchSetGlobalSceneImg($data, $is_force=false) {
  11008. $anime_id = getProp($data, 'anime_id');
  11009. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11010. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11011. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11012. $art_style = getProp($anime, 'art_style');
  11013. $update_flag = false;
  11014. foreach ($scenes as &$scene) {
  11015. $scene_name = getProp($scene, 'scene');
  11016. // 优先使用 pic_prompt,如果没有则使用 description
  11017. $pic_prompt = getProp($scene, 'pic_prompt');
  11018. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11019. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  11020. // 参考图地址
  11021. $ref_img_url = getProp($scene, 'url');
  11022. if (!$is_force && $ref_img_url) continue;
  11023. $update_flag = true;
  11024. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11025. try {
  11026. $params = [
  11027. 'prompt' => $description,
  11028. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  11029. 'ref_img_urls' => []
  11030. ];
  11031. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11032. $task_id = $task->id;
  11033. if (!$task_id) {
  11034. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  11035. }
  11036. $scene['task_id'] = $task_id;
  11037. $scene['task_status'] = 'processing';
  11038. } catch (\Exception $e) {
  11039. Utils::throwError("20003:" . $e->getMessage());
  11040. }
  11041. }
  11042. if (!$update_flag) return true;
  11043. // 保存角色信息
  11044. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11045. 'scenes' => json_encode($scenes, 256),
  11046. 'generate_status' => '执行中',
  11047. 'generate_at' => date('Y-m-d H:i:s'),
  11048. 'updated_at' => date('Y-m-d H:i:s')
  11049. ]);
  11050. if (!$boolen) {
  11051. Utils::throwError('20003:保存角色信息失败');
  11052. }
  11053. return $boolen;
  11054. }
  11055. // 生成分镜主体、场景和道具图片
  11056. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  11057. $character_prefix = '';
  11058. $scene_prefix = '';
  11059. $prop_prefix = '';
  11060. if ($art_style_type) {
  11061. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  11062. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  11063. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  11064. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  11065. }
  11066. $update_flag = false;
  11067. // 获取上一集的roles、scenes和props数据
  11068. $prev_roles = [];
  11069. $prev_scenes = [];
  11070. $prev_props = [];
  11071. if ($episode_number > 1) {
  11072. $prev_episode = DB::table('mp_anime_episodes')
  11073. ->where('anime_id', $anime_id)
  11074. ->where('episode_number', $episode_number - 1)
  11075. ->where('is_default', 1)
  11076. ->first();
  11077. if ($prev_episode) {
  11078. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  11079. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  11080. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  11081. dLog('deepseek')->info("获取上一集数据成功", [
  11082. 'anime_id' => $anime_id,
  11083. 'prev_episode_number' => $episode_number - 1,
  11084. 'prev_roles_count' => count($prev_roles),
  11085. 'prev_scenes_count' => count($prev_scenes),
  11086. 'prev_props_count' => count($prev_props)
  11087. ]);
  11088. }
  11089. }
  11090. // 处理角色图片生成
  11091. foreach ($roles as &$role) {
  11092. $role_name = getProp($role, 'role');
  11093. if ($role_name == '旁白') continue;
  11094. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  11095. if (isset($ref_products[$role_name])) {
  11096. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  11097. if ($role['url']) continue;
  11098. }
  11099. $role_description = getProp($role, 'description');
  11100. $role_pic_prompt = getProp($role, 'pic_prompt');
  11101. $role_url = getProp($role, 'url');
  11102. // 检查是否可以从上一集继承
  11103. $inherited = false;
  11104. if (!$is_force && !empty($prev_roles)) {
  11105. foreach ($prev_roles as $prev_role) {
  11106. $prev_role_name = getProp($prev_role, 'role');
  11107. $prev_description = getProp($prev_role, 'description');
  11108. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  11109. $prev_url = getProp($prev_role, 'url');
  11110. $prev_task_id = getProp($prev_role, 'task_id');
  11111. $prev_task_status = getProp($prev_role, 'task_status');
  11112. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  11113. if ($role_name == $prev_role_name
  11114. && $role_description == $prev_description
  11115. && $role_pic_prompt == $prev_pic_prompt
  11116. && !empty($prev_url)) {
  11117. $role['task_id'] = $prev_task_id;
  11118. $role['task_status'] = $prev_task_status;
  11119. $role['url'] = $prev_url;
  11120. $inherited = true;
  11121. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  11122. 'anime_id' => $anime_id,
  11123. 'episode_number' => $episode_number,
  11124. 'task_id' => $prev_task_id,
  11125. 'url' => $prev_url
  11126. ]);
  11127. break;
  11128. }
  11129. }
  11130. }
  11131. // 如果已继承或已有url,跳过生成
  11132. if ($inherited || (!$is_force && $role_url)) {
  11133. continue;
  11134. }
  11135. // 优先使用 pic_prompt,如果没有则使用 description
  11136. $pic_prompt = getProp($role, 'pic_prompt');
  11137. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11138. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11139. $update_flag = true;
  11140. // 调用AIImageGenerationService的生成图片任务接口
  11141. try {
  11142. $params = [
  11143. 'prompt' => $description,
  11144. 'ref_img_urls' => []
  11145. ];
  11146. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11147. $task_id = $task->id;
  11148. if (!$task_id) {
  11149. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  11150. continue; // 不中断,继续处理其他角色
  11151. }
  11152. $role['task_id'] = $task_id;
  11153. $role['task_status'] = 'processing';
  11154. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  11155. 'anime_id' => $anime_id,
  11156. 'episode_number' => $episode_number,
  11157. 'task_id' => $task_id
  11158. ]);
  11159. } catch (\Exception $e) {
  11160. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  11161. // 不抛出异常,继续处理其他角色
  11162. }
  11163. }
  11164. // 处理场景图片生成
  11165. foreach ($scenes as &$scene) {
  11166. $scene_name = getProp($scene, 'scene');
  11167. $scene_description = getProp($scene, 'description');
  11168. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  11169. $scene_url = getProp($scene, 'url');
  11170. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  11171. if (isset($ref_products[$scene_name])) {
  11172. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  11173. if ($scene['url']) continue;
  11174. }
  11175. // 检查是否可以从上一集继承
  11176. $inherited = false;
  11177. if (!$is_force && !empty($prev_scenes)) {
  11178. foreach ($prev_scenes as $prev_scene) {
  11179. $prev_scene_name = getProp($prev_scene, 'scene');
  11180. $prev_description = getProp($prev_scene, 'description');
  11181. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  11182. $prev_url = getProp($prev_scene, 'url');
  11183. $prev_task_id = getProp($prev_scene, 'task_id');
  11184. $prev_task_status = getProp($prev_scene, 'task_status');
  11185. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  11186. if ($scene_name == $prev_scene_name
  11187. && $scene_description == $prev_description
  11188. && $scene_pic_prompt == $prev_pic_prompt
  11189. && !empty($prev_url)) {
  11190. $scene['task_id'] = $prev_task_id;
  11191. $scene['task_status'] = $prev_task_status;
  11192. $scene['url'] = $prev_url;
  11193. $inherited = true;
  11194. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  11195. 'anime_id' => $anime_id,
  11196. 'episode_number' => $episode_number,
  11197. 'task_id' => $prev_task_id,
  11198. 'url' => $prev_url
  11199. ]);
  11200. break;
  11201. }
  11202. }
  11203. }
  11204. // 如果已继承或已有url,跳过生成
  11205. if ($inherited || (!$is_force && $scene_url)) {
  11206. continue;
  11207. }
  11208. // 优先使用 pic_prompt,如果没有则使用 description
  11209. $pic_prompt = getProp($scene, 'pic_prompt');
  11210. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11211. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11212. $update_flag = true;
  11213. // 调用AIImageGenerationService的生成图片任务接口
  11214. try {
  11215. $params = [
  11216. 'prompt' => $description,
  11217. 'ref_img_urls' => []
  11218. ];
  11219. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11220. $task_id = $task->id;
  11221. if (!$task_id) {
  11222. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  11223. continue; // 不中断,继续处理其他场景
  11224. }
  11225. $scene['task_id'] = $task_id;
  11226. $scene['task_status'] = 'processing';
  11227. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  11228. 'anime_id' => $anime_id,
  11229. 'episode_number' => $episode_number,
  11230. 'task_id' => $task_id
  11231. ]);
  11232. } catch (\Exception $e) {
  11233. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  11234. // 不抛出异常,继续处理其他场景
  11235. }
  11236. }
  11237. // 处理道具图片生成(逻辑与场景一致)
  11238. foreach ($props as &$prop) {
  11239. $prop_name = getProp($prop, 'prop');
  11240. $prop_description = getProp($prop, 'description');
  11241. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  11242. $prop_url = getProp($prop, 'url');
  11243. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  11244. if (isset($ref_products[$prop_name])) {
  11245. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  11246. if ($prop['url']) continue;
  11247. }
  11248. // 检查是否可以从上一集继承
  11249. $inherited = false;
  11250. if (!$is_force && !empty($prev_props)) {
  11251. foreach ($prev_props as $prev_prop) {
  11252. $prev_prop_name = getProp($prev_prop, 'prop');
  11253. $prev_description = getProp($prev_prop, 'description');
  11254. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  11255. $prev_url = getProp($prev_prop, 'url');
  11256. $prev_task_id = getProp($prev_prop, 'task_id');
  11257. $prev_task_status = getProp($prev_prop, 'task_status');
  11258. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  11259. if ($prop_name == $prev_prop_name
  11260. && $prop_description == $prev_description
  11261. && $prop_pic_prompt == $prev_pic_prompt
  11262. && !empty($prev_url)) {
  11263. $prop['task_id'] = $prev_task_id;
  11264. $prop['task_status'] = $prev_task_status;
  11265. $prop['url'] = $prev_url;
  11266. $inherited = true;
  11267. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  11268. 'anime_id' => $anime_id,
  11269. 'episode_number' => $episode_number,
  11270. 'task_id' => $prev_task_id,
  11271. 'url' => $prev_url
  11272. ]);
  11273. break;
  11274. }
  11275. }
  11276. }
  11277. // 如果已继承或已有url,跳过生成
  11278. if ($inherited || (!$is_force && $prop_url)) {
  11279. continue;
  11280. }
  11281. // 优先使用 pic_prompt,如果没有则使用 description
  11282. $pic_prompt = getProp($prop, 'pic_prompt');
  11283. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  11284. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11285. $update_flag = true;
  11286. // 调用AIImageGenerationService的生成图片任务接口
  11287. try {
  11288. $params = [
  11289. 'prompt' => $description,
  11290. 'ref_img_urls' => []
  11291. ];
  11292. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11293. $task_id = $task->id;
  11294. if (!$task_id) {
  11295. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11296. continue; // 不中断,继续处理其他道具
  11297. }
  11298. $prop['task_id'] = $task_id;
  11299. $prop['task_status'] = 'processing';
  11300. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11301. 'anime_id' => $anime_id,
  11302. 'episode_number' => $episode_number,
  11303. 'task_id' => $task_id
  11304. ]);
  11305. } catch (\Exception $e) {
  11306. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11307. // 不抛出异常,继续处理其他道具
  11308. }
  11309. }
  11310. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11311. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11312. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11313. // // 保存剧集的角色和场景信息
  11314. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11315. // 'roles' => json_encode($roles, 256),
  11316. // 'scenes' => json_encode($scenes, 256),
  11317. // 'generate_status' => '执行中',
  11318. // 'generate_at' => date('Y-m-d H:i:s'),
  11319. // 'updated_at' => date('Y-m-d H:i:s')
  11320. // ]);
  11321. // if (!$boolen) {
  11322. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11323. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11324. // }
  11325. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11326. // 'episode_id' => $episode_id,
  11327. 'roles_count' => count($roles),
  11328. 'scenes_count' => count($scenes),
  11329. 'props_count' => count($props)
  11330. ]);
  11331. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11332. }
  11333. /**
  11334. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11335. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11336. *
  11337. * @param int $anime_id 动漫对话ID
  11338. * @param array $episode_roles 剧集角色数据
  11339. * @param array $episode_scenes 剧集场景数据
  11340. * @param array $episode_props 剧集道具数据
  11341. * @return bool
  11342. */
  11343. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11344. // 获取全局数据
  11345. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11346. if (!$anime) {
  11347. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11348. return false;
  11349. }
  11350. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11351. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11352. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11353. $roles_added = false;
  11354. $roles_updated = false;
  11355. $scenes_added = false;
  11356. $props_added = false;
  11357. // 处理角色同步
  11358. foreach ($episode_roles as $episode_role) {
  11359. $episode_role_name = getProp($episode_role, 'role');
  11360. $episode_description = getProp($episode_role, 'description');
  11361. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11362. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11363. // 跳过旁白
  11364. if ($episode_role_name == '旁白') {
  11365. continue;
  11366. }
  11367. // 检查全局中是否已存在相同的角色
  11368. $exists = false;
  11369. $global_role_index = -1;
  11370. foreach ($global_roles as $index => $global_role) {
  11371. $global_role_name = getProp($global_role, 'role');
  11372. $global_description = getProp($global_role, 'description');
  11373. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11374. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11375. if ($episode_role_name == $global_role_name
  11376. && $episode_description == $global_description
  11377. && $episode_pic_prompt == $global_pic_prompt) {
  11378. $exists = true;
  11379. $global_role_index = $index;
  11380. break;
  11381. }
  11382. }
  11383. // 如果不存在,则添加到全局
  11384. if (!$exists) {
  11385. $global_roles[] = $episode_role;
  11386. $roles_added = true;
  11387. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11388. 'anime_id' => $anime_id,
  11389. 'role' => $episode_role_name
  11390. ]);
  11391. } else {
  11392. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11393. if (!empty($episode_voice_prompt)) {
  11394. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11395. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11396. if ($global_voice_prompt !== $episode_voice_prompt) {
  11397. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11398. $roles_updated = true;
  11399. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11400. 'anime_id' => $anime_id,
  11401. 'role' => $episode_role_name,
  11402. 'voice_prompt' => $episode_voice_prompt
  11403. ]);
  11404. }
  11405. }
  11406. }
  11407. }
  11408. // 处理场景同步
  11409. foreach ($episode_scenes as $episode_scene) {
  11410. $episode_scene_name = getProp($episode_scene, 'scene');
  11411. $episode_description = getProp($episode_scene, 'description');
  11412. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11413. // 检查全局中是否已存在相同的场景
  11414. $exists = false;
  11415. foreach ($global_scenes as $global_scene) {
  11416. $global_scene_name = getProp($global_scene, 'scene');
  11417. $global_description = getProp($global_scene, 'description');
  11418. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11419. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  11420. if ($episode_scene_name == $global_scene_name
  11421. && $episode_description == $global_description
  11422. && $episode_pic_prompt == $global_pic_prompt) {
  11423. $exists = true;
  11424. break;
  11425. }
  11426. }
  11427. // 如果不存在,则添加到全局
  11428. if (!$exists) {
  11429. $global_scenes[] = $episode_scene;
  11430. $scenes_added = true;
  11431. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  11432. 'anime_id' => $anime_id,
  11433. 'scene' => $episode_scene_name
  11434. ]);
  11435. }
  11436. }
  11437. // 处理道具同步(逻辑与场景一致)
  11438. foreach ($episode_props as $episode_prop) {
  11439. $episode_prop_name = getProp($episode_prop, 'prop');
  11440. $episode_description = getProp($episode_prop, 'description');
  11441. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  11442. // 检查全局中是否已存在相同的道具
  11443. $exists = false;
  11444. foreach ($global_props as $global_prop) {
  11445. $global_prop_name = getProp($global_prop, 'prop');
  11446. $global_description = getProp($global_prop, 'description');
  11447. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  11448. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  11449. if ($episode_prop_name == $global_prop_name
  11450. && $episode_description == $global_description
  11451. && $episode_pic_prompt == $global_pic_prompt) {
  11452. $exists = true;
  11453. break;
  11454. }
  11455. }
  11456. // 如果不存在,则添加到全局
  11457. if (!$exists) {
  11458. $global_props[] = $episode_prop;
  11459. $props_added = true;
  11460. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  11461. 'anime_id' => $anime_id,
  11462. 'prop' => $episode_prop_name
  11463. ]);
  11464. }
  11465. }
  11466. // 如果有新增或更新,则更新全局数据
  11467. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  11468. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11469. if ($roles_added || $roles_updated) {
  11470. $update_data['roles'] = json_encode($global_roles, 256);
  11471. }
  11472. if ($scenes_added) {
  11473. $update_data['scenes'] = json_encode($global_scenes, 256);
  11474. }
  11475. if ($props_added) {
  11476. $update_data['props'] = json_encode($global_props, 256);
  11477. }
  11478. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11479. dLog('deepseek')->info('剧集数据同步到全局完成', [
  11480. 'anime_id' => $anime_id,
  11481. 'roles_added' => $roles_added,
  11482. 'roles_updated' => $roles_updated,
  11483. 'scenes_added' => $scenes_added,
  11484. 'props_added' => $props_added,
  11485. 'global_roles_count' => count($global_roles),
  11486. 'global_scenes_count' => count($global_scenes),
  11487. 'global_props_count' => count($global_props)
  11488. ]);
  11489. }
  11490. return true;
  11491. }
  11492. /**
  11493. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  11494. *
  11495. * @param int $anime_id 动漫对话ID
  11496. * @param int $episode_id 分集ID
  11497. * @return bool
  11498. */
  11499. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  11500. // 获取全局角色和场景数据
  11501. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11502. if (!$anime) {
  11503. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11504. return false;
  11505. }
  11506. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11507. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11508. // 获取指定的分集
  11509. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  11510. if (!$episode) {
  11511. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11512. return false;
  11513. }
  11514. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11515. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11516. $roles_updated = false;
  11517. $scenes_updated = false;
  11518. // 继承角色的task_id、task_status和url
  11519. foreach ($episode_roles as &$episode_role) {
  11520. $episode_role_name = getProp($episode_role, 'role');
  11521. $episode_description = getProp($episode_role, 'description');
  11522. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11523. $episode_url = getProp($episode_role, 'url');
  11524. // 跳过旁白角色
  11525. if ($episode_role_name == '旁白') {
  11526. continue;
  11527. }
  11528. // 如果剧集中已有URL,跳过
  11529. if (!empty($episode_url)) {
  11530. continue;
  11531. }
  11532. // 遍历全局角色数据,查找匹配的角色
  11533. foreach ($global_roles as $global_role) {
  11534. $global_role_name = getProp($global_role, 'role');
  11535. $global_description = getProp($global_role, 'description');
  11536. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11537. $global_url = getProp($global_role, 'url');
  11538. $global_task_id = getProp($global_role, 'task_id');
  11539. $global_task_status = getProp($global_role, 'task_status');
  11540. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11541. if ($episode_role_name == $global_role_name
  11542. && $episode_description == $global_description
  11543. && $episode_pic_prompt == $global_pic_prompt) {
  11544. // 继承 task_id、task_status 和 url
  11545. if (!empty($global_task_id)) {
  11546. $episode_role['task_id'] = $global_task_id;
  11547. $episode_role['task_status'] = $global_task_status;
  11548. $roles_updated = true;
  11549. dLog('deepseek')->info('剧集角色继承全局task_id', [
  11550. 'episode_id' => $episode_id,
  11551. 'role' => $episode_role_name,
  11552. 'task_id' => $global_task_id,
  11553. 'task_status' => $global_task_status
  11554. ]);
  11555. }
  11556. if (!empty($global_url)) {
  11557. $episode_role['url'] = $global_url;
  11558. $roles_updated = true;
  11559. dLog('deepseek')->info('剧集角色继承全局url', [
  11560. 'episode_id' => $episode_id,
  11561. 'role' => $episode_role_name,
  11562. 'url' => $global_url
  11563. ]);
  11564. }
  11565. break;
  11566. }
  11567. }
  11568. }
  11569. // 继承场景的task_id、task_status和url
  11570. foreach ($episode_scenes as &$episode_scene) {
  11571. $episode_scene_name = getProp($episode_scene, 'scene');
  11572. $episode_description = getProp($episode_scene, 'description');
  11573. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11574. $episode_url = getProp($episode_scene, 'url');
  11575. // 如果剧集中已有URL,跳过
  11576. if (!empty($episode_url)) {
  11577. continue;
  11578. }
  11579. // 遍历全局场景数据,查找匹配的场景
  11580. foreach ($global_scenes as $global_scene) {
  11581. $global_scene_name = getProp($global_scene, 'scene');
  11582. $global_description = getProp($global_scene, 'description');
  11583. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11584. $global_url = getProp($global_scene, 'url');
  11585. $global_task_id = getProp($global_scene, 'task_id');
  11586. $global_task_status = getProp($global_scene, 'task_status');
  11587. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11588. if ($episode_scene_name == $global_scene_name
  11589. && $episode_description == $global_description
  11590. && $episode_pic_prompt == $global_pic_prompt) {
  11591. // 继承 task_id、task_status 和 url
  11592. if (!empty($global_task_id)) {
  11593. $episode_scene['task_id'] = $global_task_id;
  11594. $episode_scene['task_status'] = $global_task_status;
  11595. $scenes_updated = true;
  11596. dLog('deepseek')->info('剧集场景继承全局task_id', [
  11597. 'episode_id' => $episode_id,
  11598. 'scene' => $episode_scene_name,
  11599. 'task_id' => $global_task_id,
  11600. 'task_status' => $global_task_status
  11601. ]);
  11602. }
  11603. if (!empty($global_url)) {
  11604. $episode_scene['url'] = $global_url;
  11605. $scenes_updated = true;
  11606. dLog('deepseek')->info('剧集场景继承全局url', [
  11607. 'episode_id' => $episode_id,
  11608. 'scene' => $episode_scene_name,
  11609. 'url' => $global_url
  11610. ]);
  11611. }
  11612. break;
  11613. }
  11614. }
  11615. }
  11616. // 如果有更新,则保存到数据库
  11617. if ($roles_updated || $scenes_updated) {
  11618. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11619. if ($roles_updated) {
  11620. $update_data['roles'] = json_encode($episode_roles, 256);
  11621. }
  11622. if ($scenes_updated) {
  11623. $update_data['scenes'] = json_encode($episode_scenes, 256);
  11624. }
  11625. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  11626. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  11627. 'episode_id' => $episode_id,
  11628. 'roles_updated' => $roles_updated,
  11629. 'scenes_updated' => $scenes_updated
  11630. ]);
  11631. }
  11632. return true;
  11633. }
  11634. public function chatChangeImg($data) {
  11635. $segment = getProp($data, 'segment');
  11636. $segment_content = getProp($segment, 'segment_content');
  11637. $prompt = getProp($data, 'prompt');
  11638. $ref_img = getProp($data, 'ref_img');
  11639. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  11640. // 处理文本模型
  11641. $model = getProp($data, 'model');
  11642. if (!$model) {
  11643. // 用户没有输入,从anime表获取
  11644. $segment_id = getProp($segment, 'segment_id');
  11645. if ($segment_id) {
  11646. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  11647. if ($episode_id) {
  11648. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  11649. if ($anime_id) {
  11650. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  11651. }
  11652. }
  11653. }
  11654. if (!$model) {
  11655. // anime表也没有,使用默认值
  11656. $model = 'doubao-seed-2-0-mini-260215';
  11657. }
  11658. }
  11659. // 验证模型是否在可用模型表中
  11660. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11661. $model = 'doubao-seed-2-0-mini-260215';
  11662. }
  11663. $messages[] =
  11664. [
  11665. 'role' => 'user',
  11666. 'content' => $question
  11667. ];
  11668. $post_data = [
  11669. 'model' => $model,
  11670. 'messages' => $messages,
  11671. // 'max_tokens' => 8192,
  11672. 'temperature' => 0.7,
  11673. 'frequency_penalty' => 0,
  11674. 'presence_penalty' => 0,
  11675. 'response_format' => ['type' => 'text'],
  11676. 'stream' => false // 是否启用流式输出
  11677. ];
  11678. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11679. // DeepSeek 官方模型使用 DeepSeek API
  11680. $chatResult = $this->chatOnly($post_data);
  11681. } else if (in_array($model, $this->gpt_text_models)) {
  11682. // GPT-5.4 模型使用 TokenRouter API
  11683. $chatResult = $this->gpt54ChatOnly($post_data);
  11684. } else {
  11685. // 其他模型使用火山引擎API
  11686. $chatResult = $this->volcEngineChatCompletion($post_data);
  11687. }
  11688. if (is_array($chatResult)) {
  11689. extract($chatResult);
  11690. }else {
  11691. Utils::throwError('20003: 接口调用失败!');
  11692. }
  11693. return [
  11694. 'type' => 'done',
  11695. // 'episode' => $episode,
  11696. 'answer' => $fullContent,
  11697. 'reasoning' => $fullReasoningContent,
  11698. 'usage' => $usage
  11699. ];
  11700. }
  11701. /**
  11702. * 仅调用 deepseek 对话接口(非流式)
  11703. *
  11704. * @param array $post_data
  11705. * @param int $timeout
  11706. * @return array
  11707. */
  11708. private function chatOnly($post_data, $timeout = 1800) {
  11709. $post_data['max_tokens'] = 300000;
  11710. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  11711. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  11712. $response = $result->getBody()->getContents();
  11713. $response_arr = json_decode($response, true);
  11714. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  11715. $fullContent = '';
  11716. $fullReasoningContent = [];
  11717. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11718. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11719. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11720. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  11721. }
  11722. return [
  11723. 'fullContent' => $fullContent,
  11724. 'fullReasoningContent' => $fullReasoningContent,
  11725. 'usage' => $usage
  11726. ];
  11727. }
  11728. /**
  11729. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  11730. *
  11731. * @param string $errorMessage
  11732. * @return string|null
  11733. */
  11734. public function analyzeErrorMessage($errorMessage)
  11735. {
  11736. try {
  11737. $post_data = [
  11738. 'model' => 'deepseek-v4-flash',
  11739. 'messages' => [
  11740. [
  11741. 'role' => 'system',
  11742. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  11743. ],
  11744. [
  11745. 'role' => 'user',
  11746. 'content' => (string)$errorMessage,
  11747. ],
  11748. ],
  11749. 'temperature' => 0.3,
  11750. 'frequency_penalty' => 0,
  11751. 'presence_penalty' => 0,
  11752. 'response_format' => ['type' => 'text'],
  11753. 'stream' => false,
  11754. ];
  11755. $result = $this->chatOnly($post_data, 8);
  11756. $content = trim((string)($result['fullContent'] ?? ''));
  11757. if ($content === '') {
  11758. return null;
  11759. }
  11760. return mb_substr($content, 0, 50);
  11761. } catch (\Exception $e) {
  11762. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  11763. 'error_message' => $errorMessage
  11764. ]);
  11765. return null;
  11766. }
  11767. }
  11768. // 仅调用 GPT-5.4 对话接口(非流式)
  11769. private function gpt54ChatOnly($post_data) {
  11770. $apiKey = env('GPT_54_API_KEY');
  11771. if (empty($apiKey)) {
  11772. Utils::throwError('20003:GPT-5.4 API Key未配置');
  11773. }
  11774. // 先探活,服务不可用时自动重试
  11775. $this->ensureGptServiceAvailable();
  11776. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11777. $headers = [
  11778. 'Authorization' => 'Bearer ' . $apiKey,
  11779. 'Content-Type' => 'application/json'
  11780. ];
  11781. // 移除 thinking 参数,GPT-5.4 不支持
  11782. if (isset($post_data['thinking'])) {
  11783. unset($post_data['thinking']);
  11784. }
  11785. if (isset($post_data['reasoning_effort'])) {
  11786. unset($post_data['reasoning_effort']);
  11787. }
  11788. $post_data['max_completion_tokens'] = 100000;
  11789. // 确保 stream 为 false
  11790. $post_data['stream'] = false;
  11791. $maxRetries = $this->gptRetryTimes();
  11792. $interval = $this->gptRetryInterval();
  11793. $attempt = 0;
  11794. while (true) {
  11795. try {
  11796. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  11797. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  11798. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  11799. 'json' => $post_data,
  11800. 'headers' => $headers
  11801. ]);
  11802. $response = $result->getBody()->getContents();
  11803. $response_arr = json_decode($response, true);
  11804. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  11805. $fullContent = '';
  11806. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11807. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11808. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11809. }
  11810. return [
  11811. 'fullContent' => $fullContent,
  11812. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  11813. 'usage' => $usage
  11814. ];
  11815. } catch (\Exception $e) {
  11816. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  11817. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  11818. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  11819. throw $e;
  11820. }
  11821. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  11822. 'retry' => $attempt + 1,
  11823. 'max_retries' => $maxRetries,
  11824. 'error' => $e->getMessage()
  11825. ]);
  11826. sleep($interval);
  11827. $attempt++;
  11828. }
  11829. }
  11830. }
  11831. private function splitContent($content) {
  11832. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  11833. $chapters = [];
  11834. // 匹配章节标题格式:
  11835. // 1. 标题可能独占一行,也可能在正文末尾或中间
  11836. // 2. 格式支持:
  11837. // - **第一集**
  11838. // - 第一集:
  11839. // - ###第1章 重生
  11840. // - ##第2章 相救
  11841. // - 第三章 共处一室
  11842. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  11843. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  11844. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  11845. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  11846. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  11847. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  11848. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  11849. // 先在每个标题前插入换行符(如果前面不是换行的话)
  11850. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  11851. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  11852. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  11853. // 用正则找出所有章节标题的位置
  11854. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  11855. $titleCount = count($matches[0]);
  11856. for ($i = 0; $i < $titleCount; $i++) {
  11857. // 获取当前章节标题
  11858. $titleLine = trim($matches[0][$i][0]);
  11859. // 去除标题开头的特殊符号
  11860. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  11861. // 去除标题结尾的冒号和特殊符号
  11862. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  11863. $cleanTitle = trim($cleanTitle);
  11864. // 获取当前标题的结束位置
  11865. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  11866. // 获取下一个章节标题的开始位置(如果存在)
  11867. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  11868. // 提取章节内容(从标题结束到下一个标题开始)
  11869. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  11870. // 清理内容:去除前后空白和分隔线
  11871. $chapterContent = trim($chapterContent);
  11872. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  11873. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  11874. if (!empty($cleanTitle) && !empty($chapterContent)) {
  11875. $chapters[] = [
  11876. 'title' => $cleanTitle,
  11877. 'content' => $chapterContent
  11878. ];
  11879. }
  11880. }
  11881. } else {
  11882. // 如果没有匹配到章节,返回整个内容
  11883. $chapters[] = [
  11884. 'title' => '',
  11885. 'content' => $content
  11886. ];
  11887. }
  11888. return $chapters;
  11889. }
  11890. public function getContentByBid($bid) {
  11891. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  11892. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  11893. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  11894. $content = '';
  11895. foreach ($chapters as $chapter) {
  11896. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  11897. }
  11898. return $content;
  11899. }
  11900. public function getContentByScriptId($script_id) {
  11901. $content = '';
  11902. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  11903. if ($contents) {
  11904. $content = implode(PHP_EOL, $contents);
  11905. }else {
  11906. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  11907. }
  11908. return $content;
  11909. }
  11910. /**
  11911. * 根据文件类型提取文本内容
  11912. *
  11913. * @param mixed $file 文件对象或文件路径
  11914. * @return string
  11915. */
  11916. public function extractFileContent($file) {
  11917. // 获取文件路径和扩展名
  11918. if (is_string($file)) {
  11919. $filePath = $file;
  11920. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  11921. } else {
  11922. // Laravel UploadedFile 对象
  11923. $filePath = $file->getRealPath();
  11924. $extension = strtolower($file->getClientOriginalExtension());
  11925. }
  11926. $content = '';
  11927. switch ($extension) {
  11928. case 'txt':
  11929. $content = $this->extractTxtContent($filePath);
  11930. break;
  11931. case 'pdf':
  11932. $content = $this->extractPdfContent($filePath);
  11933. break;
  11934. case 'doc':
  11935. case 'docx':
  11936. $content = $this->extractWordContent($filePath);
  11937. break;
  11938. // case 'jpg':
  11939. // case 'jpeg':
  11940. // case 'png':
  11941. // case 'gif':
  11942. // case 'bmp':
  11943. // case 'webp':
  11944. // $content = $this->extractImageContent($filePath);
  11945. // break;
  11946. default:
  11947. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  11948. }
  11949. return $content;
  11950. }
  11951. /**
  11952. * 提取 TXT 文件内容
  11953. */
  11954. private function extractTxtContent($filePath) {
  11955. if (!file_exists($filePath)) {
  11956. Utils::throwError('20003:文件不存在');
  11957. }
  11958. $content = file_get_contents($filePath);
  11959. // 尝试检测并转换编码
  11960. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  11961. if ($encoding && $encoding !== 'UTF-8') {
  11962. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  11963. }
  11964. return trim($content);
  11965. }
  11966. /**
  11967. * 提取 PDF 文件内容
  11968. */
  11969. private function extractPdfContent($filePath) {
  11970. if (!file_exists($filePath)) {
  11971. Utils::throwError('20003:文件不存在');
  11972. }
  11973. try {
  11974. $parser = new PdfParser();
  11975. $pdf = $parser->parseFile($filePath);
  11976. $content = $pdf->getText();
  11977. return trim($content);
  11978. } catch (\Exception $e) {
  11979. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  11980. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  11981. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  11982. }
  11983. }
  11984. /**
  11985. * 提取 Word 文件内容(支持 doc 和 docx)
  11986. */
  11987. private function extractWordContent($filePath) {
  11988. if (!file_exists($filePath)) {
  11989. Utils::throwError('20003:文件不存在');
  11990. }
  11991. try {
  11992. $phpWord = WordIOFactory::load($filePath);
  11993. $content = '';
  11994. foreach ($phpWord->getSections() as $section) {
  11995. foreach ($section->getElements() as $element) {
  11996. $content .= $this->extractWordElementText($element);
  11997. }
  11998. }
  11999. return trim($content);
  12000. } catch (\Exception $e) {
  12001. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  12002. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  12003. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  12004. }
  12005. }
  12006. /**
  12007. * 递归提取 Word 元素中的文本
  12008. */
  12009. private function extractWordElementText($element) {
  12010. $text = '';
  12011. if (method_exists($element, 'getText')) {
  12012. $text .= $element->getText() . "\n";
  12013. } elseif (method_exists($element, 'getElements')) {
  12014. foreach ($element->getElements() as $childElement) {
  12015. $text .= $this->extractWordElementText($childElement);
  12016. }
  12017. }
  12018. return $text;
  12019. }
  12020. /**
  12021. * 提取图片内容(使用火山引擎 OCR)
  12022. */
  12023. private function extractImageContent($filePath) {
  12024. if (!file_exists($filePath)) {
  12025. Utils::throwError('20003:文件不存在');
  12026. }
  12027. try {
  12028. // 读取图片并转换为 base64
  12029. $imageData = file_get_contents($filePath);
  12030. $base64Image = base64_encode($imageData);
  12031. // 调用火山引擎 OCR 服务
  12032. $content = $this->callVolcEngineOCR($base64Image);
  12033. return trim($content);
  12034. } catch (\Exception $e) {
  12035. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  12036. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  12037. Utils::throwError('20003:图片识别失败');
  12038. }
  12039. }
  12040. /**
  12041. * 调用火山引擎 OCR 服务识别图片文字
  12042. *
  12043. * @param string $base64Image base64 编码的图片数据
  12044. * @return string 识别的文字内容
  12045. */
  12046. private function callVolcEngineOCR($base64Image) {
  12047. $method = 'POST';
  12048. $service = 'cv';
  12049. $host = 'visual.volcengineapi.com';
  12050. $region = env('VOLC_REGION', 'cn-north-1');
  12051. $access_key = env('VOLC_AK');
  12052. $secret_key = env('VOLC_SK');
  12053. $action = 'OCRNormal';
  12054. $version = '2020-08-26';
  12055. if (!$access_key || !$secret_key) {
  12056. Utils::throwError('20003:请配置火山引擎 AK/SK');
  12057. }
  12058. // 请求体
  12059. $body = json_encode([
  12060. 'image_base64' => $base64Image
  12061. ]);
  12062. // 生成签名
  12063. $headers = $this->getVolcEngineSignHeaders(
  12064. $method, $service, $host, $region,
  12065. "Action={$action}&Version={$version}",
  12066. $access_key, $secret_key, $body
  12067. );
  12068. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12069. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  12070. 'headers' => $headers,
  12071. 'body' => $body
  12072. ]);
  12073. $response_arr = json_decode($response->getBody()->getContents(), true);
  12074. // 提取识别的文字
  12075. $textLines = [];
  12076. if (isset($response_arr['data']['line_texts'])) {
  12077. $textLines = $response_arr['data']['line_texts'];
  12078. } elseif (isset($response_arr['data']['ocr_infos'])) {
  12079. foreach ($response_arr['data']['ocr_infos'] as $info) {
  12080. if (isset($info['text'])) {
  12081. $textLines[] = $info['text'];
  12082. }
  12083. }
  12084. }
  12085. if (empty($textLines)) {
  12086. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  12087. return '';
  12088. }
  12089. return implode("\n", $textLines);
  12090. }
  12091. /**
  12092. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  12093. */
  12094. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  12095. $contentType = 'application/json';
  12096. $accept = 'application/json';
  12097. // 获取当前UTC时间
  12098. $t = new DateTime('now', new DateTimeZone('UTC'));
  12099. $xDate = $t->format('Ymd\THis\Z');
  12100. $dateStamp = $t->format('Ymd');
  12101. // 计算 body 的 sha256 哈希
  12102. $payloadHash = hash('sha256', $body);
  12103. // 1. 拼接规范请求串
  12104. $canonicalUri = '/';
  12105. $canonicalQueryString = $queryString;
  12106. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  12107. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  12108. $canonicalRequest = implode("\n", [
  12109. $method,
  12110. $canonicalUri,
  12111. $canonicalQueryString,
  12112. $canonicalHeaders,
  12113. $signedHeaders,
  12114. $payloadHash
  12115. ]);
  12116. // 2. 拼接待签名字符串
  12117. $algorithm = 'HMAC-SHA256';
  12118. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  12119. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  12120. $stringToSign = implode("\n", [
  12121. $algorithm,
  12122. $xDate,
  12123. $credentialScope,
  12124. $hashedCanonicalRequest
  12125. ]);
  12126. // 3. 计算签名
  12127. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  12128. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  12129. // 4. 添加签名到请求头
  12130. $authorizationHeader = sprintf(
  12131. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  12132. $algorithm,
  12133. $access_key,
  12134. $credentialScope,
  12135. $signedHeaders,
  12136. $signature
  12137. );
  12138. return [
  12139. 'Accept' => $accept,
  12140. 'Content-Type' => $contentType,
  12141. 'Host' => $host,
  12142. 'X-Date' => $xDate,
  12143. 'X-Content-Sha256'=> $payloadHash,
  12144. 'Authorization' => $authorizationHeader
  12145. ];
  12146. }
  12147. public function generateScriptWords($cid, $model = 'r1') {
  12148. ini_set('max_execution_time', 0);
  12149. if (!$cid) Utils::throwError('20003: 请选择章节!');
  12150. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  12151. // 模型兼容性处理和思考模式设置
  12152. $thinkingMode = 'disabled';
  12153. $reasoningEffort = 'high';
  12154. if ($model == 'r1') {
  12155. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  12156. $thinkingMode = 'enabled';
  12157. } else {
  12158. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  12159. $thinkingMode = 'disabled';
  12160. }
  12161. $messages = [
  12162. [
  12163. 'role' => 'system',
  12164. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  12165. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  12166. 2.非对话部分请全部用旁白角色代替
  12167. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  12168. ],
  12169. [
  12170. 'role' => 'user',
  12171. 'content' => $content
  12172. ]
  12173. ];
  12174. $post_data = [
  12175. 'model' => $model,
  12176. 'messages' => $messages,
  12177. // 'max_tokens' => 8192,
  12178. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  12179. 'frequency_penalty' => 0,
  12180. 'presence_penalty' => 0,
  12181. 'thinking' => ['type' => $thinkingMode],
  12182. 'response_format' => [
  12183. 'type' => 'text'
  12184. ],
  12185. 'stream' => false
  12186. ];
  12187. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12188. // 根据模型类型选择调用方法
  12189. $fullContent = '';
  12190. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12191. // DeepSeek 官方模型使用 DeepSeek API
  12192. $chatResult = $this->chatOnly($post_data);
  12193. } else if (in_array($model, $this->gpt_text_models)) {
  12194. // GPT-5.4 模型使用 TokenRouter API
  12195. $chatResult = $this->gpt54ChatOnly($post_data);
  12196. } else {
  12197. // 其他模型使用火山引擎API
  12198. $chatResult = $this->volcEngineChatCompletion($post_data);
  12199. }
  12200. if (is_array($chatResult)) {
  12201. $fullContent = $chatResult['fullContent'];
  12202. }
  12203. return $fullContent;
  12204. }
  12205. /**
  12206. * 智能化解析集数信息
  12207. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  12208. *
  12209. * @param string $prompt 用户输入的提示词
  12210. * @return int|null 解析出的集数,如果没有找到则返回null
  12211. */
  12212. private function extractEpisodeNumber($prompt)
  12213. {
  12214. if (empty($prompt)) {
  12215. return null;
  12216. }
  12217. // 定义各种可能的表达模式
  12218. $patterns = [
  12219. // 基本模式:改成N集、调整成N集、修改成N集
  12220. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  12221. // 扩展模式:分成N集、拆分成N集、分割成N集
  12222. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  12223. // 数量模式:N集、共N集、总共N集
  12224. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  12225. // 制作模式:制作N集、生成N集、创建N集
  12226. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  12227. // 计划模式:计划N集、预计N集、打算N集
  12228. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  12229. // 需要模式:需要N集、要N集
  12230. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  12231. // 中文数字模式:改成三集、调整成五集等
  12232. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  12233. // 英文数字模式
  12234. '/(?: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',
  12235. ];
  12236. // 中文数字转阿拉伯数字的映射
  12237. $chineseNumbers = [
  12238. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  12239. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  12240. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  12241. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  12242. ];
  12243. // 逐个尝试匹配模式
  12244. foreach ($patterns as $pattern) {
  12245. if (preg_match($pattern, $prompt, $matches)) {
  12246. $number = trim($matches[1]);
  12247. // 如果是中文数字,转换为阿拉伯数字
  12248. if (isset($chineseNumbers[$number])) {
  12249. return $chineseNumbers[$number];
  12250. }
  12251. // 如果是阿拉伯数字,直接返回
  12252. if (is_numeric($number)) {
  12253. $episodeNum = intval($number);
  12254. // 合理性检查:集数应该在1-100之间
  12255. if ($episodeNum >= 1 && $episodeNum <= 100) {
  12256. return $episodeNum;
  12257. }
  12258. }
  12259. }
  12260. }
  12261. return null;
  12262. }
  12263. /**
  12264. * 调用火山引擎对话(Chat) API
  12265. *
  12266. * @param array $params 包含以下参数:
  12267. * - model: 模型ID(必填)
  12268. * - messages: 消息列表(必填)
  12269. * - stream: 是否流式输出(可选,默认false)
  12270. * - max_tokens: 最大输出token数(可选)
  12271. * - temperature: 采样温度(可选,默认1)
  12272. * - top_p: 核采样概率(可选,默认0.7)
  12273. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  12274. * - presence_penalty: 存在惩罚系数(可选,默认0)
  12275. * - stop: 停止词(可选)
  12276. * - tools: 工具列表(可选)
  12277. * @return array|Generator 非流式返回数组,流式返回生成器
  12278. */
  12279. public function volcEngineChatCompletion(array $params)
  12280. {
  12281. $apiKey = env('VOLC_AI_API_KEY');
  12282. if (empty($apiKey)) {
  12283. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  12284. }
  12285. // 构建请求参数
  12286. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  12287. $requestData = [
  12288. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  12289. 'messages' => $params['messages'] ?? [],
  12290. ];
  12291. if (!in_array($originalModel, $this->valid_text_models)) {
  12292. Utils::throwError('20003:该模型不支持!');
  12293. }
  12294. // 添加可选参数
  12295. if (isset($params['stream'])) {
  12296. $requestData['stream'] = $params['stream'];
  12297. }
  12298. if (isset($params['stream_options'])) {
  12299. $requestData['stream_options'] = $params['stream_options'];
  12300. }
  12301. if (isset($params['max_tokens'])) {
  12302. $requestData['max_tokens'] = $params['max_tokens'];
  12303. }else if (isset($params['max_completion_tokens'])) {
  12304. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  12305. }else {
  12306. $requestData['max_completion_tokens'] = 100000;
  12307. }
  12308. if (isset($params['temperature'])) {
  12309. $requestData['temperature'] = $params['temperature'];
  12310. }
  12311. if (isset($params['top_p'])) {
  12312. $requestData['top_p'] = $params['top_p'];
  12313. }
  12314. if (isset($params['frequency_penalty'])) {
  12315. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  12316. }
  12317. if (isset($params['presence_penalty'])) {
  12318. $requestData['presence_penalty'] = $params['presence_penalty'];
  12319. }
  12320. if (isset($params['stop'])) {
  12321. $requestData['stop'] = $params['stop'];
  12322. }
  12323. if (isset($params['tools'])) {
  12324. $requestData['tools'] = $params['tools'];
  12325. }
  12326. if (isset($params['tool_choice'])) {
  12327. $requestData['tool_choice'] = $params['tool_choice'];
  12328. }
  12329. if (isset($params['response_format'])) {
  12330. $requestData['response_format'] = $params['response_format'];
  12331. }
  12332. if (isset($params['thinking'])) {
  12333. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  12334. if (is_array($params['thinking'])) {
  12335. $requestData['thinking'] = $params['thinking'];
  12336. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  12337. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12338. }
  12339. } else {
  12340. $requestData['thinking'] = ['type' => $params['thinking']];
  12341. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12342. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12343. }
  12344. }
  12345. } else {
  12346. $requestData['thinking'] = ['type' => 'disabled'];
  12347. }
  12348. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12349. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12350. try {
  12351. // 判断是否为流式输出
  12352. $isStream = isset($params['stream']) && $params['stream'] === true;
  12353. if ($isStream) {
  12354. // 流式输出
  12355. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12356. } else {
  12357. // 非流式输出
  12358. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12359. 'headers' => [
  12360. 'Authorization' => 'Bearer ' . $apiKey,
  12361. 'Content-Type' => 'application/json',
  12362. ],
  12363. 'json' => $requestData
  12364. ]);
  12365. $responseData = json_decode($response->getBody(), true);
  12366. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12367. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12368. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12369. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12370. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12371. }
  12372. return [
  12373. 'fullContent' => $fullContent,
  12374. 'fullReasoningContent' => $fullReasoningContent,
  12375. 'usage' => $usage
  12376. ];
  12377. }
  12378. } catch (\Exception $e) {
  12379. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12380. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12381. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12382. }
  12383. }
  12384. /**
  12385. * 火山引擎对话API流式输出
  12386. *
  12387. * @param Client $client HTTP客户端
  12388. * @param string $apiKey API密钥
  12389. * @param array $requestData 请求数据
  12390. * @return Generator
  12391. */
  12392. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12393. {
  12394. try {
  12395. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12396. 'headers' => [
  12397. 'Authorization' => 'Bearer ' . $apiKey,
  12398. 'Content-Type' => 'application/json',
  12399. ],
  12400. 'json' => $requestData,
  12401. 'stream' => true
  12402. ]);
  12403. $body = $response->getBody();
  12404. $buffer = '';
  12405. $fullContent = '';
  12406. $fullReasoningContent = '';
  12407. $usage = [];
  12408. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  12409. // 逐行读取流式响应
  12410. while (!$body->eof()) {
  12411. $chunk = $body->read(1024);
  12412. $buffer .= $chunk;
  12413. // 按行分割
  12414. $lines = explode("\n", $buffer);
  12415. $buffer = array_pop($lines);
  12416. foreach ($lines as $line) {
  12417. $line = trim($line);
  12418. if (empty($line)) {
  12419. continue;
  12420. }
  12421. // 检查是否是SSE数据行
  12422. if (strpos($line, 'data: ') !== 0) {
  12423. continue;
  12424. }
  12425. $data = substr($line, 6);
  12426. if ($data === '[DONE]') {
  12427. dLog('deepseek')->info('收到结束标记');
  12428. break 2;
  12429. }
  12430. try {
  12431. $json = json_decode($data, true);
  12432. if (json_last_error() !== JSON_ERROR_NONE) {
  12433. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  12434. continue;
  12435. }
  12436. if (isset($json['choices'][0]['delta'])) {
  12437. $delta = $json['choices'][0]['delta'];
  12438. // 处理思维链内容
  12439. if (isset($delta['reasoning_content'])) {
  12440. $fullReasoningContent .= $delta['reasoning_content'];
  12441. yield [
  12442. 'type' => 'reasoning',
  12443. 'content' => $delta['reasoning_content'],
  12444. 'full_reasoning' => $fullReasoningContent
  12445. ];
  12446. }
  12447. // 处理回答内容
  12448. if (isset($delta['content'])) {
  12449. $fullContent .= $delta['content'];
  12450. yield [
  12451. 'type' => 'content',
  12452. 'content' => $delta['content'],
  12453. ];
  12454. }
  12455. }
  12456. // 获取使用统计信息
  12457. if (isset($json['usage'])) {
  12458. $usage = $json['usage'];
  12459. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  12460. }
  12461. } catch (\Exception $e) {
  12462. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  12463. continue;
  12464. }
  12465. }
  12466. }
  12467. dLog('deepseek')->info('流式读取完成', [
  12468. 'content_length' => strlen($fullContent),
  12469. 'reasoning_length' => strlen($fullReasoningContent)
  12470. ]);
  12471. yield [
  12472. 'type' => 'done',
  12473. 'full_content' => $fullContent,
  12474. 'full_reasoning' => $fullReasoningContent,
  12475. 'usage' => $usage
  12476. ];
  12477. } catch (\Exception $e) {
  12478. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  12479. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  12480. throw $e;
  12481. }
  12482. }
  12483. /**
  12484. * 检查并创建图片生成任务
  12485. *
  12486. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  12487. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  12488. * @param string $nameKey 资源名称字段('role' 或 'scene')
  12489. * @param string $art_style 美术风格
  12490. * @return array 更新后的资源列表
  12491. */
  12492. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  12493. {
  12494. // 确保参数为数组
  12495. $merged_items = is_array($merged_items) ? $merged_items : [];
  12496. $global_items = is_array($global_items) ? $global_items : [];
  12497. // 构建全局资源映射表,用于快速查找
  12498. $global_map = [];
  12499. foreach ($global_items as $item) {
  12500. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12501. if ($itemKey === '') {
  12502. continue;
  12503. }
  12504. $global_map[$itemKey] = $item;
  12505. }
  12506. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  12507. foreach ($merged_items as &$item) {
  12508. $item_name = getProp($item, $nameKey);
  12509. $item_description = getProp($item, 'description');
  12510. // $item_url = getProp($item, 'url');
  12511. // // 如果已有图片URL,跳过
  12512. // if (!empty($item_url)) {
  12513. // continue;
  12514. // }
  12515. // 如果是旁白角色,跳过
  12516. if ($nameKey === 'role' && $item_name === '旁白') {
  12517. continue;
  12518. }
  12519. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  12520. if ($itemKey === '') {
  12521. continue;
  12522. }
  12523. $need_create_task = false;
  12524. // 条件1:在全局资源中找不到匹配的名称
  12525. if (!isset($global_map[$itemKey])) {
  12526. $need_create_task = true;
  12527. } else {
  12528. // 条件2:名称匹配但描述或 pic_prompt 不一致
  12529. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  12530. $current_description = trim((string)$item_description);
  12531. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  12532. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  12533. // 如果 description 或 pic_prompt 有变化,需要重新生成
  12534. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  12535. $need_create_task = true;
  12536. }
  12537. }
  12538. // 如果需要创建任务,调用图片生成服务
  12539. if ($need_create_task) {
  12540. try {
  12541. // 优先使用 pic_prompt,如果没有则使用 description
  12542. $pic_prompt = getProp($item, 'pic_prompt');
  12543. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  12544. // 添加美术风格前缀
  12545. if ($art_style) {
  12546. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  12547. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  12548. $description = "{$prefix}:{$description}";
  12549. }
  12550. $params = [
  12551. 'prompt' => $description,
  12552. 'ref_img_urls' => []
  12553. ];
  12554. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12555. $task_id = $task->id;
  12556. if ($task_id) {
  12557. $item['task_id'] = $task_id;
  12558. $item['task_status'] = 'processing';
  12559. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12560. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  12561. }
  12562. } catch (\Exception $e) {
  12563. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12564. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  12565. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  12566. // 不抛出异常,继续处理其他资源
  12567. }
  12568. }
  12569. }
  12570. return $merged_items;
  12571. }
  12572. /**
  12573. * 同步新出现的主体和场景到全局
  12574. *
  12575. * @param int $anime_id 动漫ID
  12576. * @param array $merged_roles 合并后的角色列表
  12577. * @param array $merged_scenes 合并后的场景列表
  12578. * @param array $global_roles 全局角色列表
  12579. * @param array $global_scenes 全局场景列表
  12580. * @return void
  12581. */
  12582. private function syncNewResourcesToGlobal(
  12583. int $anime_id,
  12584. array $merged_roles,
  12585. array $merged_scenes,
  12586. array $global_roles,
  12587. array $global_scenes
  12588. ): void {
  12589. // 构建全局角色映射表
  12590. $global_role_map = [];
  12591. foreach ($global_roles as $role) {
  12592. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  12593. if ($roleKey !== '') {
  12594. $global_role_map[$roleKey] = $role;
  12595. }
  12596. }
  12597. // 构建全局场景映射表
  12598. $global_scene_map = [];
  12599. foreach ($global_scenes as $scene) {
  12600. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  12601. if ($sceneKey !== '') {
  12602. $global_scene_map[$sceneKey] = $scene;
  12603. }
  12604. }
  12605. $need_update = false;
  12606. $new_global_roles = $global_roles;
  12607. $new_global_scenes = $global_scenes;
  12608. // 检查并添加新角色到全局
  12609. foreach ($merged_roles as $role) {
  12610. $role_name = getProp($role, 'role');
  12611. // 跳过旁白
  12612. if ($role_name === '旁白') {
  12613. continue;
  12614. }
  12615. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  12616. if ($roleKey === '') {
  12617. continue;
  12618. }
  12619. // 如果全局中不存在该角色,添加到全局
  12620. if (!isset($global_role_map[$roleKey])) {
  12621. $new_global_roles[] = [
  12622. 'role' => $role_name,
  12623. 'description' => getProp($role, 'description', ''),
  12624. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  12625. 'voice_name' => getProp($role, 'voice_name', ''),
  12626. 'voice_type' => getProp($role, 'voice_type', ''),
  12627. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  12628. 'url' => getProp($role, 'url', ''),
  12629. 'task_id' => getProp($role, 'task_id', ''),
  12630. 'task_status' => getProp($role, 'task_status', ''),
  12631. ];
  12632. $global_role_map[$roleKey] = true; // 标记已添加
  12633. $need_update = true;
  12634. dLog('deepseek')->info("新角色同步到全局", [
  12635. 'anime_id' => $anime_id,
  12636. 'role' => $role_name,
  12637. 'task_id' => getProp($role, 'task_id', ''),
  12638. ]);
  12639. }
  12640. // else {
  12641. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12642. // $global_role = $global_role_map[$roleKey];
  12643. // if (is_array($global_role)) {
  12644. // $updated = false;
  12645. // $update_fields = [];
  12646. // // 检查描述是否更新
  12647. // $current_description = trim((string)getProp($role, 'description'));
  12648. // $global_description = trim((string)getProp($global_role, 'description'));
  12649. // if ($current_description !== '' && $current_description !== $global_description) {
  12650. // $updated = true;
  12651. // $update_fields[] = 'description';
  12652. // }
  12653. // // 检查pic_prompt是否更新
  12654. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  12655. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  12656. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12657. // $updated = true;
  12658. // $update_fields[] = 'pic_prompt';
  12659. // }
  12660. // // 检查图片任务信息是否更新
  12661. // $current_task_id = getProp($role, 'task_id');
  12662. // $global_task_id = getProp($global_role, 'task_id');
  12663. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12664. // $updated = true;
  12665. // $update_fields[] = 'task_id';
  12666. // }
  12667. // // 如果有更新,同步到全局
  12668. // if ($updated) {
  12669. // foreach ($new_global_roles as &$global_role_item) {
  12670. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  12671. // if ($global_role_key === $roleKey) {
  12672. // if (in_array('description', $update_fields)) {
  12673. // $global_role_item['description'] = $current_description;
  12674. // }
  12675. // if (in_array('pic_prompt', $update_fields)) {
  12676. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  12677. // }
  12678. // if (in_array('task_id', $update_fields)) {
  12679. // $global_role_item['task_id'] = $current_task_id;
  12680. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  12681. // $global_role_item['url'] = getProp($role, 'url', '');
  12682. // }
  12683. // break;
  12684. // }
  12685. // }
  12686. // $need_update = true;
  12687. // dLog('deepseek')->info("角色信息更新到全局", [
  12688. // 'anime_id' => $anime_id,
  12689. // 'role' => $role_name,
  12690. // 'update_fields' => implode(',', $update_fields),
  12691. // ]);
  12692. // }
  12693. // }
  12694. // }
  12695. }
  12696. // 检查并添加新场景到全局
  12697. foreach ($merged_scenes as $scene) {
  12698. $scene_name = getProp($scene, 'scene');
  12699. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  12700. if ($sceneKey === '') {
  12701. continue;
  12702. }
  12703. // 如果全局中不存在该场景,添加到全局
  12704. if (!isset($global_scene_map[$sceneKey])) {
  12705. $new_global_scenes[] = [
  12706. 'scene' => $scene_name,
  12707. 'description' => getProp($scene, 'description', ''),
  12708. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  12709. 'url' => getProp($scene, 'url', ''),
  12710. 'task_id' => getProp($scene, 'task_id', ''),
  12711. 'task_status' => getProp($scene, 'task_status', ''),
  12712. ];
  12713. $global_scene_map[$sceneKey] = true; // 标记已添加
  12714. $need_update = true;
  12715. dLog('deepseek')->info("新场景同步到全局", [
  12716. 'anime_id' => $anime_id,
  12717. 'scene' => $scene_name,
  12718. 'task_id' => getProp($scene, 'task_id', ''),
  12719. ]);
  12720. }
  12721. // else {
  12722. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12723. // $global_scene = $global_scene_map[$sceneKey];
  12724. // if (is_array($global_scene)) {
  12725. // $updated = false;
  12726. // $update_fields = [];
  12727. // // 检查描述是否更新
  12728. // $current_description = trim((string)getProp($scene, 'description'));
  12729. // $global_description = trim((string)getProp($global_scene, 'description'));
  12730. // if ($current_description !== '' && $current_description !== $global_description) {
  12731. // $updated = true;
  12732. // $update_fields[] = 'description';
  12733. // }
  12734. // // 检查pic_prompt是否更新
  12735. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  12736. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  12737. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12738. // $updated = true;
  12739. // $update_fields[] = 'pic_prompt';
  12740. // }
  12741. // // 检查图片任务信息是否更新
  12742. // $current_task_id = getProp($scene, 'task_id');
  12743. // $global_task_id = getProp($global_scene, 'task_id');
  12744. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12745. // $updated = true;
  12746. // $update_fields[] = 'task_id';
  12747. // }
  12748. // // 如果有更新,同步到全局
  12749. // if ($updated) {
  12750. // foreach ($new_global_scenes as &$global_scene_item) {
  12751. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  12752. // if ($global_scene_key === $sceneKey) {
  12753. // if (in_array('description', $update_fields)) {
  12754. // $global_scene_item['description'] = $current_description;
  12755. // }
  12756. // if (in_array('pic_prompt', $update_fields)) {
  12757. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  12758. // }
  12759. // if (in_array('task_id', $update_fields)) {
  12760. // $global_scene_item['task_id'] = $current_task_id;
  12761. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  12762. // $global_scene_item['url'] = getProp($scene, 'url', '');
  12763. // }
  12764. // break;
  12765. // }
  12766. // }
  12767. // $need_update = true;
  12768. // dLog('deepseek')->info("场景信息更新到全局", [
  12769. // 'anime_id' => $anime_id,
  12770. // 'scene' => $scene_name,
  12771. // 'update_fields' => implode(',', $update_fields),
  12772. // ]);
  12773. // }
  12774. // }
  12775. // }
  12776. }
  12777. // 如果有新增或更新,更新数据库
  12778. if ($need_update) {
  12779. $update_data = [
  12780. 'roles' => json_encode($new_global_roles, 256),
  12781. 'scenes' => json_encode($new_global_scenes, 256),
  12782. 'updated_at' => date('Y-m-d H:i:s'),
  12783. ];
  12784. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12785. if ($result !== false) {
  12786. dLog('deepseek')->info("全局角色和场景更新成功", [
  12787. 'anime_id' => $anime_id,
  12788. 'roles_count' => count($new_global_roles),
  12789. 'scenes_count' => count($new_global_scenes),
  12790. ]);
  12791. } else {
  12792. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  12793. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  12794. }
  12795. }
  12796. }
  12797. }